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/NSURL_NSURLExtras.h>
53 #import <Foundation/NSURLFileTypeMappings.h>
55 #import <CoreGraphics/CGContextGState.h>
57 // Included to help work around this bug:
58 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
59 #import <AppKit/NSKeyBindingManager.h>
61 // Included so usage of _NSSoftLinkingGetFrameworkFuncPtr will compile
62 #import <mach-o/dyld.h>
65 // need to declare this because AppKit does not make it available as API or SPI
66 extern NSString *NSMarkedClauseSegmentAttributeName;
67 extern NSString *NSTextInputReplacementRangeAttributeName;
69 // Kill ring calls. Would be better to use NSKillRing.h, but that's not available in SPI.
70 void _NSInitializeKillRing(void);
71 void _NSAppendToKillRing(NSString *);
72 void _NSPrependToKillRing(NSString *);
73 NSString *_NSYankFromKillRing(void);
74 NSString *_NSYankPreviousFromKillRing(void);
75 void _NSNewKillRingSequence(void);
76 void _NSSetKillRingToYankedState(void);
77 void _NSResetKillRingOperationFlag(void);
79 @interface NSView (AppKitSecretsIKnowAbout)
80 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
81 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
83 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
84 - (void)_propagateDirtyRectsToOpaqueAncestors;
87 @interface NSApplication (AppKitSecretsIKnowAbout)
88 - (void)speakString:(NSString *)string;
91 @interface NSWindow (AppKitSecretsIKnowAbout)
92 - (id)_newFirstResponderAfterResigning;
95 @interface NSAttributedString (AppKitSecretsIKnowAbout)
96 - (id)_initWithDOMRange:(DOMRange *)domRange;
97 - (DOMDocumentFragment *)_documentFromRange:(NSRange)range document:(DOMDocument *)document documentAttributes:(NSDictionary *)dict subresources:(NSArray **)subresources;
100 @interface NSSpellChecker (CurrentlyPrivateForTextView)
101 - (void)learnWord:(NSString *)word;
104 // By imaging to a width a little wider than the available pixels,
105 // thin pages will be scaled down a little, matching the way they
106 // print in IE and Camino. This lets them use fewer sheets than they
107 // would otherwise, which is presumably why other browsers do this.
108 // Wide pages will be scaled down more than this.
109 #define PrintingMinimumShrinkFactor 1.25
111 // This number determines how small we are willing to reduce the page content
112 // in order to accommodate the widest line. If the page would have to be
113 // reduced smaller to make the widest line fit, we just clip instead (this
114 // behavior matches MacIE and Mozilla, at least)
115 #define PrintingMaximumShrinkFactor 2.0
117 #define AUTOSCROLL_INTERVAL 0.1
119 #define DRAG_LABEL_BORDER_X 4.0
120 #define DRAG_LABEL_BORDER_Y 2.0
121 #define DRAG_LABEL_RADIUS 5.0
122 #define DRAG_LABEL_BORDER_Y_OFFSET 2.0
124 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP 120.0
125 #define MAX_DRAG_LABEL_WIDTH 320.0
127 #define DRAG_LINK_LABEL_FONT_SIZE 11.0
128 #define DRAG_LINK_URL_FONT_SIZE 10.0
130 #ifndef OMIT_TIGER_FEATURES
131 #define USE_APPKIT_FOR_ATTRIBUTED_STRINGS
134 // Any non-zero value will do, but using something recognizable might help us debug some day.
135 #define TRACKING_RECT_TAG 0xBADFACE
137 // FIXME: This constant is copied from AppKit's _NXSmartPaste constant.
138 #define WebSmartPastePboardType @"NeXT smart paste pasteboard type"
140 #define STANDARD_WEIGHT 5
141 #define MIN_BOLD_WEIGHT 9
142 #define STANDARD_BOLD_WEIGHT 10
145 deleteSelectionAction,
147 forwardDeleteKeyAction
150 static BOOL forceRealHitTest = NO;
152 // Used to avoid linking with ApplicationServices framework for _DCMDictionaryServiceWindowShow
153 void *_NSSoftLinkingGetFrameworkFuncPtr(NSString *inUmbrellaFrameworkName,
154 NSString *inFrameworkName,
155 const char *inFuncName,
156 const struct mach_header **ioCachedFrameworkImageHeaderPtr);
159 @interface WebHTMLView (WebTextSizing) <_web_WebDocumentTextSizing>
162 @interface WebHTMLView (WebHTMLViewFileInternal)
163 - (BOOL)_imageExistsAtPaths:(NSArray *)paths;
164 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText chosePlainText:(BOOL *)chosePlainText;
165 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
166 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
167 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action;
168 - (float)_calculatePrintHeight;
169 - (void)_updateTextSizeMultiplier;
170 - (DOMRange *)_selectedRange;
171 - (BOOL)_shouldDeleteRange:(DOMRange *)range;
172 - (void)_deleteRange:(DOMRange *)range
173 killRing:(BOOL)killRing
174 prepend:(BOOL)prepend
175 smartDeleteOK:(BOOL)smartDeleteOK
176 deletionAction:(WebDeletionAction)deletionAction;
177 - (void)_deleteSelection;
178 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard;
179 - (NSView *)_hitViewForEvent:(NSEvent *)event;
180 - (void)_writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard cachedAttributedString:(NSAttributedString *)attributedString;
183 @interface WebHTMLView (WebForwardDeclaration) // FIXME: Put this in a normal category and stop doing the forward declaration trick.
184 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize;
187 @interface WebHTMLView (WebNSTextInputSupport) <NSTextInput>
188 - (void)_updateSelectionForInputManager;
189 - (void)_insertText:(NSString *)text selectInsertedText:(BOOL)selectText;
192 @interface WebHTMLView (WebEditingStyleSupport)
193 - (DOMCSSStyleDeclaration *)_emptyStyle;
194 - (NSString *)_colorAsString:(NSColor *)color;
197 @interface NSView (WebHTMLViewFileInternal)
198 - (void)_web_setPrintingModeRecursive;
199 - (void)_web_clearPrintingModeRecursive;
200 - (void)_web_layoutIfNeededRecursive;
201 - (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
204 @interface NSMutableDictionary (WebHTMLViewFileInternal)
205 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
208 // Handles the complete: text command
209 @interface WebTextCompleteController : NSObject
213 NSWindow *_popupWindow;
214 NSTableView *_tableView;
215 NSArray *_completions;
216 NSString *_originalString;
219 - (id)initWithHTMLView:(WebHTMLView *)view;
220 - (void)doCompletion;
221 - (void)endRevertingChange:(BOOL)revertChange moveLeft:(BOOL)goLeft;
222 - (BOOL)filterKeyDown:(NSEvent *)event;
223 - (void)_reflectSelection;
226 @implementation WebHTMLViewPrivate
230 ASSERT(autoscrollTimer == nil);
231 ASSERT(autoscrollTriggerEvent == nil);
233 [mouseDownEvent release];
234 [draggingImageURL release];
235 [pluginController release];
237 [compController release];
238 [firstResponderAtMouseDownTime release];
245 @implementation WebHTMLView (WebHTMLViewFileInternal)
247 - (BOOL)_imageExistsAtPaths:(NSArray *)paths
249 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
250 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
251 NSEnumerator *enumerator = [paths objectEnumerator];
254 while ((path = [enumerator nextObject]) != nil) {
255 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
256 if ([imageMIMETypes containsObject:MIMEType]) {
264 - (DOMDocumentFragment *)_documentFragmentWithPaths:(NSArray *)paths
266 DOMDocumentFragment *fragment = [[[self _bridge] DOMDocument] createDocumentFragment];
267 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
268 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
269 NSEnumerator *enumerator = [paths objectEnumerator];
270 WebDataSource *dataSource = [self _dataSource];
273 while ((path = [enumerator nextObject]) != nil) {
274 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
275 if ([imageMIMETypes containsObject:MIMEType]) {
276 WebResource *resource = [[WebResource alloc] initWithData:[NSData dataWithContentsOfFile:path]
277 URL:[NSURL fileURLWithPath:path]
282 [fragment appendChild:[dataSource _imageElementWithImageResource:resource]];
288 return [fragment firstChild] != nil ? fragment : nil;
291 + (NSArray *)_excludedElementsForAttributedStringConversion
293 static NSArray *elements = nil;
294 if (elements == nil) {
295 elements = [[NSArray alloc] initWithObjects:
296 // Omit style since we want style to be inline so the fragment can be easily inserted.
298 // Omit xml so the result is not XHTML.
300 // Omit tags that will get stripped when converted to a fragment anyway.
301 @"doctype", @"html", @"head", @"body",
302 // Omit deprecated tags.
303 @"applet", @"basefont", @"center", @"dir", @"font", @"isindex", @"menu", @"s", @"strike", @"u",
304 // Omit object so no file attachments are part of the fragment.
310 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText chosePlainText:(BOOL *)chosePlainText
312 NSArray *types = [pasteboard types];
313 *chosePlainText = NO;
315 if ([types containsObject:WebArchivePboardType]) {
316 WebArchive *archive = [[WebArchive alloc] initWithData:[pasteboard dataForType:WebArchivePboardType]];
318 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithArchive:archive];
326 if ([types containsObject:NSFilenamesPboardType]) {
327 DOMDocumentFragment *fragment = [self _documentFragmentWithPaths:[pasteboard propertyListForType:NSFilenamesPboardType]];
328 if (fragment != nil) {
335 if ([types containsObject:NSHTMLPboardType]) {
336 NSString *HTMLString = [pasteboard stringForType:NSHTMLPboardType];
337 // This is a hack to make Microsoft's HTML pasteboard data work. See 3778785.
338 if ([HTMLString hasPrefix:@"Version:"]) {
339 NSRange range = [HTMLString rangeOfString:@"<html" options:NSCaseInsensitiveSearch];
340 if (range.location != NSNotFound) {
341 HTMLString = [HTMLString substringFromIndex:range.location];
344 if ([HTMLString length] != 0) {
345 return [[self _bridge] documentFragmentWithMarkupString:HTMLString baseURLString:nil];
349 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
350 NSAttributedString *string = nil;
351 if ([types containsObject:NSRTFDPboardType]) {
352 string = [[NSAttributedString alloc] initWithRTFD:[pasteboard dataForType:NSRTFDPboardType] documentAttributes:NULL];
354 if (string == nil && [types containsObject:NSRTFPboardType]) {
355 string = [[NSAttributedString alloc] initWithRTF:[pasteboard dataForType:NSRTFPboardType] documentAttributes:NULL];
358 NSDictionary *documentAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:
359 [[self class] _excludedElementsForAttributedStringConversion], NSExcludedElementsDocumentAttribute,
360 self, @"WebResourceHandler", nil];
361 NSArray *subresources;
362 DOMDocumentFragment *fragment = [string _documentFromRange:NSMakeRange(0, [string length])
363 document:[[self _bridge] DOMDocument]
364 documentAttributes:documentAttributes
365 subresources:&subresources];
366 [documentAttributes release];
372 if ([types containsObject:NSTIFFPboardType]) {
373 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSTIFFPboardType]
374 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.tiff"]
375 MIMEType:@"image/tiff"
378 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
383 if ([types containsObject:NSPICTPboardType]) {
384 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSPICTPboardType]
385 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.pict"]
386 MIMEType:@"image/pict"
389 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
394 if ((URL = [NSURL URLFromPasteboard:pasteboard])) {
395 NSString *URLString = [URL _web_userVisibleString];
396 if ([URLString length] > 0) {
397 return [[self _bridge] documentFragmentWithText:URLString];
401 if (allowPlainText && [types containsObject:NSStringPboardType]) {
402 *chosePlainText = YES;
403 return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
409 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
410 - (WebResource *)resourceForData:(NSData *)data preferredFilename:(NSString *)name
412 // This method is called by [NSAttributedString _documentFromRange::::]
413 // which uses the URL of the resource for the fragment that it returns.
414 NSString *extension = [name pathExtension];
415 NSString *MIMEType = nil;
416 if ([extension length] != 0) {
417 MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
419 // Only support image resources.
420 if (MIMEType == nil || ![[[WebImageRendererFactory sharedFactory] supportedMIMETypes] containsObject:MIMEType]) {
423 NSURL *URL = [NSURL _web_URLWithUserTypedString:[NSString stringWithFormat:@"/%@", name] relativeToURL:[NSURL _web_uniqueWebDataURL]];
424 WebResource *resource = [[[WebResource alloc] initWithData:data
428 frameName:nil] autorelease];
429 [[self _dataSource] addSubresource:resource];
434 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
437 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:allowPlainText chosePlainText:&chosePlainText];
438 WebBridge *bridge = [self _bridge];
439 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[self _selectedRange] givenAction:WebViewInsertActionPasted]) {
440 [bridge replaceSelectionWithFragment:fragment selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard] matchStyle:chosePlainText];
444 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
446 WebView *webView = [self _webView];
447 DOMNode *child = [fragment firstChild];
448 if ([fragment lastChild] == child && [child isKindOfClass:[DOMCharacterData class]]) {
449 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:[(DOMCharacterData *)child data] replacingDOMRange:range givenAction:action];
451 return [[webView _editingDelegateForwarder] webView:webView shouldInsertNode:fragment replacingDOMRange:range givenAction:action];
455 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action
457 WebView *webView = [self _webView];
458 DOMRange *selectedRange = [self _selectedRange];
459 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:selectedRange givenAction:action];
462 // Calculate the vertical size of the view that fits on a single page
463 - (float)_calculatePrintHeight
465 // Obtain the print info object for the current operation
466 NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
468 // Calculate the page height in points
469 NSSize paperSize = [pi paperSize];
470 return paperSize.height - [pi topMargin] - [pi bottomMargin];
473 - (void)_updateTextSizeMultiplier
475 [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];
478 - (DOMRange *)_selectedRange
480 return [[self _bridge] selectedDOMRange];
483 - (BOOL)_shouldDeleteRange:(DOMRange *)range
485 if (range == nil || [range collapsed])
488 if (![[self _bridge] canDeleteRange:range])
491 WebView *webView = [self _webView];
492 return [[webView _editingDelegateForwarder] webView:webView shouldDeleteDOMRange:range];
495 - (void)_deleteRange:(DOMRange *)range
496 killRing:(BOOL)killRing
497 prepend:(BOOL)prepend
498 smartDeleteOK:(BOOL)smartDeleteOK
499 deletionAction:(WebDeletionAction)deletionAction
501 if (![self _shouldDeleteRange:range]) {
505 WebBridge *bridge = [self _bridge];
506 BOOL smartDelete = smartDeleteOK ? [self _canSmartCopyOrDelete] : NO;
508 BOOL startNewKillRingSequence = _private->startNewKillRingSequence;
511 if (startNewKillRingSequence) {
512 _NSNewKillRingSequence();
514 NSString *string = [bridge stringForRange:range];
516 _NSPrependToKillRing(string);
518 _NSAppendToKillRing(string);
520 startNewKillRingSequence = NO;
523 switch (deletionAction) {
524 case deleteSelectionAction:
525 [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:YES];
526 [bridge deleteSelectionWithSmartDelete:smartDelete];
528 case deleteKeyAction:
529 [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:NO];
530 [bridge deleteKeyPressedWithSmartDelete:smartDelete];
532 case forwardDeleteKeyAction:
533 [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:NO];
534 [bridge forwardDeleteKeyPressedWithSmartDelete:smartDelete];
538 _private->startNewKillRingSequence = startNewKillRingSequence;
541 - (void)_deleteSelection
543 [self _deleteRange:[self _selectedRange]
547 deletionAction:deleteSelectionAction];
550 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard
552 return [[self _webView] smartInsertDeleteEnabled] && [[pasteboard types] containsObject:WebSmartPastePboardType];
555 - (NSView *)_hitViewForEvent:(NSEvent *)event
557 // Usually, we hack AK's hitTest method to catch all events at the topmost WebHTMLView.
558 // Callers of this method, however, want to query the deepest view instead.
559 forceRealHitTest = YES;
560 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
561 forceRealHitTest = NO;
565 // This method is copied from NSTextView
566 - (NSAttributedString *)_stripAttachmentCharactersFromAttributedString:(NSAttributedString *)originalAttributedString
568 NSRange attachmentRange;
569 NSString *originalString = [originalAttributedString string];
570 static NSString *attachmentCharString = nil;
572 if (!attachmentCharString) {
574 if (!attachmentCharString) {
575 chars[0] = NSAttachmentCharacter;
577 attachmentCharString = [[NSString alloc] initWithCharacters:chars length:1];
581 attachmentRange = [originalString rangeOfString:attachmentCharString];
582 if (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
583 NSMutableAttributedString *newAttributedString = [[originalAttributedString mutableCopyWithZone:NULL] autorelease];
585 while (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
586 [newAttributedString replaceCharactersInRange:attachmentRange withString:@""];
587 attachmentRange = [[newAttributedString string] rangeOfString:attachmentCharString];
589 return newAttributedString;
591 return originalAttributedString;
595 - (void)_writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard cachedAttributedString:(NSAttributedString *)attributedString
597 // Put HTML on the pasteboard.
598 if ([types containsObject:WebArchivePboardType]) {
599 WebArchive *archive = [self _selectedArchive];
600 [pasteboard setData:[archive data] forType:WebArchivePboardType];
603 // Put the attributed string on the pasteboard (RTF/RTFD format).
604 if ([types containsObject:NSRTFDPboardType]) {
605 if (attributedString == nil) {
606 attributedString = [self selectedAttributedString];
608 NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
609 [pasteboard setData:RTFDData forType:NSRTFDPboardType];
611 if ([types containsObject:NSRTFPboardType]) {
612 if (attributedString == nil) {
613 attributedString = [self selectedAttributedString];
615 if ([attributedString containsAttachments]) {
616 attributedString = [self _stripAttachmentCharactersFromAttributedString:attributedString];
618 NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
619 [pasteboard setData:RTFData forType:NSRTFPboardType];
622 // Put plain string on the pasteboard.
623 if ([types containsObject:NSStringPboardType]) {
624 // Map to a plain old space because this is better for source code, other browsers do it,
625 // and because HTML forces you to do this any time you want two spaces in a row.
626 NSMutableString *s = [[self selectedString] mutableCopy];
627 const unichar NonBreakingSpaceCharacter = 0xA0;
628 NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
629 [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
630 [pasteboard setString:s forType:NSStringPboardType];
634 if ([self _canSmartCopyOrDelete] && [types containsObject:WebSmartPastePboardType]) {
635 [pasteboard setData:nil forType:WebSmartPastePboardType];
641 @implementation WebHTMLView (WebPrivate)
645 [WebImageRenderer stopAnimationsInView:self];
648 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
650 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
651 location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
652 modifierFlags:[flagsChangedEvent modifierFlags]
653 timestamp:[flagsChangedEvent timestamp]
654 windowNumber:[flagsChangedEvent windowNumber]
655 context:[flagsChangedEvent context]
656 eventNumber:0 clickCount:0 pressure:0];
658 // Pretend it's a mouse move.
659 [[NSNotificationCenter defaultCenter]
660 postNotificationName:NSMouseMovedNotification object:self
661 userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
664 - (void)_updateMouseoverWithFakeEvent
666 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
667 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
668 modifierFlags:[[NSApp currentEvent] modifierFlags]
669 timestamp:[NSDate timeIntervalSinceReferenceDate]
670 windowNumber:[[self window] windowNumber]
671 context:[[NSApp currentEvent] context]
672 eventNumber:0 clickCount:0 pressure:0];
674 [self _updateMouseoverWithEvent:fakeEvent];
677 - (void)_frameOrBoundsChanged
679 if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
680 [self setNeedsLayout:YES];
681 [self setNeedsDisplay:YES];
682 [_private->compController endRevertingChange:NO moveLeft:NO];
685 NSPoint origin = [[self superview] bounds].origin;
686 if (!NSEqualPoints(_private->lastScrollPosition, origin)) {
687 [[self _bridge] sendScrollEvent];
688 [_private->compController endRevertingChange:NO moveLeft:NO];
690 _private->lastScrollPosition = origin;
692 SEL selector = @selector(_updateMouseoverWithFakeEvent);
693 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
694 [self performSelector:selector withObject:nil afterDelay:0];
697 - (void)_setAsideSubviews
699 ASSERT(!_private->subviewsSetAside);
700 ASSERT(_private->savedSubviews == nil);
701 _private->savedSubviews = _subviews;
703 _private->subviewsSetAside = YES;
706 - (void)_restoreSubviews
708 ASSERT(_private->subviewsSetAside);
709 ASSERT(_subviews == nil);
710 _subviews = _private->savedSubviews;
711 _private->savedSubviews = nil;
712 _private->subviewsSetAside = NO;
715 // This is called when we are about to draw, but before our dirty rect is propagated to our ancestors.
716 // That's the perfect time to do a layout, except that ideally we'd want to be sure that we're dirty
717 // before doing it. As a compromise, when we're opaque we do the layout only when actually asked to
718 // draw, but when we're transparent we do the layout at this stage so views behind us know that they
719 // need to be redrawn (in case the layout causes some things to get dirtied).
720 - (void)_propagateDirtyRectsToOpaqueAncestors
722 if (![[self _webView] drawsBackground]) {
723 [self _web_layoutIfNeededRecursive];
725 [super _propagateDirtyRectsToOpaqueAncestors];
728 // Don't let AppKit even draw subviews. We take care of that.
729 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
731 // This helps when we print as part of a larger print process.
732 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
733 BOOL wasInPrintingMode = _private->printing;
734 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
735 if (wasInPrintingMode != isPrinting) {
737 [self _web_setPrintingModeRecursive];
739 [self _web_clearPrintingModeRecursive];
743 [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
745 [self _setAsideSubviews];
746 [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
747 rectIsVisibleRectForView:visibleView topView:topView];
748 [self _restoreSubviews];
750 if (wasInPrintingMode != isPrinting) {
751 if (wasInPrintingMode) {
752 [self _web_setPrintingModeRecursive];
754 [self _web_clearPrintingModeRecursive];
759 // Don't let AppKit even draw subviews. We take care of that.
760 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
762 BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
764 BOOL wasInPrintingMode = _private->printing;
765 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
767 if (needToSetAsideSubviews) {
768 // This helps when we print as part of a larger print process.
769 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
770 if (wasInPrintingMode != isPrinting) {
772 [self _web_setPrintingModeRecursive];
774 [self _web_clearPrintingModeRecursive];
778 NSRect boundsBeforeLayout = [self bounds];
779 [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
781 // If layout changes the view's bounds, then we need to recompute the visRect.
782 // That's because the visRect passed to us was based on the bounds at the time
783 // we were called. This method is only displayed to draw "all", so it's safe
784 // to just call visibleRect to compute the entire rectangle.
785 if (!NSEqualRects(boundsBeforeLayout, [self bounds])) {
786 visRect = [self visibleRect];
789 [self _setAsideSubviews];
792 [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
794 if (needToSetAsideSubviews) {
795 if (wasInPrintingMode != isPrinting) {
796 if (wasInPrintingMode) {
797 [self _web_setPrintingModeRecursive];
799 [self _web_clearPrintingModeRecursive];
803 [self _restoreSubviews];
807 - (BOOL)_insideAnotherHTMLView
810 while ((view = [view superview])) {
811 if ([view isKindOfClass:[WebHTMLView class]]) {
818 - (void)scrollPoint:(NSPoint)point
820 // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
821 // If we get called during the handling of a key down event, we assume the call came from
822 // NSTextView, and ignore it and use our own code to decide how to page up and page down
823 // We are smarter about how far to scroll, and we have "superview scrolling" logic.
824 NSEvent *event = [[self window] currentEvent];
825 if ([event type] == NSKeyDown) {
826 const unichar pageUp = NSPageUpFunctionKey;
827 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
828 [self tryToPerform:@selector(scrollPageUp:) with:nil];
831 const unichar pageDown = NSPageDownFunctionKey;
832 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
833 [self tryToPerform:@selector(scrollPageDown:) with:nil];
838 [super scrollPoint:point];
841 - (NSView *)hitTest:(NSPoint)point
843 // WebHTMLView objects handle all left mouse clicks for objects inside them.
844 // That does not include left mouse clicks with the control key held down.
845 BOOL captureHitsOnSubviews;
846 if (forceRealHitTest) {
847 captureHitsOnSubviews = NO;
849 NSEvent *event = [[self window] currentEvent];
850 captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
852 if (!captureHitsOnSubviews) {
853 return [super hitTest:point];
855 if ([[self superview] mouse:point inRect:[self frame]]) {
861 static WebHTMLView *lastHitView = nil;
863 - (void)_clearLastHitViewIfSelf
865 if (lastHitView == self) {
870 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
872 ASSERT(_private->trackingRectOwner == nil);
873 _private->trackingRectOwner = owner;
874 _private->trackingRectUserData = data;
875 return TRACKING_RECT_TAG;
878 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
880 ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
881 ASSERT(_private->trackingRectOwner == nil);
882 _private->trackingRectOwner = owner;
883 _private->trackingRectUserData = data;
884 return TRACKING_RECT_TAG;
887 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
890 ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
891 ASSERT(_private->trackingRectOwner == nil);
892 _private->trackingRectOwner = owner;
893 _private->trackingRectUserData = userDataList[0];
894 trackingNums[0] = TRACKING_RECT_TAG;
897 - (void)removeTrackingRect:(NSTrackingRectTag)tag
901 ASSERT(tag == TRACKING_RECT_TAG);
902 if (_private != nil) {
903 _private->trackingRectOwner = nil;
907 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
910 for (i = 0; i < count; ++i) {
914 ASSERT(tag == TRACKING_RECT_TAG);
915 if (_private != nil) {
916 _private->trackingRectOwner = nil;
921 - (void)_sendToolTipMouseExited
923 // Nothing matters except window, trackingNumber, and userData.
924 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
925 location:NSMakePoint(0, 0)
928 windowNumber:[[self window] windowNumber]
931 trackingNumber:TRACKING_RECT_TAG
932 userData:_private->trackingRectUserData];
933 [_private->trackingRectOwner mouseExited:fakeEvent];
936 - (void)_sendToolTipMouseEntered
938 // Nothing matters except window, trackingNumber, and userData.
939 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
940 location:NSMakePoint(0, 0)
943 windowNumber:[[self window] windowNumber]
946 trackingNumber:TRACKING_RECT_TAG
947 userData:_private->trackingRectUserData];
948 [_private->trackingRectOwner mouseEntered:fakeEvent];
951 - (void)_setToolTip:(NSString *)string
953 NSString *toolTip = [string length] == 0 ? nil : string;
954 NSString *oldToolTip = _private->toolTip;
955 if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
959 [self _sendToolTipMouseExited];
960 [oldToolTip release];
962 _private->toolTip = [toolTip copy];
964 [self removeAllToolTips];
965 NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
966 [self addToolTipRect:wideOpenRect owner:self userData:NULL];
967 [self _sendToolTipMouseEntered];
971 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
973 return [[_private->toolTip copy] autorelease];
976 - (void)_updateMouseoverWithEvent:(NSEvent *)event
980 WebHTMLView *view = nil;
981 if ([event window] == [self window]) {
982 NSView *hitView = [self _hitViewForEvent:event];
984 if ([hitView isKindOfClass:[WebHTMLView class]]) {
985 view = (WebHTMLView *)hitView;
988 hitView = [hitView superview];
992 if (lastHitView != view && lastHitView != nil) {
993 // If we are moving out of a view (or frame), let's pretend the mouse moved
994 // all the way out of that view. But we have to account for scrolling, because
995 // khtml doesn't understand our clipping.
996 NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
997 float yScroll = visibleRect.origin.y;
998 float xScroll = visibleRect.origin.x;
1000 event = [NSEvent mouseEventWithType:NSMouseMoved
1001 location:NSMakePoint(-1 - xScroll, -1 - yScroll )
1002 modifierFlags:[[NSApp currentEvent] modifierFlags]
1003 timestamp:[NSDate timeIntervalSinceReferenceDate]
1004 windowNumber:[[self window] windowNumber]
1005 context:[[NSApp currentEvent] context]
1006 eventNumber:0 clickCount:0 pressure:0];
1007 [[lastHitView _bridge] mouseMoved:event];
1012 NSDictionary *element;
1016 [[view _bridge] mouseMoved:event];
1018 NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
1019 element = [view elementAtPoint:point];
1022 // Have the web view send a message to the delegate so it can do status bar display.
1023 [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
1025 // Set a tool tip; it won't show up right away but will if the user pauses.
1026 NSString *newToolTip = nil;
1027 if (_private->showsURLsInToolTips) {
1028 newToolTip = [[element objectForKey:WebCoreElementLinkURLKey] _web_userVisibleString];
1030 if (newToolTip == nil) {
1031 newToolTip = [element objectForKey:WebCoreElementTitleKey];
1033 [self _setToolTip:newToolTip];
1038 + (NSArray *)_insertablePasteboardTypes
1040 static NSArray *types = nil;
1042 types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
1043 NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType,
1044 NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
1049 + (NSArray *)_selectionPasteboardTypes
1051 // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
1052 return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil];
1055 - (WebArchive *)_selectedArchive
1059 double start = CFAbsoluteTimeGetCurrent();
1061 NSString *markupString = [[self _bridge] markupStringFromRange:[self _selectedRange] nodes:&nodes];
1063 double duration = CFAbsoluteTimeGetCurrent() - start;
1064 LOG(Timing, "copying markup took %f seconds.", duration);
1067 WebArchive *archive = [[self _dataSource] _archiveWithMarkupString:markupString nodes:nodes];
1069 if ([[self _bridge] isFrameSet]) {
1070 // Wrap the frameset document in an iframe so it can be pasted into
1071 // another document (which will have a body or frameset of its own).
1072 NSString *iframeMarkup = [[NSString alloc] initWithFormat:@"<iframe frameborder=\"no\" marginwidth=\"0\" marginheight=\"0\" width=\"98%%\" height=\"98%%\" src=\"%@\"></iframe>", [[[self _dataSource] response] URL]];
1073 WebResource *iframeResource = [[WebResource alloc] initWithData:[iframeMarkup dataUsingEncoding:NSUTF8StringEncoding]
1074 URL:[NSURL URLWithString:@"about:blank"]
1075 MIMEType:@"text/html"
1076 textEncodingName:@"UTF-8"
1079 NSArray *subframeArchives = [NSArray arrayWithObject:archive];
1080 archive = [[[WebArchive alloc] initWithMainResource:iframeResource subresources:nil subframeArchives:subframeArchives] autorelease];
1082 [iframeResource release];
1083 [iframeMarkup release];
1089 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
1091 ASSERT([self _hasSelection]);
1092 NSArray *types = [self pasteboardTypesForSelection];
1094 // Don't write RTFD to the pasteboard when the copied attributed string has no attachments.
1095 NSAttributedString *attributedString = [self selectedAttributedString];
1096 NSMutableArray *mutableTypes = nil;
1097 if (![attributedString containsAttachments]) {
1098 mutableTypes = [types mutableCopy];
1099 [mutableTypes removeObject:NSRTFDPboardType];
1100 types = mutableTypes;
1103 [pasteboard declareTypes:types owner:nil];
1104 [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:attributedString];
1105 [mutableTypes release];
1108 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
1110 NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
1112 BOOL drawURLString = YES;
1113 BOOL clipURLString = NO, clipLabelString = NO;
1115 NSString *label = [element objectForKey: WebElementLinkLabelKey];
1116 NSString *urlString = [linkURL _web_userVisibleString];
1123 NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
1124 toHaveTrait:NSBoldFontMask];
1125 NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
1127 labelSize.width = [label _web_widthWithFont: labelFont];
1128 labelSize.height = [labelFont ascender] - [labelFont descender];
1129 if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
1130 labelSize.width = MAX_DRAG_LABEL_WIDTH;
1131 clipLabelString = YES;
1134 NSSize imageSize, urlStringSize;
1135 imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
1136 imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
1137 if (drawURLString) {
1138 urlStringSize.width = [urlString _web_widthWithFont: urlFont];
1139 urlStringSize.height = [urlFont ascender] - [urlFont descender];
1140 imageSize.height += urlStringSize.height;
1141 if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
1142 imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
1143 clipURLString = YES;
1145 imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
1148 NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
1149 [dragImage lockFocus];
1151 [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
1153 // Drag a rectangle with rounded corners/
1154 NSBezierPath *path = [NSBezierPath bezierPath];
1155 [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1156 [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1157 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1158 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1160 [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
1161 [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1162 [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1165 NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
1166 NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
1167 if (drawURLString) {
1169 urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
1171 [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender])
1172 withTopColor:topColor bottomColor:bottomColor font:urlFont];
1175 if (clipLabelString)
1176 label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
1177 [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
1178 withTopColor:topColor bottomColor:bottomColor font:labelFont];
1180 [dragImage unlockFocus];
1185 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
1187 NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
1188 NSDictionary *element = [self elementAtPoint:mouseDownPoint];
1190 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1191 NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
1192 BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
1194 [_private->draggingImageURL release];
1195 _private->draggingImageURL = nil;
1197 NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
1198 _private->webCoreDragOp = op; // will be DragNone if WebCore doesn't care
1199 NSImage *dragImage = nil;
1200 NSPoint dragLoc = { 0, 0 }; // quiet gcc 4.0 warning
1202 // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
1203 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
1204 // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
1206 dragImage = wcDragImage;
1207 // wcDragLoc is the cursor position relative to the lower-left corner of the image.
1208 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
1211 dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
1213 dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
1215 _private->dragOffset = wcDragLoc;
1218 WebView *webView = [self _webView];
1219 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
1220 WebImageRenderer *image = [element objectForKey:WebElementImageKey];
1221 BOOL startedDrag = YES; // optimism - we almost always manage to start the drag
1223 // note per kwebster, the offset arg below is always ignored in positioning the image
1224 if (imageURL != nil && image != nil && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1226 if (!dhtmlWroteData) {
1227 // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
1228 DOMHTMLElement *imageElement = [element objectForKey:WebElementDOMNodeKey];
1229 ASSERT(imageElement != nil);
1230 [webView setSelectedDOMRange:[[[self _bridge] DOMDocument] _createRangeWithNode:imageElement] affinity:NSSelectionAffinityDownstream];
1231 _private->draggingImageURL = [imageURL retain];
1232 source = [pasteboard _web_declareAndWriteDragImage:image
1233 URL:linkURL ? linkURL : imageURL
1234 title:[element objectForKey:WebElementImageAltStringKey]
1235 archive:[imageElement webArchive]
1238 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
1239 if (dragImage == nil) {
1240 [self _web_dragImage:[element objectForKey:WebElementImageKey]
1241 rect:[[element objectForKey:WebElementImageRectKey] rectValue]
1242 event:_private->mouseDownEvent
1243 pasteboard:pasteboard
1245 offset:&_private->dragOffset];
1247 [self dragImage:dragImage
1250 event:_private->mouseDownEvent
1251 pasteboard:pasteboard
1255 } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1256 if (!dhtmlWroteData) {
1257 NSArray *types = [NSPasteboard _web_writableTypesForURL];
1258 [pasteboard declareTypes:types owner:self];
1259 [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];
1261 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1262 if (dragImage == nil) {
1263 dragImage = [self _dragImageForLinkElement:element];
1264 NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1265 dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1266 _private->dragOffset.x = offset.width;
1267 _private->dragOffset.y = -offset.height; // inverted because we are flipped
1269 // HACK: We should pass the mouseDown event instead of the mouseDragged! This hack gets rid of
1270 // a flash of the image at the mouseDown location when the drag starts.
1271 [self dragImage:dragImage
1274 event:mouseDraggedEvent
1275 pasteboard:pasteboard
1278 } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1279 if (!dhtmlWroteData) {
1280 [self _writeSelectionToPasteboard:pasteboard];
1282 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1283 if (dragImage == nil) {
1284 dragImage = [self _selectionDraggingImage];
1285 NSRect draggingRect = [self _selectionDraggingRect];
1286 dragLoc = NSMakePoint(NSMinX(draggingRect), NSMaxY(draggingRect));
1287 _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1288 _private->dragOffset.y = dragLoc.y - mouseDownPoint.y; // inverted because we are flipped
1290 [self dragImage:dragImage
1293 event:_private->mouseDownEvent
1294 pasteboard:pasteboard
1297 } else if (srcIsDHTML) {
1298 ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1299 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1300 if (dragImage == nil) {
1301 // WebCore should have given us an image, but we'll make one up
1302 NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1303 dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1304 NSSize imageSize = [dragImage size];
1305 dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width/2, mouseDownPoint.y + imageSize.height/2);
1306 _private->dragOffset.x = imageSize.width/2;
1307 _private->dragOffset.y = imageSize.height/2; // inverted because we are flipped
1309 [self dragImage:dragImage
1312 event:_private->mouseDownEvent
1313 pasteboard:pasteboard
1317 // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1318 // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1324 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1326 [self autoscroll:event];
1327 [self _startAutoscrollTimer:event];
1330 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1332 NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1333 NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint];
1335 ASSERT([self _webView]);
1336 if ([mouseDownElement objectForKey: WebElementImageKey] != nil &&
1337 [mouseDownElement objectForKey: WebElementImageURLKey] != nil &&
1338 [[[self _webView] preferences] loadsImagesAutomatically] &&
1339 (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1343 if ([mouseDownElement objectForKey:WebElementLinkURLKey] != nil &&
1344 (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1348 if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
1349 (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1356 - (WebPluginController *)_pluginController
1358 return _private->pluginController;
1361 - (void)_web_setPrintingModeRecursive
1363 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1364 [super _web_setPrintingModeRecursive];
1367 - (void)_web_clearPrintingModeRecursive
1369 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1370 [super _web_clearPrintingModeRecursive];
1373 - (void)_layoutIfNeeded
1375 ASSERT(!_private->subviewsSetAside);
1377 if ([[self _bridge] needsLayout])
1378 _private->needsLayout = YES;
1379 if (_private->needsToApplyStyles || _private->needsLayout)
1383 - (void)_web_layoutIfNeededRecursive
1385 [self _layoutIfNeeded];
1386 [super _web_layoutIfNeededRecursive];
1389 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1391 ASSERT(!_private->subviewsSetAside);
1392 displayRect = NSIntersectionRect(displayRect, [self bounds]);
1394 if (!testDirtyRect || [self needsDisplay]) {
1395 if (testDirtyRect) {
1396 NSRect dirtyRect = [self _dirtyRect];
1397 displayRect = NSIntersectionRect(displayRect, dirtyRect);
1399 if (!NSIsEmptyRect(displayRect)) {
1400 [self _layoutIfNeeded];
1404 [super _web_layoutIfNeededRecursive:displayRect testDirtyRect:NO];
1407 - (NSRect)_selectionRect
1409 return [[self _bridge] selectionRect];
1412 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1414 if (_private->autoscrollTimer == nil) {
1415 _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1416 target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1417 _private->autoscrollTriggerEvent = [triggerEvent retain];
1421 - (void)_stopAutoscrollTimer
1423 NSTimer *timer = _private->autoscrollTimer;
1424 _private->autoscrollTimer = nil;
1425 [_private->autoscrollTriggerEvent release];
1426 _private->autoscrollTriggerEvent = nil;
1435 // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1436 // a mouse up event.
1437 PSstilldown([_private->autoscrollTriggerEvent eventNumber], &isStillDown);
1439 [self _stopAutoscrollTimer];
1443 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1444 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1445 modifierFlags:[[NSApp currentEvent] modifierFlags]
1446 timestamp:[NSDate timeIntervalSinceReferenceDate]
1447 windowNumber:[[self window] windowNumber]
1448 context:[[NSApp currentEvent] context]
1449 eventNumber:0 clickCount:0 pressure:0];
1450 [self mouseDragged:fakeEvent];
1455 // Copying can be done regardless of whether you can edit.
1456 return [self _hasSelection];
1461 return [self _hasSelection] && [self _isEditable];
1466 return [self _hasSelection] && [self _isEditable];
1471 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1476 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1479 - (BOOL)_hasSelection
1481 return [[self _bridge] selectionState] == WebSelectionStateRange;
1484 - (BOOL)_hasSelectionOrInsertionPoint
1486 return [[self _bridge] selectionState] != WebSelectionStateNone;
1491 return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1494 - (BOOL)_isSelectionMisspelled
1496 NSString *selectedString = [self selectedString];
1497 unsigned length = [selectedString length];
1501 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1505 inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1507 return range.length == length;
1510 - (NSArray *)_guessesForMisspelledSelection
1512 ASSERT([[self selectedString] length] != 0);
1513 return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1516 - (void)_changeSpellingFromMenu:(id)sender
1518 ASSERT([[self selectedString] length] != 0);
1519 [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1522 - (void)_ignoreSpellingFromMenu:(id)sender
1524 ASSERT([[self selectedString] length] != 0);
1525 [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1528 - (void)_learnSpellingFromMenu:(id)sender
1530 ASSERT([[self selectedString] length] != 0);
1531 [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1534 #ifndef OMIT_TIGER_FEATURES
1535 - (void)_searchWithGoogleFromMenu:(id)sender
1537 // This should only be called when there's a selection, but play it safe.
1538 if (![self _hasSelection]) {
1542 NSPasteboard *pboard = [NSPasteboard pasteboardWithUniqueName];
1543 if ([self writeSelectionToPasteboard:pboard types:[NSArray arrayWithObject:NSStringPboardType]]) {
1544 // FIXME: seems fragile to use the service by name, but this is what AppKit does
1545 NSPerformService(@"Search With Google", pboard);
1549 - (void)_searchWithSpotlightFromMenu:(id)sender
1551 // This should only be called when there's a selection, but play it safe.
1552 if (![self _hasSelection]) {
1556 (void)HISearchWindowShow((CFStringRef)[self selectedString], kNilOptions);
1558 - (void)_lookUpInDictionaryFromMenu:(id)sender
1560 // This should only be called when there's a selection, but play it safe.
1561 if (![self _hasSelection]) {
1565 // Soft link to dictionary-display function to avoid linking another framework (ApplicationServices/LangAnalysis)
1566 static OSStatus (*__dictionaryServiceWindowShow)(id inWordString, NSRect inWordBoundary, UInt16 inLineDirection) = NULL;
1567 static const struct mach_header *frameworkImageHeader = NULL;
1568 static BOOL lookedForFunction = NO;
1569 if (!lookedForFunction) {
1570 __dictionaryServiceWindowShow = _NSSoftLinkingGetFrameworkFuncPtr(@"ApplicationServices", @"LangAnalysis", "_DCMDictionaryServiceWindowShow", &frameworkImageHeader);
1571 lookedForFunction = YES;
1573 if (!__dictionaryServiceWindowShow) {
1574 ERROR("Couldn't find _DCMDictionaryServiceWindowShow");
1578 // FIXME: must check for right-to-left here
1579 NSWritingDirection writingDirection = NSWritingDirectionLeftToRight;
1581 NSAttributedString *attrString = [self selectedAttributedString];
1582 // FIXME: the dictionary API expects the rect for the first line of selection. Passing
1583 // the rect for the entire selection, as we do here, positions the pop-up window near
1584 // the bottom of the selection rather than at the selected word.
1585 NSRect rect = [self convertRect:[[self _bridge] visibleSelectionRect] toView:nil];
1586 rect.origin = [[self window] convertBaseToScreen:rect.origin];
1587 NSData *data = [attrString RTFFromRange:NSMakeRange(0, [attrString length]) documentAttributes:nil];
1588 (void)__dictionaryServiceWindowShow(data, rect, (writingDirection == NSWritingDirectionRightToLeft) ? 1 : 0);
1592 #if APPKIT_CODE_FOR_REFERENCE
1594 - (void)_openLinkFromMenu:(id)sender
1596 NSTextStorage *text = _getTextStorage(self);
1597 NSRange charRange = [self selectedRange];
1598 if (charRange.location != NSNotFound && charRange.length > 0) {
1599 id link = [text attribute:NSLinkAttributeName atIndex:charRange.location effectiveRange:NULL];
1601 [self clickedOnLink:link atIndex:charRange.location];
1603 NSString *string = [[text string] substringWithRange:charRange];
1604 link = [NSURL URLWithString:string];
1605 if (link) [[NSWorkspace sharedWorkspace] openURL:link];
1612 - (BOOL)_transparentBackground
1614 return _private->transparentBackground;
1617 - (void)_setTransparentBackground:(BOOL)f
1619 _private->transparentBackground = f;
1622 - (NSImage *)_selectionDraggingImage
1624 if ([self _hasSelection]) {
1625 NSImage *dragImage = [[self _bridge] selectionImage];
1626 [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1632 - (NSRect)_selectionDraggingRect
1634 if ([self _hasSelection]) {
1635 return [[self _bridge] visibleSelectionRect];
1642 @implementation NSView (WebHTMLViewFileInternal)
1644 - (void)_web_setPrintingModeRecursive
1646 [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1649 - (void)_web_clearPrintingModeRecursive
1651 [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1654 - (void)_web_layoutIfNeededRecursive
1656 [_subviews makeObjectsPerformSelector:@selector(_web_layoutIfNeededRecursive)];
1659 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1661 unsigned index, count;
1662 for (index = 0, count = [_subviews count]; index < count; index++) {
1663 NSView *subview = [_subviews objectAtIndex:index];
1664 NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1665 [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1671 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1673 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1675 if (object == nil) {
1676 [self removeObjectForKey:key];
1678 [self setObject:object forKey:key];
1684 // The following is a workaround for
1685 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1686 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1687 // Since the category will be searched before the real class, we'll prevent the flag from being
1688 // set on the tool tip panel.
1690 @interface NSToolTipPanel : NSPanel
1693 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1696 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1698 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1700 // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1706 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
1709 @interface NSArray (WebHTMLView)
1710 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1713 @implementation WebHTMLView
1717 [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes]
1718 returnTypes:[[self class] _insertablePasteboardTypes]];
1719 _NSInitializeKillRing();
1722 - (void)_resetCachedWebPreferences:(NSNotification *)ignored
1724 WebPreferences *preferences = [[self _webView] preferences];
1725 // Check for nil because we might not yet have an associated webView when this is called
1726 if (preferences == nil) {
1727 preferences = [WebPreferences standardPreferences];
1729 _private->showsURLsInToolTips = [preferences showsURLsInToolTips];
1732 - (id)initWithFrame:(NSRect)frame
1734 [super initWithFrame:frame];
1736 // Make all drawing go through us instead of subviews.
1737 if (NSAppKitVersionNumber >= 711) {
1738 [self _setDrawsOwnDescendants:YES];
1741 _private = [[WebHTMLViewPrivate alloc] init];
1743 _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1744 _private->needsLayout = YES;
1745 [self _resetCachedWebPreferences:nil];
1746 [[NSNotificationCenter defaultCenter]
1747 addObserver:self selector:@selector(_resetCachedWebPreferences:)
1748 name:WebPreferencesChangedNotification object:nil];
1755 [self _clearLastHitViewIfSelf];
1757 [[NSNotificationCenter defaultCenter] removeObserver:self];
1758 [_private->pluginController destroyAllPlugins];
1766 [self _clearLastHitViewIfSelf];
1768 [[NSNotificationCenter defaultCenter] removeObserver:self];
1769 [_private->pluginController destroyAllPlugins];
1774 - (IBAction)takeFindStringFromSelection:(id)sender
1776 if (![self _hasSelection]) {
1781 [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1784 - (NSArray *)pasteboardTypesForSelection
1786 if ([self _canSmartCopyOrDelete]) {
1787 NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1788 [types addObject:WebSmartPastePboardType];
1791 return [[self class] _selectionPasteboardTypes];
1795 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1797 [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:nil];
1800 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1802 [pasteboard declareTypes:types owner:nil];
1803 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
1807 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
1809 [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
1813 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1815 if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
1817 } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
1820 return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
1823 - (void)selectAll:(id)sender
1828 - (void)jumpToSelection:(id)sender
1830 [[self _bridge] jumpToSelection];
1833 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
1835 SEL action = [item action];
1836 WebBridge *bridge = [self _bridge];
1838 if (action == @selector(alignCenter:)
1839 || action == @selector(alignLeft:)
1840 || action == @selector(alignJustified:)
1841 || action == @selector(alignRight:)
1842 || action == @selector(changeAttributes:)
1843 || action == @selector(changeBaseWritingDirection:) // FIXME: check menu item based on writing direction
1844 || action == @selector(changeColor:)
1845 || action == @selector(changeFont:)
1846 || action == @selector(changeSpelling:)
1847 || action == @selector(_changeSpellingFromMenu:)
1848 || action == @selector(checkSpelling:)
1849 || action == @selector(complete:)
1850 || action == @selector(deleteBackward:)
1851 || action == @selector(deleteBackwardByDecomposingPreviousCharacter:)
1852 || action == @selector(deleteForward:)
1853 || action == @selector(deleteToBeginningOfLine:)
1854 || action == @selector(deleteToBeginningOfParagraph:)
1855 || action == @selector(deleteToEndOfLine:)
1856 || action == @selector(deleteToEndOfParagraph:)
1857 || action == @selector(deleteToMark:)
1858 || action == @selector(deleteWordBackward:)
1859 || action == @selector(deleteWordForward:)
1860 || action == @selector(insertBacktab:)
1861 || action == @selector(insertLineBreak:)
1862 || action == @selector(insertNewline:)
1863 || action == @selector(insertNewlineIgnoringFieldEditor:)
1864 || action == @selector(insertParagraphSeparator:)
1865 || action == @selector(insertTab:)
1866 || action == @selector(insertTabIgnoringFieldEditor:)
1867 || action == @selector(moveBackward:)
1868 || action == @selector(moveBackwardAndModifySelection:)
1869 || action == @selector(moveDown:)
1870 || action == @selector(moveDownAndModifySelection:)
1871 || action == @selector(moveForward:)
1872 || action == @selector(moveForwardAndModifySelection:)
1873 || action == @selector(moveLeft:)
1874 || action == @selector(moveLeftAndModifySelection:)
1875 || action == @selector(moveParagraphBackwardAndModifySelection:)
1876 || action == @selector(moveParagraphForwardAndModifySelection:)
1877 || action == @selector(moveRight:)
1878 || action == @selector(moveRightAndModifySelection:)
1879 || action == @selector(moveToBeginningOfDocument:)
1880 || action == @selector(moveToBeginningOfDocumentAndModifySelection:)
1881 || action == @selector(moveToBeginningOfLine:)
1882 || action == @selector(moveToBeginningOfLineAndModifySelection:)
1883 || action == @selector(moveToBeginningOfParagraph:)
1884 || action == @selector(moveToBeginningOfParagraphAndModifySelection:)
1885 || action == @selector(moveToEndOfDocument:)
1886 || action == @selector(moveToEndOfDocumentAndModifySelection:)
1887 || action == @selector(moveToEndOfLine:)
1888 || action == @selector(moveToEndOfLineAndModifySelection:)
1889 || action == @selector(moveToEndOfParagraph:)
1890 || action == @selector(moveToEndOfParagraphAndModifySelection:)
1891 || action == @selector(moveUp:)
1892 || action == @selector(moveUpAndModifySelection:)
1893 || action == @selector(moveWordBackward:)
1894 || action == @selector(moveWordBackwardAndModifySelection:)
1895 || action == @selector(moveWordForward:)
1896 || action == @selector(moveWordForwardAndModifySelection:)
1897 || action == @selector(moveWordLeft:)
1898 || action == @selector(moveWordLeftAndModifySelection:)
1899 || action == @selector(moveWordRight:)
1900 || action == @selector(moveWordRightAndModifySelection:)
1901 || action == @selector(pageDown:)
1902 || action == @selector(pageDownAndModifySelection:)
1903 || action == @selector(pageUp:)
1904 || action == @selector(pageUpAndModifySelection:)
1905 || action == @selector(pasteFont:)
1906 || action == @selector(showGuessPanel:)
1907 || action == @selector(toggleBaseWritingDirection:)
1908 || action == @selector(transpose:)
1909 || action == @selector(yank:)
1910 || action == @selector(yankAndSelect:)) {
1911 return [self _canEdit];
1912 } else if (action == @selector(capitalizeWord:)
1913 || action == @selector(lowercaseWord:)
1914 || action == @selector(uppercaseWord:)) {
1915 return [self _hasSelection] && [self _isEditable];
1916 } else if (action == @selector(centerSelectionInVisibleArea:)
1917 || action == @selector(copyFont:)
1918 || action == @selector(setMark:)) {
1919 return [self _hasSelectionOrInsertionPoint];
1920 } else if (action == @selector(changeDocumentBackgroundColor:)) {
1921 return [[self _webView] isEditable];
1922 } else if (action == @selector(copy:)) {
1923 return [bridge mayDHTMLCopy] || [self _canCopy];
1924 } else if (action == @selector(cut:)) {
1925 return [bridge mayDHTMLCut] || [self _canDelete];
1926 } else if (action == @selector(delete:)) {
1927 return [self _canDelete];
1928 } else if (action == @selector(_ignoreSpellingFromMenu:)
1929 || action == @selector(jumpToSelection:)
1930 || action == @selector(_learnSpellingFromMenu:)
1931 || action == @selector(takeFindStringFromSelection:)) {
1932 return [self _hasSelection];
1933 } else if (action == @selector(paste:) || action == @selector(pasteAsPlainText:) || action == @selector(pasteAsRichText:)) {
1934 return [bridge mayDHTMLPaste] || [self _canPaste];
1935 } else if (action == @selector(performFindPanelAction:)) {
1936 // FIXME: Not yet implemented.
1938 } else if (action == @selector(selectToMark:)
1939 || action == @selector(swapWithMark:)) {
1940 return [self _hasSelectionOrInsertionPoint] && [[self _bridge] markDOMRange] != nil;
1941 } else if (action == @selector(subscript:)) {
1942 NSMenuItem *menuItem = (NSMenuItem *)item;
1943 if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1944 DOMCSSStyleDeclaration *style = [self _emptyStyle];
1945 [style setVerticalAlign:@"sub"];
1946 [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1948 return [self _canEdit];
1949 } else if (action == @selector(superscript:)) {
1950 NSMenuItem *menuItem = (NSMenuItem *)item;
1951 if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1952 DOMCSSStyleDeclaration *style = [self _emptyStyle];
1953 [style setVerticalAlign:@"super"];
1954 [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1956 return [self _canEdit];
1957 } else if (action == @selector(underline:)) {
1958 NSMenuItem *menuItem = (NSMenuItem *)item;
1959 if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1960 DOMCSSStyleDeclaration *style = [self _emptyStyle];
1961 [style setProperty:@"-khtml-text-decorations-in-effect" :@"underline" :@""];
1962 [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1964 return [self _canEdit];
1965 } else if (action == @selector(unscript:)) {
1966 NSMenuItem *menuItem = (NSMenuItem *)item;
1967 if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1968 DOMCSSStyleDeclaration *style = [self _emptyStyle];
1969 [style setVerticalAlign:@"baseline"];
1970 [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1972 return [self _canEdit];
1973 #ifndef OMIT_TIGER_FEATURES
1974 } else if (action == @selector(_searchWithSpotlightFromMenu:)
1975 || action == @selector(_searchWithGoogleFromMenu:)
1976 || action == @selector(_lookUpInDictionaryFromMenu:)) {
1977 return [self _hasSelection];
1984 - (BOOL)acceptsFirstResponder
1986 // Don't accept first responder when we first click on this view.
1987 // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1988 // Do accept first responder at any other time, for example from keyboard events,
1989 // or from calls back from WebCore once we begin mouse-down event handling.
1990 NSEvent *event = [NSApp currentEvent];
1991 if ([event type] == NSLeftMouseDown
1992 && !_private->handlingMouseDownEvent
1993 && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1999 - (BOOL)maintainsInactiveSelection
2001 // This method helps to determing whether the view should maintain
2002 // an inactive selection when the view is not first responder.
2003 // Traditionally, these views have not maintained such selections,
2004 // clearing them when the view was not first responder. However,
2005 // to fix bugs like this one:
2006 // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even
2007 // when they're not firstResponder"
2008 // it was decided to add a switch to act more like an NSTextView.
2009 // For now, however, the view only acts in this way when the
2010 // web view is set to be editable. This will maintain traditional
2011 // behavior for WebKit clients dating back to before this change,
2012 // and will likely be a decent switch for the long term, since
2013 // clients to ste the web view to be editable probably want it
2014 // to act like a "regular" Cocoa view in terms of its selection
2016 id nextResponder = [[self window] _newFirstResponderAfterResigning];
2018 // Predict the case where we are losing first responder status only to
2019 // gain it back again. Want to keep the selection in that case.
2020 if ([nextResponder isKindOfClass:[NSScrollView class]]) {
2021 id contentView = [nextResponder contentView];
2023 nextResponder = contentView;
2026 if ([nextResponder isKindOfClass:[NSClipView class]]) {
2027 id documentView = [nextResponder documentView];
2029 nextResponder = documentView;
2033 if (nextResponder == self)
2036 if (![[self _webView] maintainsInactiveSelection])
2039 // editable views lose selection when losing first responder status
2040 // to a widget in the same page, but not otherwise
2041 BOOL loseSelection = [nextResponder isKindOfClass:[NSView class]]
2042 && [nextResponder isDescendantOf:[self _webView]];
2044 return !loseSelection;
2047 - (void)addMouseMovedObserver
2049 // Always add a mouse move observer if the DB requested, or if we're the key window.
2050 if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
2051 [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
2052 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
2053 name:NSMouseMovedNotification object:nil];
2054 [self _frameOrBoundsChanged];
2058 - (void)removeMouseMovedObserver
2060 // Don't remove the observer if we're running the DB
2061 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
2064 [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
2065 [[NSNotificationCenter defaultCenter] removeObserver:self
2066 name:NSMouseMovedNotification object:nil];
2069 - (void)updateFocusState
2071 // This method does the job of updating the view based on the view's firstResponder-ness and
2072 // the window key-ness of the window containing this view. This involves three kinds of
2073 // drawing updates right now, all handled in WebCore in response to the call over the bridge.
2075 // The three display attributes are as follows:
2077 // 1. The background color used to draw behind selected content (active | inactive color)
2078 // 2. Caret blinking (blinks | does not blink)
2079 // 3. The drawing of a focus ring around links in web pages.
2081 // Also, this is responsible for letting the bridge know if the window has gained or lost focus
2082 // so we can send focus and blur events.
2084 WebBridge *bridge = [self _bridge];
2085 BOOL windowIsKey = [[self window] isKeyWindow];
2087 BOOL flag = !_private->resigningFirstResponder && windowIsKey && [self _web_firstResponderCausesFocusDisplay];
2088 [bridge setDisplaysWithFocusAttributes:flag];
2090 [bridge setWindowHasFocus:windowIsKey];
2093 - (void)addSuperviewObservers
2095 // We watch the bounds of our superview, so that we can do a layout when the size
2096 // of the superview changes. This is different from other scrollable things that don't
2097 // need this kind of thing because their layout doesn't change.
2099 // We need to pay attention to both height and width because our "layout" has to change
2100 // to extend the background the full height of the space and because some elements have
2101 // sizes that are based on the total size of the view.
2103 NSView *superview = [self superview];
2104 if (superview && [self window]) {
2105 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
2106 name:NSViewFrameDidChangeNotification object:superview];
2107 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
2108 name:NSViewBoundsDidChangeNotification object:superview];
2112 - (void)removeSuperviewObservers
2114 NSView *superview = [self superview];
2115 if (superview && [self window]) {
2116 [[NSNotificationCenter defaultCenter] removeObserver:self
2117 name:NSViewFrameDidChangeNotification object:superview];
2118 [[NSNotificationCenter defaultCenter] removeObserver:self
2119 name:NSViewBoundsDidChangeNotification object:superview];
2123 - (void)addWindowObservers
2125 NSWindow *window = [self window];
2127 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
2128 name:NSWindowDidBecomeKeyNotification object:window];
2129 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
2130 name:NSWindowDidResignKeyNotification object:window];
2131 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
2132 name:NSWindowWillCloseNotification object:window];
2136 - (void)removeWindowObservers
2138 NSWindow *window = [self window];
2140 [[NSNotificationCenter defaultCenter] removeObserver:self
2141 name:NSWindowDidBecomeKeyNotification object:window];
2142 [[NSNotificationCenter defaultCenter] removeObserver:self
2143 name:NSWindowDidResignKeyNotification object:window];
2144 [[NSNotificationCenter defaultCenter] removeObserver:self
2145 name:NSWindowWillCloseNotification object:window];
2149 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
2151 [self removeSuperviewObservers];
2154 - (void)viewDidMoveToSuperview
2156 // Do this here in case the text size multiplier changed when a non-HTML
2157 // view was installed.
2158 if ([self superview] != nil) {
2159 [self _updateTextSizeMultiplier];
2160 [self addSuperviewObservers];
2164 - (void)viewWillMoveToWindow:(NSWindow *)window
2166 // Don't do anything if we aren't initialized. This happens
2167 // when decoding a WebView. When WebViews are decoded their subviews
2168 // are created by initWithCoder: and so won't be normally
2169 // initialized. The stub views are discarded by WebView.
2171 // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
2172 [self removeMouseMovedObserver];
2173 [self removeWindowObservers];
2174 [self removeSuperviewObservers];
2175 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2177 [[self _pluginController] stopAllPlugins];
2181 - (void)viewDidMoveToWindow
2183 // Don't do anything if we aren't initialized. This happens
2184 // when decoding a WebView. When WebViews are decoded their subviews
2185 // are created by initWithCoder: and so won't be normally
2186 // initialized. The stub views are discarded by WebView.
2188 [self _stopAutoscrollTimer];
2189 if ([self window]) {
2190 _private->lastScrollPosition = [[self superview] bounds].origin;
2191 [self addWindowObservers];
2192 [self addSuperviewObservers];
2193 [self addMouseMovedObserver];
2195 // Schedule this update, rather than making the call right now.
2196 // The reason is that placing the caret in the just-installed view requires
2197 // the HTML/XML document to be available on the WebCore side, but it is not
2198 // at the time this code is running. However, it will be there on the next
2199 // crank of the run loop. Doing this helps to make a blinking caret appear
2200 // in a new, empty window "automatic".
2201 [self performSelector:@selector(updateFocusState) withObject:nil afterDelay:0];
2203 [[self _pluginController] startAllPlugins];
2205 _private->lastScrollPosition = NSZeroPoint;
2207 _private->inWindow = YES;
2209 // Reset when we are moved out of a window after being moved into one.
2210 // Without this check, we reset ourselves before we even start.
2211 // This is only needed because viewDidMoveToWindow is called even when
2212 // the window is not changing (bug in AppKit).
2213 if (_private->inWindow) {
2215 _private->inWindow = NO;
2221 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
2223 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
2226 - (void)viewDidMoveToHostWindow
2228 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
2232 - (void)addSubview:(NSView *)view
2234 [super addSubview:view];
2236 if ([WebPluginController isPlugInView:view]) {
2237 [[self _pluginController] addPlugin:view];
2241 - (void)reapplyStyles
2243 if (!_private->needsToApplyStyles) {
2248 double start = CFAbsoluteTimeGetCurrent();
2251 [[self _bridge] reapplyStylesForDeviceType:
2252 _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
2255 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2256 LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
2259 _private->needsToApplyStyles = NO;
2262 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
2263 // minPageWidth==0 implies a non-printing layout
2264 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
2266 [self reapplyStyles];
2268 // Ensure that we will receive mouse move events. Is this the best place to put this?
2269 [[self window] setAcceptsMouseMovedEvents: YES];
2270 [[self window] _setShouldPostEventNotifications: YES];
2272 if (!_private->needsLayout) {
2277 double start = CFAbsoluteTimeGetCurrent();
2280 LOG(View, "%@ doing layout", self);
2282 if (minPageWidth > 0.0) {
2283 [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2285 [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
2287 _private->needsLayout = NO;
2289 if (!_private->printing) {
2290 // get size of the containing dynamic scrollview, so
2291 // appearance and disappearance of scrollbars will not show up
2293 NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
2294 if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
2295 [[self _bridge] sendResizeEvent];
2297 _private->laidOutAtLeastOnce = YES;
2298 _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
2299 _private->lastLayoutFrameSize = newLayoutFrameSize;
2303 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2304 LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
2310 [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
2313 - (NSMenu *)menuForEvent:(NSEvent *)event
2315 [_private->compController endRevertingChange:NO moveLeft:NO];
2317 if ([[self _bridge] sendContextMenuEvent:event]) {
2320 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2321 NSDictionary *element = [self elementAtPoint:point];
2322 return [[self _webView] _menuForElement:element];
2325 // Search from the end of the currently selected location, or from the beginning of the
2326 // document if nothing is selected.
2327 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2329 return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag findInSelection:NO];
2332 // Private method that adds a findInSelection parameter; might be public someday
2333 // FIXME: this is currently discovered using respondsToSelector; no SPI or API yet
2334 // FIXME: this needs to be done for other WebDocumentSearching implementors also, such as
2335 // WebPDFView and WebSearchableTextView
2336 - (BOOL)_searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag findInSelection:(BOOL)inSelectionFlag
2338 return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag findInSelection:inSelectionFlag];
2341 - (DOMRange *)_documentRange
2343 return [[[self _bridge] DOMDocument] _documentRange];
2346 - (NSString *)string
2348 return [[self _bridge] stringForRange:[self _documentRange]];
2351 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
2353 NSAttributedString *attributedString = nil;
2354 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
2356 double start = CFAbsoluteTimeGetCurrent();
2358 attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
2360 double duration = CFAbsoluteTimeGetCurrent() - start;
2361 LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
2364 return attributedString;
2367 - (NSAttributedString *)attributedString
2369 WebBridge *bridge = [self _bridge];
2370 DOMDocument *document = [bridge DOMDocument];
2371 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
2372 if (attributedString == nil) {
2373 attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
2375 return attributedString;
2378 - (NSString *)selectedString
2380 return [[self _bridge] selectedString];
2383 - (NSAttributedString *)selectedAttributedString
2385 WebBridge *bridge = [self _bridge];
2386 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
2387 if (attributedString == nil) {
2388 attributedString = [bridge selectedAttributedString];
2390 return attributedString;
2395 [[self _bridge] selectAll];
2398 // Remove the selection.
2401 [[self _bridge] deselectAll];
2404 - (void)deselectText
2406 [[self _bridge] deselectText];
2411 return [[self _webView] drawsBackground];
2414 - (void)setNeedsDisplay:(BOOL)flag
2416 LOG(View, "%@ flag = %d", self, (int)flag);
2417 [super setNeedsDisplay: flag];
2420 - (void)setNeedsLayout: (BOOL)flag
2422 LOG(View, "%@ flag = %d", self, (int)flag);
2423 _private->needsLayout = flag;
2427 - (void)setNeedsToApplyStyles: (BOOL)flag
2429 LOG(View, "%@ flag = %d", self, (int)flag);
2430 _private->needsToApplyStyles = flag;
2433 - (void)drawRect:(NSRect)rect
2435 LOG(View, "%@ drawing", self);
2437 // Work around AppKit bug <rdar://problem/3875305> rect passed to drawRect: is too large.
2438 // Ignore the passed-in rect and instead union in the rectangles from getRectsBeingDrawn.
2439 // This does a better job of clipping out rects that are entirely outside the visible area.
2440 const NSRect *rects;
2442 [self getRectsBeingDrawn:&rects count:&count];
2444 // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2445 // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2446 // The reason for the workaround is that this method is called explicitly from the code
2447 // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2451 for (i = 0; i < count; ++i) {
2452 rect = NSUnionRect(rect, rects[i]);
2454 if (rect.size.height == 0 || rect.size.width == 0) {
2459 BOOL subviewsWereSetAside = _private->subviewsSetAside;
2460 if (subviewsWereSetAside) {
2461 [self _restoreSubviews];
2465 double start = CFAbsoluteTimeGetCurrent();
2468 [NSGraphicsContext saveGraphicsState];
2471 ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2473 [(WebClipView *)[self superview] setAdditionalClip:rect];
2476 WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
2477 if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
2478 textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
2479 [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
2482 if ([self _transparentBackground]) {
2483 [[NSColor clearColor] set];
2487 //double start = CFAbsoluteTimeGetCurrent();
2488 [[self _bridge] drawRect:rect];
2489 //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
2491 if (textRendererFactoryIfCoalescing != nil) {
2492 [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
2495 [(WebClipView *)[self superview] resetAdditionalClip];
2497 [NSGraphicsContext restoreGraphicsState];
2499 [(WebClipView *)[self superview] resetAdditionalClip];
2500 [NSGraphicsContext restoreGraphicsState];
2501 ERROR("Exception caught while drawing: %@", localException);
2502 [localException raise];
2506 NSRect vframe = [self frame];
2507 [[NSColor blackColor] set];
2509 path = [NSBezierPath bezierPath];
2510 [path setLineWidth:(float)0.1];
2511 [path moveToPoint:NSMakePoint(0, 0)];
2512 [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2515 path = [NSBezierPath bezierPath];
2516 [path setLineWidth:(float)0.1];
2517 [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2518 [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2524 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2525 LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2528 if (subviewsWereSetAside) {
2529 [self _setAsideSubviews];
2533 // Turn off the additional clip while computing our visibleRect.
2534 - (NSRect)visibleRect
2536 if (!([[self superview] isKindOfClass:[WebClipView class]]))
2537 return [super visibleRect];
2539 WebClipView *clipView = (WebClipView *)[self superview];
2541 BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2542 if (!hasAdditionalClip) {
2543 return [super visibleRect];
2546 NSRect additionalClip = [clipView additionalClip];
2547 [clipView resetAdditionalClip];
2548 NSRect visibleRect = [super visibleRect];
2549 [clipView setAdditionalClip:additionalClip];
2558 - (void)windowDidBecomeKey:(NSNotification *)notification
2560 ASSERT([notification object] == [self window]);
2561 [self addMouseMovedObserver];
2562 [self updateFocusState];
2565 - (void)windowDidResignKey: (NSNotification *)notification
2567 ASSERT([notification object] == [self window]);
2568 [_private->compController endRevertingChange:NO moveLeft:NO];
2569 [self removeMouseMovedObserver];
2570 [self updateFocusState];
2573 - (void)windowWillClose:(NSNotification *)notification
2575 [_private->compController endRevertingChange:NO moveLeft:NO];
2576 [[self _pluginController] destroyAllPlugins];
2579 - (void)scrollWheel:(NSEvent *)event
2583 if (![[self _bridge] sendScrollWheelEvent:event]) {
2584 [[self nextResponder] scrollWheel:event];
2590 - (BOOL)_isSelectionEvent:(NSEvent *)event
2592 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2593 return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2596 - (void)_setMouseDownEvent:(NSEvent *)event
2598 ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2600 if (event == _private->mouseDownEvent) {
2605 [_private->mouseDownEvent release];
2606 _private->mouseDownEvent = event;
2608 [_private->firstResponderAtMouseDownTime release];
2609 _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2612 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2614 NSView *hitView = [self _hitViewForEvent:event];
2615 WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2616 [hitHTMLView _setMouseDownEvent:event];
2618 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2621 if (hitHTMLView != nil) {
2622 [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2623 return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2625 return [hitView acceptsFirstMouse:event];
2629 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2631 NSView *hitView = [self _hitViewForEvent:event];
2632 WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2633 if (hitHTMLView != nil) {
2634 [hitHTMLView _setMouseDownEvent:event];
2635 return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2637 return [hitView shouldDelayWindowOrderingForEvent:event];
2641 - (void)mouseDown:(NSEvent *)event
2645 _private->handlingMouseDownEvent = YES;
2647 // Record the mouse down position so we can determine drag hysteresis.
2648 [self _setMouseDownEvent:event];
2650 // TEXTINPUT: if there is marked text and the current input
2651 // manager wants to handle mouse events, we need to make sure to
2652 // pass it to them. If not, then we need to notify the input
2653 // manager when the marked text is abandoned (user clicks outside
2656 [_private->compController endRevertingChange:NO moveLeft:NO];
2658 // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2659 // We don't want to pass them along to KHTML a second time.
2660 if (!([event modifierFlags] & NSControlKeyMask)) {
2661 _private->ignoringMouseDraggedEvents = NO;
2663 // Don't do any mouseover while the mouse is down.
2664 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2666 // Let KHTML get a chance to deal with the event. This will call back to us
2667 // to start the autoscroll timer if appropriate.
2668 [[self _bridge] mouseDown:event];
2671 [_private->firstResponderAtMouseDownTime release];
2672 _private->firstResponderAtMouseDownTime = nil;
2674 _private->handlingMouseDownEvent = NO;
2679 - (void)dragImage:(NSImage *)dragImage
2681 offset:(NSSize)offset
2682 event:(NSEvent *)event
2683 pasteboard:(NSPasteboard *)pasteboard
2685 slideBack:(BOOL)slideBack
2687 [self _stopAutoscrollTimer];
2689 _private->initiatedDrag = YES;
2690 [[self _webView] _setInitiatedDrag:YES];
2692 // Retain this view during the drag because it may be released before the drag ends.
2695 [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2698 - (void)mouseDragged:(NSEvent *)event
2702 // TEXTINPUT: if there is marked text and the current input
2703 // manager wants to handle mouse events, we need to make sure to
2706 if (!_private->ignoringMouseDraggedEvents) {
2707 [[self _bridge] mouseDragged:event];
2713 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2715 if (_private->webCoreDragOp == NSDragOperationNone) {
2716 return (NSDragOperationGeneric | NSDragOperationCopy);
2718 return _private->webCoreDragOp;
2722 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2724 NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2725 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2726 [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2729 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2731 NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2732 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2733 [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2735 _private->initiatedDrag = NO;
2736 [[self _webView] _setInitiatedDrag:NO];
2738 // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2739 _private->ignoringMouseDraggedEvents = YES;
2741 // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2742 // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2743 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2744 location:windowMouseLoc
2745 modifierFlags:[[NSApp currentEvent] modifierFlags]
2746 timestamp:[NSDate timeIntervalSinceReferenceDate]
2747 windowNumber:[[self window] windowNumber]
2748 context:[[NSApp currentEvent] context]
2749 eventNumber:0 clickCount:0 pressure:0];
2750 [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2752 // Balance the previous retain from when the drag started.
2756 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2758 ASSERT(_private->draggingImageURL);
2760 NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2763 // FIXME: Report an error if we fail to create a file.
2764 NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2765 path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
2766 if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2767 ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2770 return [NSArray arrayWithObject:[path lastPathComponent]];
2773 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2775 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2776 NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2777 [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2778 if ([types count] == 0) {
2780 } else if ([types count] == 1 &&
2781 [types containsObject:NSFilenamesPboardType] &&
2782 ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2786 NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2787 NSDictionary *element = [self elementAtPoint:point];
2788 if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2789 if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2790 // Can't drag onto the selection being dragged.
2801 return _private->initiatedDrag &&
2802 ([self _isEditable] && [self _hasSelection]) &&
2803 ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2806 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2808 return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2811 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2813 NSDragOperation operation = NSDragOperationNone;
2815 if (actionMask & WebDragDestinationActionDHTML) {
2816 operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2818 _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2820 if ((actionMask & WebDragDestinationActionEdit) &&
2821 !_private->webCoreHandlingDrag
2822 && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2823 if ([self _isNSColorDrag:draggingInfo]) {
2824 operation = NSDragOperationGeneric;
2827 WebView *webView = [self _webView];
2828 [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2829 operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2832 [[self _webView] removeDragCaret];
2838 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2840 [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2841 [[self _webView] removeDragCaret];
2844 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2846 WebView *webView = [self _webView];
2847 WebBridge *bridge = [self _bridge];
2848 if (_private->webCoreHandlingDrag) {
2849 ASSERT(actionMask & WebDragDestinationActionDHTML);
2850 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2851 [bridge concludeDragForDraggingInfo:draggingInfo];
2853 } else if (actionMask & WebDragDestinationActionEdit) {
2854 if ([self _isNSColorDrag:draggingInfo]) {
2855 NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2858 DOMCSSStyleDeclaration *style = [self _emptyStyle];
2859 [style setProperty:@"color" :[self _colorAsString:color] :@""];
2860 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2861 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2862 [bridge applyStyle:style withUndoAction:WebUndoActionSetColor];
2868 BOOL didInsert = NO;
2869 if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2870 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2871 BOOL chosePlainText;
2872 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES chosePlainText:&chosePlainText];
2873 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2874 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2875 if ([self _isMoveDrag]) {
2876 BOOL smartMove = [[self _bridge] selectionGranularity] == WebSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2877 [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2879 [bridge setSelectionToDragCaret];
2880 [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard] matchStyle:chosePlainText];
2885 [webView removeDragCaret];
2892 - (NSDictionary *)elementAtPoint:(NSPoint)point
2894 NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2895 NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2897 // Convert URL strings to NSURLs
2898 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2899 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2901 WebFrameView *webFrameView = [self _web_parentWebFrameView];
2902 ASSERT(webFrameView);
2903 WebFrame *webFrame = [webFrameView webFrame];
2906 NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2907 if ([frameName length] == 0) {
2908 [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2910 WebFrame *wf = [webFrame findFrameNamed:frameName];
2912 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2914 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2917 [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2920 return [elementInfo autorelease];
2923 - (void)mouseUp:(NSEvent *)event
2925 // TEXTINPUT: if there is marked text and the current input
2926 // manager wants to handle mouse events, we need to make sure to
2931 [self _stopAutoscrollTimer];
2932 [[self _bridge] mouseUp:event];
2933 [self _updateMouseoverWithFakeEvent];
2938 - (void)mouseMovedNotification:(NSNotification *)notification
2940 [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2943 - (BOOL)supportsTextEncoding
2948 - (NSView *)nextValidKeyView
2951 BOOL lookInsideWebFrameViews = YES;
2952 if ([self isHiddenOrHasHiddenAncestor]) {
2953 lookInsideWebFrameViews = NO;
2954 } else if ([self _frame] == [[self _webView] mainFrame]) {
2955 // Check for case where first responder is last frame in a frameset, and we are
2956 // the top-level documentView.
2957 NSResponder *firstResponder = [[self window] firstResponder];
2958 if ((firstResponder != self) && [firstResponder isKindOfClass:[WebHTMLView class]] && ([(NSView *)firstResponder nextKeyView] == nil)) {
2959 lookInsideWebFrameViews = NO;
2963 if (lookInsideWebFrameViews) {
2964 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2968 view = [super nextValidKeyView];
2969 // If there's no next view wired up, we must be in the last subframe.
2970 // There's no direct link to the next valid key view; get it from the bridge.
2971 // Note that view == self here when nextKeyView returns nil, due to AppKit oddness.
2972 // We'll check for both nil and self in case the AppKit oddness goes away.
2973 // WebFrameView has this same kind of logic for the previousValidKeyView case.
2974 if (view == nil || view == self) {
2975 ASSERT([self _frame] != [[self _webView] mainFrame]);
2976 ASSERT(lookInsideWebFrameViews);
2977 view = [[self _bridge] nextValidKeyViewOutsideWebFrameViews];
2984 - (NSView *)previousValidKeyView
2987 if (![self isHiddenOrHasHiddenAncestor]) {
2988 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2991 view = [super previousValidKeyView];
2996 - (BOOL)becomeFirstResponder
2999 if (![[self _webView] _isPerformingProgrammaticFocus]) {
3000 switch ([[self window] keyViewSelectionDirection]) {
3001 case NSDirectSelection:
3003 case NSSelectingNext:
3004 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
3006 case NSSelectingPrevious:
3007 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
3012 [[self window] makeFirstResponder:view];
3014 [self updateFocusState];
3015 [self _updateFontPanel];
3016 _private->startNewKillRingSequence = YES;
3020 // This approach could be relaxed when dealing with 3228554.
3021 // Some alteration to the selection behavior was done to deal with 3672088.
3022 - (BOOL)resignFirstResponder
3024 BOOL resign = [super resignFirstResponder];
3026 [_private->compController endRevertingChange:NO moveLeft:NO];
3027 _private->resigningFirstResponder = YES;
3028 if (![self maintainsInactiveSelection]) {
3029 if ([[self _webView] _isPerformingProgrammaticFocus]) {
3030 [self deselectText];
3036 [self updateFocusState];
3037 _private->resigningFirstResponder = NO;
3042 //------------------------------------------------------------------------------------
3043 // WebDocumentView protocol
3044 //------------------------------------------------------------------------------------
3045 - (void)setDataSource:(WebDataSource *)dataSource
3049 - (void)dataSourceUpdated:(WebDataSource *)dataSource
3053 // Does setNeedsDisplay:NO as a side effect when printing is ending.
3054 // pageWidth != 0 implies we will relayout to a new width
3055 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
3057 WebFrame *frame = [self _frame];
3058 NSArray *subframes = [frame childFrames];
3059 unsigned n = [subframes count];
3061 for (i = 0; i != n; ++i) {
3062 WebFrame *subframe = [subframes objectAtIndex:i];
3063 WebFrameView *frameView = [subframe frameView];
3064 if ([[subframe dataSource] _isDocumentHTML]) {
3065 [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
3069 if (printing != _private->printing) {
3070 [_private->pageRects release];
3071 _private->pageRects = nil;
3072 _private->printing = printing;
3073 [self setNeedsToApplyStyles:YES];
3074 [self setNeedsLayout:YES];
3075 [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
3077 // Can't do this when starting printing or nested printing won't work, see 3491427.
3078 [self setNeedsDisplay:NO];
3083 - (BOOL)canPrintHeadersAndFooters
3088 // This is needed for the case where the webview is embedded in the view that's being printed.
3089 // It shouldn't be called when the webview is being printed directly.
3090 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
3092 // This helps when we print as part of a larger print process.
3093 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
3094 BOOL wasInPrintingMode = _private->printing;
3095 if (!wasInPrintingMode) {
3096 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3099 [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
3101 if (!wasInPrintingMode) {
3102 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3106 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
3108 NSPrintInfo *printInfo = [printOperation printInfo];
3109 return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
3112 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
3114 float viewWidth = NSWidth([self bounds]);
3115 if (viewWidth < 1) {
3116 ERROR("%@ has no width when printing", self);
3120 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3121 float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
3122 float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
3123 return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
3126 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
3127 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
3128 // if AppKit makes it SPI/API.
3129 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation
3131 return [self _scaleFactorForPrintOperation:printOperation];
3134 // This is used for Carbon printing. At some point we might want to make this public API.
3135 - (void)setPageWidthForPrinting:(float)pageWidth
3137 [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
3138 [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
3142 // Return the number of pages available for printing
3143 - (BOOL)knowsPageRange:(NSRangePointer)range {
3144 // Must do this explicit display here, because otherwise the view might redisplay while the print
3145 // sheet was up, using printer fonts (and looking different).
3146 [self displayIfNeeded];
3147 [[self window] setAutodisplay:NO];
3149 // If we are a frameset just print with the layout we have onscreen, otherwise relayout
3150 // according to the paper size
3151 float minLayoutWidth = 0.0;
3152 float maxLayoutWidth = 0.0;
3153 if (![[self _bridge] isFrameSet]) {
3154 float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
3155 minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
3156 maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
3158 [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
3159 [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
3161 // There is a theoretical chance that someone could do some drawing between here and endDocument,
3162 // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
3163 // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
3165 range->location = 1;
3166 NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
3167 float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
3168 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3169 [_private->pageRects release];
3170 NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
3171 printHeight:floorf([self _calculatePrintHeight]/totalScaleFactor)];
3172 // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
3173 // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
3174 // a blank page (with correct-looking header and footer if that option is on), which matches
3175 // the behavior of IE and Camino at least.
3176 if ([newPageRects count] == 0) {
3177 newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
3179 _private->pageRects = [newPageRects retain];
3181 range->length = [_private->pageRects count];
3186 // Return the drawing rectangle for a particular page number
3187 - (NSRect)rectForPage:(int)page {
3188 return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
3191 - (void)drawPageBorderWithSize:(NSSize)borderSize
3193 ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));
3194 [[self _webView] _drawHeaderAndFooter];
3197 - (void)beginDocument
3200 [super beginDocument];
3202 // Exception during [super beginDocument] means that endDocument will not get called,
3203 // so we need to clean up our "print mode" here.
3204 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
3205 [[self window] setAutodisplay:YES];
3211 [super endDocument];
3212 // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO
3213 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
3214 [[self window] setAutodisplay:YES];
3217 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
3219 // Work around this bug:
3220 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
3221 [NSKeyBindingManager sharedKeyBindingManager];
3223 // Use the isEditable state to determine whether or not to process tab key events.
3224 // The idea here is that isEditable will be NO when this WebView is being used
3225 // in a browser, and we desire the behavior where tab moves to the next element
3226 // in tab order. If isEditable is YES, it is likely that the WebView is being
3227 // embedded as the whole view, as in Mail, and tabs should input tabs as expected
3228 // in a text editor.
3229 if (![[self _webView] isEditable] && [event _web_isTabKeyEvent])
3232 // Now process the key normally
3233 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
3237 - (void)keyDown:(NSEvent *)event
3241 BOOL callSuper = NO;
3243 _private->keyDownEvent = event;
3245 WebBridge *bridge = [self _bridge];
3246 if ([bridge interceptKeyEvent:event toView:self]) {
3247 // WebCore processed a key event, bail on any outstanding complete: UI
3248 [_private->compController endRevertingChange:YES moveLeft:NO];
3249 } else if (_private->compController && [_private->compController filterKeyDown:event]) {
3250 // Consumed by complete: popup window
3252 // We're going to process a key event, bail on any outstanding complete: UI
3253 [_private->compController endRevertingChange:YES moveLeft:NO];
3254 if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
3255 // Consumed by key bindings manager.
3261 [super keyDown:event];
3263 [NSCursor setHiddenUntilMouseMoves:YES];
3266 _private->keyDownEvent = nil;
3271 - (void)keyUp:(NSEvent *)event
3275 if (![[self _bridge] interceptKeyEvent:event toView:self]) {
3276 [super keyUp:event];
3282 - (id)accessibilityAttributeValue:(NSString*)attributeName
3284 if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
3285 id accTree = [[self _bridge] accessibilityTree];
3287 return [NSArray arrayWithObject: accTree];
3290 return [super accessibilityAttributeValue:attributeName];
3293 - (id)accessibilityFocusedUIElement
3295 id accTree = [[self _bridge] accessibilityTree];
3297 return [accTree accessibilityFocusedUIElement];
3302 - (id)accessibilityHitTest:(NSPoint)point
3304 id accTree = [[self _bridge] accessibilityTree];
3306 NSPoint windowCoord = [[self window] convertScreenToBase: point];
3307 return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
3313 - (id)_accessibilityParentForSubview:(NSView *)subview
3315 id accTree = [[self _bridge] accessibilityTree];
3319 id parent = [accTree _accessibilityParentForSubview:subview];
3326 - (void)centerSelectionInVisibleArea:(id)sender
3328 [[self _bridge] centerSelectionInVisibleArea];
3331 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
3333 WebBridge *bridge = [self _bridge];
3334 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
3335 WebView *webView = [self _webView];
3336 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3337 [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
3341 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
3343 WebBridge *bridge = [self _bridge];
3344 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
3345 WebView *webView = [self _webView];
3346 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3347 [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
3351 - (void)moveBackward:(id)sender
3353 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
3356 - (void)moveBackwardAndModifySelection:(id)sender
3358 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
3361 - (void)moveDown:(id)sender
3363 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
3366 - (void)moveDownAndModifySelection:(id)sender
3368 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
3371 - (void)moveForward:(id)sender
3373 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
3376 - (void)moveForwardAndModifySelection:(id)sender
3378 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
3381 - (void)moveLeft:(id)sender
3383 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
3386 - (void)moveLeftAndModifySelection:(id)sender
3388 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
3391 - (void)moveRight:(id)sender
3393 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
3396 - (void)moveRightAndModifySelection:(id)sender
3398 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
3401 - (void)moveToBeginningOfDocument:(id)sender
3403 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
3406 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
3408 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
3411 - (void)moveToBeginningOfLine:(id)sender
3413 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3416 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
3418 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3421 - (void)moveToBeginningOfParagraph:(id)sender
3423 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3426 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
3428 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3431 - (void)moveToEndOfDocument:(id)sender
3433 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3436 - (void)moveToEndOfDocumentAndModifySelection:(id)sender