3 Copyright 2002, Apple, Inc. All rights reserved.
6 #import <WebKit/WebHTMLView.h>
9 #import <WebKit/DOMExtensions.h>
10 #import <WebKit/WebArchive.h>
11 #import <WebKit/WebBridge.h>
12 #import <WebKit/WebClipView.h>
13 #import <WebKit/WebDataProtocol.h>
14 #import <WebKit/WebDataSourcePrivate.h>
15 #import <WebKit/WebDocumentInternal.h>
16 #import <WebKit/WebDOMOperationsPrivate.h>
17 #import <WebKit/WebEditingDelegate.h>
18 #import <WebKit/WebException.h>
19 #import <WebKit/WebFramePrivate.h>
20 #import <WebKit/WebFrameViewInternal.h>
21 #import <WebKit/WebHTMLViewInternal.h>
22 #import <WebKit/WebHTMLRepresentationPrivate.h>
23 #import <WebKit/WebImageRenderer.h>
24 #import <WebKit/WebImageRendererFactory.h>
25 #import <WebKit/WebKitLogging.h>
26 #import <WebKit/WebKitNSStringExtras.h>
27 #import <WebKit/WebNetscapePluginEmbeddedView.h>
28 #import <WebKit/WebNSEventExtras.h>
29 #import <WebKit/WebNSImageExtras.h>
30 #import <WebKit/WebNSObjectExtras.h>
31 #import <WebKit/WebNSPasteboardExtras.h>
32 #import <WebKit/WebNSPrintOperationExtras.h>
33 #import <WebKit/WebNSURLExtras.h>
34 #import <WebKit/WebNSViewExtras.h>
35 #import <WebKit/WebPluginController.h>
36 #import <WebKit/WebPreferences.h>
37 #import <WebKit/WebPreferencesPrivate.h>
38 #import <WebKit/WebResourcePrivate.h>
39 #import <WebKit/WebStringTruncator.h>
40 #import <WebKit/WebTextRenderer.h>
41 #import <WebKit/WebTextRendererFactory.h>
42 #import <WebKit/WebUIDelegatePrivate.h>
43 #import <WebKit/WebUnicode.h>
44 #import <WebKit/WebViewInternal.h>
45 #import <WebKit/WebViewPrivate.h>
47 #import <AppKit/NSAccessibility.h>
48 #import <AppKit/NSGraphicsContextPrivate.h>
49 #import <AppKit/NSResponder_Private.h>
51 #import <Foundation/NSFileManager_NSURLExtras.h>
52 #import <Foundation/NSURL_NSURLExtras.h>
53 #import <Foundation/NSURLFileTypeMappings.h>
55 #import <CoreGraphics/CGContextGState.h>
57 // Included to help work around this bug:
58 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
59 #import <AppKit/NSKeyBindingManager.h>
61 // Kill ring calls. Would be better to use NSKillRing.h, but that's not available in SPI.
62 void _NSInitializeKillRing(void);
63 void _NSAppendToKillRing(NSString *);
64 void _NSPrependToKillRing(NSString *);
65 NSString *_NSYankFromKillRing(void);
66 NSString *_NSYankPreviousFromKillRing(void);
67 void _NSNewKillRingSequence(void);
68 void _NSSetKillRingToYankedState(void);
69 void _NSResetKillRingOperationFlag(void);
71 @interface NSView (AppKitSecretsIKnowAbout)
72 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
73 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
75 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
76 - (void)_propagateDirtyRectsToOpaqueAncestors;
79 @interface NSApplication (AppKitSecretsIKnowAbout)
80 - (void)speakString:(NSString *)string;
83 @interface NSWindow (AppKitSecretsIKnowAbout)
84 - (id)_newFirstResponderAfterResigning;
87 @interface NSAttributedString (AppKitSecretsIKnowAbout)
88 - (id)_initWithDOMRange:(DOMRange *)domRange;
89 - (DOMDocumentFragment *)_documentFromRange:(NSRange)range document:(DOMDocument *)document documentAttributes:(NSDictionary *)dict subresources:(NSArray **)subresources;
92 @interface NSSpellChecker (CurrentlyPrivateForTextView)
93 - (void)learnWord:(NSString *)word;
96 // By imaging to a width a little wider than the available pixels,
97 // thin pages will be scaled down a little, matching the way they
98 // print in IE and Camino. This lets them use fewer sheets than they
99 // would otherwise, which is presumably why other browsers do this.
100 // Wide pages will be scaled down more than this.
101 #define PrintingMinimumShrinkFactor 1.25
103 // This number determines how small we are willing to reduce the page content
104 // in order to accommodate the widest line. If the page would have to be
105 // reduced smaller to make the widest line fit, we just clip instead (this
106 // behavior matches MacIE and Mozilla, at least)
107 #define PrintingMaximumShrinkFactor 2.0
109 #define AUTOSCROLL_INTERVAL 0.1
111 #define DRAG_LABEL_BORDER_X 4.0
112 #define DRAG_LABEL_BORDER_Y 2.0
113 #define DRAG_LABEL_RADIUS 5.0
114 #define DRAG_LABEL_BORDER_Y_OFFSET 2.0
116 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP 120.0
117 #define MAX_DRAG_LABEL_WIDTH 320.0
119 #define DRAG_LINK_LABEL_FONT_SIZE 11.0
120 #define DRAG_LINK_URL_FONT_SIZE 10.0
122 #ifndef OMIT_TIGER_FEATURES
123 #define USE_APPKIT_FOR_ATTRIBUTED_STRINGS
126 // Any non-zero value will do, but using something recognizable might help us debug some day.
127 #define TRACKING_RECT_TAG 0xBADFACE
129 // FIXME: This constant is copied from AppKit's _NXSmartPaste constant.
130 #define WebSmartPastePboardType @"NeXT smart paste pasteboard type"
132 static BOOL forceRealHitTest = NO;
134 @interface WebHTMLView (WebTextSizing) <_web_WebDocumentTextSizing>
137 @interface WebHTMLView (WebHTMLViewFileInternal)
138 - (BOOL)_imageExistsAtPaths:(NSArray *)paths;
139 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
140 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
141 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
142 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action;
143 - (float)_calculatePrintHeight;
144 - (void)_updateTextSizeMultiplier;
145 - (DOMRange *)_selectedRange;
146 - (BOOL)_shouldDeleteRange:(DOMRange *)range;
147 - (void)_deleteRange:(DOMRange *)range
148 preflight:(BOOL)preflight
149 killRing:(BOOL)killRing
150 prepend:(BOOL)prepend
151 smartDeleteOK:(BOOL)smartDeleteOK;
152 - (void)_deleteSelection;
153 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard;
156 @interface WebHTMLView (WebForwardDeclaration) // FIXME: Put this in a normal category and stop doing the forward declaration trick.
157 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize;
160 @interface WebHTMLView (WebNSTextInputSupport) <NSTextInput>
161 - (void)_updateSelectionForInputManager;
162 - (void)_insertText:(NSString *)text selectInsertedText:(BOOL)selectText;
165 @interface WebHTMLView (WebEditingStyleSupport)
166 - (DOMCSSStyleDeclaration *)_emptyStyle;
167 - (NSString *)_colorAsString:(NSColor *)color;
170 @interface NSView (WebHTMLViewFileInternal)
171 - (void)_web_setPrintingModeRecursive;
172 - (void)_web_clearPrintingModeRecursive;
173 - (void)_web_layoutIfNeededRecursive;
174 - (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
177 @interface NSMutableDictionary (WebHTMLViewFileInternal)
178 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
181 // Handles the complete: text command
182 @interface WebTextCompleteController : NSObject
186 NSWindow *_popupWindow;
187 NSTableView *_tableView;
188 NSArray *_completions;
189 NSString *_originalString;
192 - (id)initWithHTMLView:(WebHTMLView *)view;
193 - (void)doCompletion;
194 - (void)endRevertingChange:(BOOL)revertChange moveLeft:(BOOL)goLeft;
195 - (BOOL)filterKeyDown:(NSEvent *)event;
196 - (void)_reflectSelection;
199 @implementation WebHTMLViewPrivate
203 ASSERT(autoscrollTimer == nil);
204 ASSERT(autoscrollTriggerEvent == nil);
206 [mouseDownEvent release];
207 [draggingImageURL release];
208 [pluginController release];
210 [compController release];
211 [firstResponderAtMouseDownTime release];
218 @implementation WebHTMLView (WebHTMLViewFileInternal)
220 - (BOOL)_imageExistsAtPaths:(NSArray *)paths
222 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
223 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
224 NSEnumerator *enumerator = [paths objectEnumerator];
227 while ((path = [enumerator nextObject]) != nil) {
228 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
229 if ([imageMIMETypes containsObject:MIMEType]) {
237 - (DOMDocumentFragment *)_documentFragmentWithPaths:(NSArray *)paths
239 DOMDocumentFragment *fragment = [[[self _bridge] DOMDocument] createDocumentFragment];
240 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
241 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
242 NSEnumerator *enumerator = [paths objectEnumerator];
243 WebDataSource *dataSource = [self _dataSource];
246 while ((path = [enumerator nextObject]) != nil) {
247 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
248 if ([imageMIMETypes containsObject:MIMEType]) {
249 WebResource *resource = [[WebResource alloc] initWithData:[NSData dataWithContentsOfFile:path]
250 URL:[NSURL fileURLWithPath:path]
255 [fragment appendChild:[dataSource _imageElementWithImageResource:resource]];
261 return [fragment firstChild] != nil ? fragment : nil;
264 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
266 NSArray *types = [pasteboard types];
268 if ([types containsObject:WebArchivePboardType]) {
269 WebArchive *archive = [[WebArchive alloc] initWithData:[pasteboard dataForType:WebArchivePboardType]];
271 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithArchive:archive];
279 if ([types containsObject:NSFilenamesPboardType]) {
280 DOMDocumentFragment *fragment = [self _documentFragmentWithPaths:[pasteboard propertyListForType:NSFilenamesPboardType]];
281 if (fragment != nil) {
288 if ([types containsObject:NSHTMLPboardType]) {
289 NSString *HTMLString = [pasteboard stringForType:NSHTMLPboardType];
290 // This is a hack to make Microsoft's HTML pasteboard data work. See 3778785.
291 if ([HTMLString hasPrefix:@"Version:"]) {
292 NSRange range = [HTMLString rangeOfString:@"<html" options:NSCaseInsensitiveSearch];
293 if (range.location != NSNotFound) {
294 HTMLString = [HTMLString substringFromIndex:range.location];
297 if ([HTMLString length] != 0) {
298 return [[self _bridge] documentFragmentWithMarkupString:HTMLString baseURLString:nil];
302 if ([types containsObject:NSTIFFPboardType]) {
303 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSTIFFPboardType]
304 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.tiff"]
305 MIMEType:@"image/tiff"
308 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
313 if ([types containsObject:NSPICTPboardType]) {
314 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSPICTPboardType]
315 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.pict"]
316 MIMEType:@"image/pict"
319 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
324 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
325 NSAttributedString *string = nil;
326 if ([types containsObject:NSRTFDPboardType]) {
327 string = [[NSAttributedString alloc] initWithRTFD:[pasteboard dataForType:NSRTFDPboardType] documentAttributes:NULL];
329 if (string == nil && [types containsObject:NSRTFPboardType]) {
330 string = [[NSAttributedString alloc] initWithRTF:[pasteboard dataForType:NSRTFPboardType] documentAttributes:NULL];
333 NSArray *elements = [[NSArray alloc] initWithObjects:
334 // Omit style since we want style to be inline so the fragment can be easily inserted.
336 NSDictionary *documentAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:
337 elements, NSExcludedElementsDocumentAttribute,
338 self, @"WebResourceHandler", nil];
340 NSArray *subresources;
341 DOMDocumentFragment *fragment = [string _documentFromRange:NSMakeRange(0, [string length])
342 document:[[self _bridge] DOMDocument]
343 documentAttributes:documentAttributes
344 subresources:&subresources];
345 [documentAttributes release];
351 if ((URL = [NSURL URLFromPasteboard:pasteboard])) {
352 NSString *URLString = [URL _web_userVisibleString];
353 if ([URLString length] > 0) {
354 return [[self _bridge] documentFragmentWithText:URLString];
358 if (allowPlainText && [types containsObject:NSStringPboardType]) {
359 return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
365 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
366 - (WebResource *)resourceForData:(NSData *)data preferredFilename:(NSString *)name
368 // This method is called by [NSAttributedString _documentFromRange::::]
369 // which uses the URL of the resource for the fragment that it returns.
370 NSString *extension = [name pathExtension];
371 NSString *MIMEType = nil;
372 if ([extension length] != 0) {
373 MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
375 // Only support image resources.
376 if (MIMEType == nil || ![[[WebImageRendererFactory sharedFactory] supportedMIMETypes] containsObject:MIMEType]) {
379 NSURL *URL = [NSURL _web_URLWithUserTypedString:[NSString stringWithFormat:@"/%@", name] relativeToURL:[NSURL _web_uniqueWebDataURL]];
380 WebResource *resource = [[[WebResource alloc] initWithData:data
384 frameName:nil] autorelease];
385 [[self _dataSource] addSubresource:resource];
390 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
392 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:allowPlainText];
393 WebBridge *bridge = [self _bridge];
394 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[self _selectedRange] givenAction:WebViewInsertActionPasted]) {
395 [bridge replaceSelectionWithFragment:fragment selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
399 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
401 WebView *webView = [self _webView];
402 DOMNode *child = [fragment firstChild];
403 if ([fragment lastChild] == child && [child isKindOfClass:[DOMCharacterData class]]) {
404 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:[(DOMCharacterData *)child data] replacingDOMRange:range givenAction:action];
406 return [[webView _editingDelegateForwarder] webView:webView shouldInsertNode:fragment replacingDOMRange:range givenAction:action];
410 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action
412 WebView *webView = [self _webView];
413 DOMRange *selectedRange = [self _selectedRange];
414 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:selectedRange givenAction:action];
417 // Calculate the vertical size of the view that fits on a single page
418 - (float)_calculatePrintHeight
420 // Obtain the print info object for the current operation
421 NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
423 // Calculate the page height in points
424 NSSize paperSize = [pi paperSize];
425 return paperSize.height - [pi topMargin] - [pi bottomMargin];
428 - (void)_updateTextSizeMultiplier
430 [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];
433 - (DOMRange *)_selectedRange
435 return [[self _bridge] selectedDOMRange];
438 - (BOOL)_shouldDeleteRange:(DOMRange *)range
440 if (range == nil || [range collapsed])
442 WebView *webView = [self _webView];
443 return [[webView _editingDelegateForwarder] webView:webView shouldDeleteDOMRange:range];
446 - (void)_deleteRange:(DOMRange *)range
447 preflight:(BOOL)preflight
448 killRing:(BOOL)killRing
449 prepend:(BOOL)prepend
450 smartDeleteOK:(BOOL)smartDeleteOK
452 if (![self _shouldDeleteRange:range]) {
455 WebBridge *bridge = [self _bridge];
456 if (killRing && _private->startNewKillRingSequence) {
457 _NSNewKillRingSequence();
459 [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityUpstream];
462 _NSPrependToKillRing([bridge selectedString]);
464 _NSAppendToKillRing([bridge selectedString]);
466 _private->startNewKillRingSequence = NO;
468 BOOL smartDelete = smartDeleteOK ? [self _canSmartCopyOrDelete] : NO;
469 [bridge deleteSelectionWithSmartDelete:smartDelete];
472 - (void)_deleteSelection
474 [self _deleteRange:[self _selectedRange]
481 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard
483 return [[self _webView] smartInsertDeleteEnabled] && [[pasteboard types] containsObject:WebSmartPastePboardType];
488 @implementation WebHTMLView (WebPrivate)
492 [WebImageRenderer stopAnimationsInView:self];
495 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
497 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
498 location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
499 modifierFlags:[flagsChangedEvent modifierFlags]
500 timestamp:[flagsChangedEvent timestamp]
501 windowNumber:[flagsChangedEvent windowNumber]
502 context:[flagsChangedEvent context]
503 eventNumber:0 clickCount:0 pressure:0];
505 // Pretend it's a mouse move.
506 [[NSNotificationCenter defaultCenter]
507 postNotificationName:NSMouseMovedNotification object:self
508 userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
511 - (void)_updateMouseoverWithFakeEvent
513 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
514 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
515 modifierFlags:[[NSApp currentEvent] modifierFlags]
516 timestamp:[NSDate timeIntervalSinceReferenceDate]
517 windowNumber:[[self window] windowNumber]
518 context:[[NSApp currentEvent] context]
519 eventNumber:0 clickCount:0 pressure:0];
521 [self _updateMouseoverWithEvent:fakeEvent];
524 - (void)_frameOrBoundsChanged
526 if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
527 [self setNeedsLayout:YES];
528 [self setNeedsDisplay:YES];
529 [_private->compController endRevertingChange:NO moveLeft:NO];
532 NSPoint origin = [[self superview] bounds].origin;
533 if (!NSEqualPoints(_private->lastScrollPosition, origin)) {
534 [[self _bridge] sendScrollEvent];
535 [_private->compController endRevertingChange:NO moveLeft:NO];
537 _private->lastScrollPosition = origin;
539 SEL selector = @selector(_updateMouseoverWithFakeEvent);
540 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
541 [self performSelector:selector withObject:nil afterDelay:0];
544 - (void)_setAsideSubviews
546 ASSERT(!_private->subviewsSetAside);
547 ASSERT(_private->savedSubviews == nil);
548 _private->savedSubviews = _subviews;
550 _private->subviewsSetAside = YES;
553 - (void)_restoreSubviews
555 ASSERT(_private->subviewsSetAside);
556 ASSERT(_subviews == nil);
557 _subviews = _private->savedSubviews;
558 _private->savedSubviews = nil;
559 _private->subviewsSetAside = NO;
562 // This is called when we are about to draw, but before our dirty rect is propagated to our ancestors.
563 // That's the perfect time to do a layout, except that ideally we'd want to be sure that we're dirty
564 // before doing it. As a compromise, when we're opaque we do the layout only when actually asked to
565 // draw, but when we're transparent we do the layout at this stage so views behind us know that they
566 // need to be redrawn (in case the layout causes some things to get dirtied).
567 - (void)_propagateDirtyRectsToOpaqueAncestors
569 if (![[self _webView] drawsBackground]) {
570 [self _web_layoutIfNeededRecursive];
572 [super _propagateDirtyRectsToOpaqueAncestors];
575 // Don't let AppKit even draw subviews. We take care of that.
576 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
578 // This helps when we print as part of a larger print process.
579 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
580 BOOL wasInPrintingMode = _private->printing;
581 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
582 if (wasInPrintingMode != isPrinting) {
584 [self _web_setPrintingModeRecursive];
586 [self _web_clearPrintingModeRecursive];
590 [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
592 [self _setAsideSubviews];
593 [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
594 rectIsVisibleRectForView:visibleView topView:topView];
595 [self _restoreSubviews];
597 if (wasInPrintingMode != isPrinting) {
598 if (wasInPrintingMode) {
599 [self _web_setPrintingModeRecursive];
601 [self _web_clearPrintingModeRecursive];
606 // Don't let AppKit even draw subviews. We take care of that.
607 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
609 BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
611 BOOL wasInPrintingMode = _private->printing;
612 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
614 if (needToSetAsideSubviews) {
615 // This helps when we print as part of a larger print process.
616 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
617 if (wasInPrintingMode != isPrinting) {
619 [self _web_setPrintingModeRecursive];
621 [self _web_clearPrintingModeRecursive];
625 [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
627 [self _setAsideSubviews];
630 [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
632 if (needToSetAsideSubviews) {
633 if (wasInPrintingMode != isPrinting) {
634 if (wasInPrintingMode) {
635 [self _web_setPrintingModeRecursive];
637 [self _web_clearPrintingModeRecursive];
641 [self _restoreSubviews];
645 - (BOOL)_insideAnotherHTMLView
648 while ((view = [view superview])) {
649 if ([view isKindOfClass:[WebHTMLView class]]) {
656 - (void)scrollPoint:(NSPoint)point
658 // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
659 // If we get called during the handling of a key down event, we assume the call came from
660 // NSTextView, and ignore it and use our own code to decide how to page up and page down
661 // We are smarter about how far to scroll, and we have "superview scrolling" logic.
662 NSEvent *event = [[self window] currentEvent];
663 if ([event type] == NSKeyDown) {
664 const unichar pageUp = NSPageUpFunctionKey;
665 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
666 [self tryToPerform:@selector(scrollPageUp:) with:nil];
669 const unichar pageDown = NSPageDownFunctionKey;
670 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
671 [self tryToPerform:@selector(scrollPageDown:) with:nil];
676 [super scrollPoint:point];
679 - (NSView *)hitTest:(NSPoint)point
681 // WebHTMLView objects handle all left mouse clicks for objects inside them.
682 // That does not include left mouse clicks with the control key held down.
683 BOOL captureHitsOnSubviews;
684 if (forceRealHitTest) {
685 captureHitsOnSubviews = NO;
687 NSEvent *event = [[self window] currentEvent];
688 captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
690 if (!captureHitsOnSubviews) {
691 return [super hitTest:point];
693 if ([[self superview] mouse:point inRect:[self frame]]) {
699 static WebHTMLView *lastHitView = nil;
701 - (void)_clearLastHitViewIfSelf
703 if (lastHitView == self) {
708 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
710 ASSERT(_private->trackingRectOwner == nil);
711 _private->trackingRectOwner = owner;
712 _private->trackingRectUserData = data;
713 return TRACKING_RECT_TAG;
716 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
718 ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
719 ASSERT(_private->trackingRectOwner == nil);
720 _private->trackingRectOwner = owner;
721 _private->trackingRectUserData = data;
722 return TRACKING_RECT_TAG;
725 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
728 ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
729 ASSERT(_private->trackingRectOwner == nil);
730 _private->trackingRectOwner = owner;
731 _private->trackingRectUserData = userDataList[0];
732 trackingNums[0] = TRACKING_RECT_TAG;
735 - (void)removeTrackingRect:(NSTrackingRectTag)tag
739 ASSERT(tag == TRACKING_RECT_TAG);
740 if (_private != nil) {
741 _private->trackingRectOwner = nil;
745 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
748 for (i = 0; i < count; ++i) {
752 ASSERT(tag == TRACKING_RECT_TAG);
753 if (_private != nil) {
754 _private->trackingRectOwner = nil;
759 - (void)_sendToolTipMouseExited
761 // Nothing matters except window, trackingNumber, and userData.
762 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
763 location:NSMakePoint(0, 0)
766 windowNumber:[[self window] windowNumber]
769 trackingNumber:TRACKING_RECT_TAG
770 userData:_private->trackingRectUserData];
771 [_private->trackingRectOwner mouseExited:fakeEvent];
774 - (void)_sendToolTipMouseEntered
776 // Nothing matters except window, trackingNumber, and userData.
777 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
778 location:NSMakePoint(0, 0)
781 windowNumber:[[self window] windowNumber]
784 trackingNumber:TRACKING_RECT_TAG
785 userData:_private->trackingRectUserData];
786 [_private->trackingRectOwner mouseEntered:fakeEvent];
789 - (void)_setToolTip:(NSString *)string
791 NSString *toolTip = [string length] == 0 ? nil : string;
792 NSString *oldToolTip = _private->toolTip;
793 if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
797 [self _sendToolTipMouseExited];
798 [oldToolTip release];
800 _private->toolTip = [toolTip copy];
802 [self removeAllToolTips];
803 NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
804 [self addToolTipRect:wideOpenRect owner:self userData:NULL];
805 [self _sendToolTipMouseEntered];
809 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
811 return [[_private->toolTip copy] autorelease];
814 - (void)_updateMouseoverWithEvent:(NSEvent *)event
816 WebHTMLView *view = nil;
817 if ([event window] == [self window]) {
818 forceRealHitTest = YES;
819 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
820 forceRealHitTest = NO;
822 if ([hitView isKindOfClass:[WebHTMLView class]]) {
823 view = (WebHTMLView *)hitView;
826 hitView = [hitView superview];
830 if (lastHitView != view && lastHitView != nil) {
831 // If we are moving out of a view (or frame), let's pretend the mouse moved
832 // all the way out of that view. But we have to account for scrolling, because
833 // khtml doesn't understand our clipping.
834 NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
835 float yScroll = visibleRect.origin.y;
836 float xScroll = visibleRect.origin.x;
838 event = [NSEvent mouseEventWithType:NSMouseMoved
839 location:NSMakePoint(-1 - xScroll, -1 - yScroll )
840 modifierFlags:[[NSApp currentEvent] modifierFlags]
841 timestamp:[NSDate timeIntervalSinceReferenceDate]
842 windowNumber:[[self window] windowNumber]
843 context:[[NSApp currentEvent] context]
844 eventNumber:0 clickCount:0 pressure:0];
845 [[lastHitView _bridge] mouseMoved:event];
850 NSDictionary *element;
854 [[view _bridge] mouseMoved:event];
856 NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
857 element = [view elementAtPoint:point];
860 // Have the web view send a message to the delegate so it can do status bar display.
861 [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
863 // Set a tool tip; it won't show up right away but will if the user pauses.
864 NSString *newToolTip = nil;
865 if (_private->showsURLsInToolTips) {
866 newToolTip = [[element objectForKey:WebCoreElementLinkURLKey] _web_userVisibleString];
868 if (newToolTip == nil) {
869 newToolTip = [element objectForKey:WebCoreElementTitleKey];
871 [self _setToolTip:newToolTip];
874 + (NSArray *)_insertablePasteboardTypes
876 static NSArray *types = nil;
878 types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
879 NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType,
880 NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
885 + (NSArray *)_selectionPasteboardTypes
887 // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
888 return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFPboardType, NSRTFDPboardType, NSStringPboardType, nil];
891 - (WebArchive *)_selectedArchive
895 double start = CFAbsoluteTimeGetCurrent();
897 NSString *markupString = [[self _bridge] markupStringFromRange:[self _selectedRange] nodes:&nodes];
899 double duration = CFAbsoluteTimeGetCurrent() - start;
900 LOG(Timing, "copying markup took %f seconds.", duration);
903 return [[self _dataSource] _archiveWithMarkupString:markupString nodes:nodes];
906 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
908 ASSERT([self _hasSelection]);
909 NSArray *types = [self pasteboardTypesForSelection];
910 [pasteboard declareTypes:types owner:nil];
911 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
914 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
916 NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
918 BOOL drawURLString = YES;
919 BOOL clipURLString = NO, clipLabelString = NO;
921 NSString *label = [element objectForKey: WebElementLinkLabelKey];
922 NSString *urlString = [linkURL _web_userVisibleString];
929 NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
930 toHaveTrait:NSBoldFontMask];
931 NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
933 labelSize.width = [label _web_widthWithFont: labelFont];
934 labelSize.height = [labelFont ascender] - [labelFont descender];
935 if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
936 labelSize.width = MAX_DRAG_LABEL_WIDTH;
937 clipLabelString = YES;
940 NSSize imageSize, urlStringSize;
941 imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
942 imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
944 urlStringSize.width = [urlString _web_widthWithFont: urlFont];
945 urlStringSize.height = [urlFont ascender] - [urlFont descender];
946 imageSize.height += urlStringSize.height;
947 if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
948 imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
951 imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
954 NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
955 [dragImage lockFocus];
957 [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
959 // Drag a rectangle with rounded corners/
960 NSBezierPath *path = [NSBezierPath bezierPath];
961 [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
962 [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
963 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
964 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
966 [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
967 [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
968 [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
971 NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
972 NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
975 urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
977 [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender])
978 withTopColor:topColor bottomColor:bottomColor font:urlFont];
982 label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
983 [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
984 withTopColor:topColor bottomColor:bottomColor font:labelFont];
986 [dragImage unlockFocus];
991 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
993 NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
994 NSDictionary *element = [self elementAtPoint:mouseDownPoint];
996 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
997 NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
998 BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
1000 [_private->draggingImageURL release];
1001 _private->draggingImageURL = nil;
1003 NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
1004 _private->webCoreDragOp = op; // will be DragNone if WebCore doesn't care
1005 NSImage *dragImage = nil;
1008 // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
1009 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
1010 // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
1012 dragImage = wcDragImage;
1013 // wcDragLoc is the cursor position relative to the lower-left corner of the image.
1014 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
1017 dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
1019 dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
1021 _private->dragOffset = wcDragLoc;
1024 WebView *webView = [self _webView];
1025 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
1026 WebImageRenderer *image = [element objectForKey:WebElementImageKey];
1027 BOOL startedDrag = YES; // optimism - we almost always manage to start the drag
1029 // note per kwebster, the offset arg below is always ignored in positioning the image
1030 if (imageURL != nil && image != nil && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1032 if (!dhtmlWroteData) {
1033 // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
1034 DOMHTMLElement *imageElement = [element objectForKey:WebElementDOMNodeKey];
1035 ASSERT(imageElement != nil);
1036 [webView setSelectedDOMRange:[[[self _bridge] DOMDocument] _createRangeWithNode:imageElement] affinity:NSSelectionAffinityUpstream];
1037 _private->draggingImageURL = [imageURL retain];
1038 source = [pasteboard _web_declareAndWriteDragImage:image
1039 URL:linkURL ? linkURL : imageURL
1040 title:[element objectForKey:WebElementImageAltStringKey]
1041 archive:[imageElement webArchive]
1044 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
1045 if (dragImage == nil) {
1046 [self _web_dragImage:[element objectForKey:WebElementImageKey]
1047 rect:[[element objectForKey:WebElementImageRectKey] rectValue]
1048 event:_private->mouseDownEvent
1049 pasteboard:pasteboard
1051 offset:&_private->dragOffset];
1053 [self dragImage:dragImage
1056 event:_private->mouseDownEvent
1057 pasteboard:pasteboard
1061 } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1062 if (!dhtmlWroteData) {
1063 NSArray *types = [NSPasteboard _web_writableTypesForURL];
1064 [pasteboard declareTypes:types owner:self];
1065 [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];
1067 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1068 if (dragImage == nil) {
1069 dragImage = [self _dragImageForLinkElement:element];
1070 NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1071 dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1072 _private->dragOffset.x = offset.width;
1073 _private->dragOffset.y = -offset.height; // inverted because we are flipped
1075 // HACK: We should pass the mouseDown event instead of the mouseDragged! This hack gets rid of
1076 // a flash of the image at the mouseDown location when the drag starts.
1077 [self dragImage:dragImage
1080 event:mouseDraggedEvent
1081 pasteboard:pasteboard
1084 } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1085 if (!dhtmlWroteData) {
1086 [self _writeSelectionToPasteboard:pasteboard];
1088 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1089 if (dragImage == nil) {
1090 dragImage = [[self _bridge] selectionImage];
1091 [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1092 NSRect visibleSelectionRect = [[self _bridge] visibleSelectionRect];
1093 dragLoc = NSMakePoint(NSMinX(visibleSelectionRect), NSMaxY(visibleSelectionRect));
1094 _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1095 _private->dragOffset.y = dragLoc.y - mouseDownPoint.y; // inverted because we are flipped
1097 [self dragImage:dragImage
1100 event:_private->mouseDownEvent
1101 pasteboard:pasteboard
1104 } else if (srcIsDHTML) {
1105 ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1106 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1107 if (dragImage == nil) {
1108 // WebCore should have given us an image, but we'll make one up
1109 NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1110 dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1111 NSSize imageSize = [dragImage size];
1112 dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width/2, mouseDownPoint.y + imageSize.height/2);
1113 _private->dragOffset.x = imageSize.width/2;
1114 _private->dragOffset.y = imageSize.height/2; // inverted because we are flipped
1116 [self dragImage:dragImage
1119 event:_private->mouseDownEvent
1120 pasteboard:pasteboard
1124 // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1125 // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1131 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1133 [self autoscroll:event];
1134 [self _startAutoscrollTimer:event];
1137 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1139 NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1140 NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint];
1142 ASSERT([self _webView]);
1143 if ([mouseDownElement objectForKey: WebElementImageKey] != nil &&
1144 [mouseDownElement objectForKey: WebElementImageURLKey] != nil &&
1145 [[[self _webView] preferences] loadsImagesAutomatically] &&
1146 (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1150 if ([mouseDownElement objectForKey:WebElementLinkURLKey] != nil &&
1151 (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1155 if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
1156 (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1163 - (WebPluginController *)_pluginController
1165 return _private->pluginController;
1168 - (void)_web_setPrintingModeRecursive
1170 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1171 [super _web_setPrintingModeRecursive];
1174 - (void)_web_clearPrintingModeRecursive
1176 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1177 [super _web_clearPrintingModeRecursive];
1180 - (void)_layoutIfNeeded
1182 ASSERT(!_private->subviewsSetAside);
1184 if ([[self _bridge] needsLayout])
1185 _private->needsLayout = YES;
1186 if (_private->needsToApplyStyles || _private->needsLayout)
1190 - (void)_web_layoutIfNeededRecursive
1192 [self _layoutIfNeeded];
1193 [super _web_layoutIfNeededRecursive];
1196 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1198 ASSERT(!_private->subviewsSetAside);
1199 displayRect = NSIntersectionRect(displayRect, [self bounds]);
1201 if (!testDirtyRect || [self needsDisplay]) {
1202 if (testDirtyRect) {
1203 NSRect dirtyRect = [self _dirtyRect];
1204 displayRect = NSIntersectionRect(displayRect, dirtyRect);
1206 if (!NSIsEmptyRect(displayRect)) {
1207 [self _layoutIfNeeded];
1211 [super _web_layoutIfNeededRecursive:displayRect testDirtyRect:NO];
1214 - (NSRect)_selectionRect
1216 return [[self _bridge] selectionRect];
1219 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1221 if (_private->autoscrollTimer == nil) {
1222 _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1223 target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1224 _private->autoscrollTriggerEvent = [triggerEvent retain];
1228 - (void)_stopAutoscrollTimer
1230 NSTimer *timer = _private->autoscrollTimer;
1231 _private->autoscrollTimer = nil;
1232 [_private->autoscrollTriggerEvent release];
1233 _private->autoscrollTriggerEvent = nil;
1242 // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1243 // a mouse up event.
1244 PSstilldown([_private->autoscrollTriggerEvent eventNumber], &isStillDown);
1246 [self _stopAutoscrollTimer];
1250 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1251 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1252 modifierFlags:[[NSApp currentEvent] modifierFlags]
1253 timestamp:[NSDate timeIntervalSinceReferenceDate]
1254 windowNumber:[[self window] windowNumber]
1255 context:[[NSApp currentEvent] context]
1256 eventNumber:0 clickCount:0 pressure:0];
1257 [self mouseDragged:fakeEvent];
1262 // Copying can be done regardless of whether you can edit.
1263 return [self _hasSelection];
1268 return [self _hasSelection] && [self _isEditable];
1273 return [self _hasSelection] && [self _isEditable];
1278 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1283 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1286 - (BOOL)_hasSelection
1288 return [[self _bridge] selectionState] == WebSelectionStateRange;
1291 - (BOOL)_hasSelectionOrInsertionPoint
1293 return [[self _bridge] selectionState] != WebSelectionStateNone;
1298 return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1301 - (BOOL)_isSelectionMisspelled
1303 NSString *selectedString = [self selectedString];
1304 unsigned length = [selectedString length];
1308 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1312 inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1314 return range.length == length;
1317 - (NSArray *)_guessesForMisspelledSelection
1319 ASSERT([[self selectedString] length] != 0);
1320 return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1323 - (void)_changeSpellingFromMenu:(id)sender
1325 ASSERT([[self selectedString] length] != 0);
1326 [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1329 - (void)_ignoreSpellingFromMenu:(id)sender
1331 ASSERT([[self selectedString] length] != 0);
1332 [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1335 - (void)_learnSpellingFromMenu:(id)sender
1337 ASSERT([[self selectedString] length] != 0);
1338 [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1341 #if APPKIT_CODE_FOR_REFERENCE
1343 - (void)_openLinkFromMenu:(id)sender
1345 NSTextStorage *text = _getTextStorage(self);
1346 NSRange charRange = [self selectedRange];
1347 if (charRange.location != NSNotFound && charRange.length > 0) {
1348 id link = [text attribute:NSLinkAttributeName atIndex:charRange.location effectiveRange:NULL];
1350 [self clickedOnLink:link atIndex:charRange.location];
1352 NSString *string = [[text string] substringWithRange:charRange];
1353 link = [NSURL URLWithString:string];
1354 if (link) [[NSWorkspace sharedWorkspace] openURL:link];
1361 - (BOOL)_transparentBackground
1363 return _private->transparentBackground;
1366 - (void)_setTransparentBackground:(BOOL)f
1368 _private->transparentBackground = f;
1373 @implementation NSView (WebHTMLViewFileInternal)
1375 - (void)_web_setPrintingModeRecursive
1377 [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1380 - (void)_web_clearPrintingModeRecursive
1382 [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1385 - (void)_web_layoutIfNeededRecursive
1387 [_subviews makeObjectsPerformSelector:@selector(_web_layoutIfNeededRecursive)];
1390 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1392 unsigned index, count;
1393 for (index = 0, count = [_subviews count]; index < count; index++) {
1394 NSView *subview = [_subviews objectAtIndex:index];
1395 NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1396 [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1402 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1404 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1406 if (object == nil) {
1407 [self removeObjectForKey:key];
1409 [self setObject:object forKey:key];
1415 // The following is a workaround for
1416 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1417 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1418 // Since the category will be searched before the real class, we'll prevent the flag from being
1419 // set on the tool tip panel.
1421 @interface NSToolTipPanel : NSPanel
1424 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1427 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1429 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1431 // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1437 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
1440 @interface NSArray (WebHTMLView)
1441 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1444 @implementation WebHTMLView
1448 WebKitInitializeUnicode();
1449 [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes]
1450 returnTypes:[[self class] _insertablePasteboardTypes]];
1451 _NSInitializeKillRing();
1454 - (void)_resetCachedWebPreferences:(NSNotification *)ignored
1456 WebPreferences *preferences = [[self _webView] preferences];
1457 // Check for nil because we might not yet have an associated webView when this is called
1458 if (preferences == nil) {
1459 preferences = [WebPreferences standardPreferences];
1461 _private->showsURLsInToolTips = [preferences showsURLsInToolTips];
1464 - (id)initWithFrame:(NSRect)frame
1466 [super initWithFrame:frame];
1468 // Make all drawing go through us instead of subviews.
1469 if (NSAppKitVersionNumber >= 711) {
1470 [self _setDrawsOwnDescendants:YES];
1473 _private = [[WebHTMLViewPrivate alloc] init];
1475 _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1476 _private->needsLayout = YES;
1477 [self _resetCachedWebPreferences:nil];
1478 [[NSNotificationCenter defaultCenter]
1479 addObserver:self selector:@selector(_resetCachedWebPreferences:)
1480 name:WebPreferencesChangedNotification object:nil];
1487 [self _clearLastHitViewIfSelf];
1489 [[NSNotificationCenter defaultCenter] removeObserver:self];
1490 [_private->pluginController destroyAllPlugins];
1498 [self _clearLastHitViewIfSelf];
1500 [[NSNotificationCenter defaultCenter] removeObserver:self];
1501 [_private->pluginController destroyAllPlugins];
1506 - (IBAction)takeFindStringFromSelection:(id)sender
1508 if (![self _hasSelection]) {
1513 [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1516 - (NSArray *)pasteboardTypesForSelection
1518 if ([self _canSmartCopyOrDelete]) {
1519 NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1520 [types addObject:WebSmartPastePboardType];
1523 return [[self class] _selectionPasteboardTypes];
1527 // This method is copied from NSTextView
1528 - (NSAttributedString *)_stripAttachmentCharactersFromAttributedString:(NSAttributedString *)originalAttributedString
1530 NSRange attachmentRange;
1531 NSString *originalString = [originalAttributedString string];
1532 static NSString *attachmentCharString = nil;
1534 if (!attachmentCharString) {
1536 if (!attachmentCharString) {
1537 chars[0] = NSAttachmentCharacter;
1539 attachmentCharString = [[NSString alloc] initWithCharacters:chars length:1];
1543 attachmentRange = [originalString rangeOfString:attachmentCharString];
1544 if (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1545 NSMutableAttributedString *newAttributedString = [[originalAttributedString mutableCopyWithZone:NULL] autorelease];
1547 while (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1548 [newAttributedString replaceCharactersInRange:attachmentRange withString:@""];
1549 attachmentRange = [[newAttributedString string] rangeOfString:attachmentCharString];
1551 return newAttributedString;
1553 return originalAttributedString;
1557 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1559 // Put HTML on the pasteboard.
1560 if ([types containsObject:WebArchivePboardType]) {
1561 WebArchive *archive = [self _selectedArchive];
1562 [pasteboard setData:[archive data] forType:WebArchivePboardType];
1565 // Put the attributed string on the pasteboard (RTF/RTFD format).
1566 NSAttributedString *attributedString = nil;
1567 if ([types containsObject:NSRTFDPboardType]) {
1568 attributedString = [self selectedAttributedString];
1569 if ([attributedString containsAttachments]) {
1570 NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1571 [pasteboard setData:RTFDData forType:NSRTFDPboardType];
1574 if ([types containsObject:NSRTFPboardType]) {
1575 if (attributedString == nil) {
1576 attributedString = [self selectedAttributedString];
1578 if ([attributedString containsAttachments]) {
1579 attributedString = [self _stripAttachmentCharactersFromAttributedString:attributedString];
1581 NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1582 [pasteboard setData:RTFData forType:NSRTFPboardType];
1585 // Put plain string on the pasteboard.
1586 if ([types containsObject:NSStringPboardType]) {
1587 // Map to a plain old space because this is better for source code, other browsers do it,
1588 // and because HTML forces you to do this any time you want two spaces in a row.
1589 NSMutableString *s = [[self selectedString] mutableCopy];
1590 const unichar NonBreakingSpaceCharacter = 0xA0;
1591 NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
1592 [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
1593 [pasteboard setString:s forType:NSStringPboardType];
1597 if ([self _canSmartCopyOrDelete] && [types containsObject:WebSmartPastePboardType]) {
1598 [pasteboard setData:nil forType:WebSmartPastePboardType];
1602 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1604 [pasteboard declareTypes:types owner:nil];
1605 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
1609 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
1611 [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
1615 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1617 if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
1619 } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
1622 return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
1625 - (void)selectAll:(id)sender
1630 - (void)jumpToSelection: sender
1632 [[self _bridge] jumpToSelection];
1635 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
1637 SEL action = [item action];
1638 WebBridge *bridge = [self _bridge];
1640 if (action == @selector(cut:)) {
1641 return [bridge mayDHTMLCut] || [self _canDelete];
1642 } else if (action == @selector(copy:)) {
1643 return [bridge mayDHTMLCopy] || [self _canCopy];
1644 } else if (action == @selector(delete:)) {
1645 return [self _canDelete];
1646 } else if (action == @selector(paste:)) {
1647 return [bridge mayDHTMLPaste] || [self _canPaste];
1648 } else if (action == @selector(takeFindStringFromSelection:)) {
1649 return [self _hasSelection];
1650 } else if (action == @selector(jumpToSelection:)) {
1651 return [self _hasSelection];
1652 } else if (action == @selector(checkSpelling:)
1653 || action == @selector(showGuessPanel:)
1654 || action == @selector(changeSpelling:)
1655 || action == @selector(ignoreSpelling:)) {
1656 return [[self _bridge] isSelectionEditable];
1662 - (BOOL)acceptsFirstResponder
1664 // Don't accept first responder when we first click on this view.
1665 // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1666 // Do accept first responder at any other time, for example from keyboard events,
1667 // or from calls back from WebCore once we begin mouse-down event handling.
1668 NSEvent *event = [NSApp currentEvent];
1669 if ([event type] == NSLeftMouseDown
1670 && !_private->handlingMouseDownEvent
1671 && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1677 - (BOOL)maintainsInactiveSelection
1679 // This method helps to determing whether the view should maintain
1680 // an inactive selection when the view is not first responder.
1681 // Traditionally, these views have not maintained such selections,
1682 // clearing them when the view was not first responder. However,
1683 // to fix bugs like this one:
1684 // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even
1685 // when they're not firstResponder"
1686 // it was decided to add a switch to act more like an NSTextView.
1687 // For now, however, the view only acts in this way when the
1688 // web view is set to be editable. This will maintain traditional
1689 // behavior for WebKit clients dating back to before this change,
1690 // and will likely be a decent switch for the long term, since
1691 // clients to ste the web view to be editable probably want it
1692 // to act like a "regular" Cocoa view in terms of its selection
1694 if (![[self _webView] isEditable])
1697 id nextResponder = [[self window] _newFirstResponderAfterResigning];
1698 return !nextResponder || ![nextResponder isKindOfClass:[NSView class]] || ![nextResponder isDescendantOf:[self _webView]];
1701 - (void)addMouseMovedObserver
1703 // Always add a mouse move observer if the DB requested, or if we're the key window.
1704 if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
1705 [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
1706 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
1707 name:NSMouseMovedNotification object:nil];
1708 [self _frameOrBoundsChanged];
1712 - (void)removeMouseMovedObserver
1714 // Don't remove the observer if we're running the DB
1715 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
1718 [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
1719 [[NSNotificationCenter defaultCenter] removeObserver:self
1720 name:NSMouseMovedNotification object:nil];
1723 - (void)updateFocusDisplay
1725 // This method does the job of updating the view based on the view's firstResponder-ness and
1726 // the window key-ness of the window containing this view. This involves three kinds of
1727 // drawing updates right now, all handled in WebCore in response to the call over the bridge.
1729 // The three display attributes are as follows:
1731 // 1. The background color used to draw behind selected content (active | inactive color)
1732 // 2. Caret blinking (blinks | does not blink)
1733 // 3. The drawing of a focus ring around links in web pages.
1735 BOOL flag = !_private->resigningFirstResponder && [[self window] isKeyWindow] && [self _web_firstResponderCausesFocusDisplay];
1736 [[self _bridge] setDisplaysWithFocusAttributes:flag];
1739 - (void)addSuperviewObservers
1741 // We watch the bounds of our superview, so that we can do a layout when the size
1742 // of the superview changes. This is different from other scrollable things that don't
1743 // need this kind of thing because their layout doesn't change.
1745 // We need to pay attention to both height and width because our "layout" has to change
1746 // to extend the background the full height of the space and because some elements have
1747 // sizes that are based on the total size of the view.
1749 NSView *superview = [self superview];
1750 if (superview && [self window]) {
1751 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1752 name:NSViewFrameDidChangeNotification object:superview];
1753 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1754 name:NSViewBoundsDidChangeNotification object:superview];
1758 - (void)removeSuperviewObservers
1760 NSView *superview = [self superview];
1761 if (superview && [self window]) {
1762 [[NSNotificationCenter defaultCenter] removeObserver:self
1763 name:NSViewFrameDidChangeNotification object:superview];
1764 [[NSNotificationCenter defaultCenter] removeObserver:self
1765 name:NSViewBoundsDidChangeNotification object:superview];
1769 - (void)addWindowObservers
1771 NSWindow *window = [self window];
1773 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
1774 name:NSWindowDidBecomeKeyNotification object:window];
1775 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
1776 name:NSWindowDidResignKeyNotification object:window];
1777 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
1778 name:NSWindowWillCloseNotification object:window];
1782 - (void)removeWindowObservers
1784 NSWindow *window = [self window];
1786 [[NSNotificationCenter defaultCenter] removeObserver:self
1787 name:NSWindowDidBecomeKeyNotification object:window];
1788 [[NSNotificationCenter defaultCenter] removeObserver:self
1789 name:NSWindowDidResignKeyNotification object:window];
1790 [[NSNotificationCenter defaultCenter] removeObserver:self
1791 name:NSWindowWillCloseNotification object:window];
1795 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
1797 [self removeSuperviewObservers];
1800 - (void)viewDidMoveToSuperview
1802 // Do this here in case the text size multiplier changed when a non-HTML
1803 // view was installed.
1804 if ([self superview] != nil) {
1805 [self _updateTextSizeMultiplier];
1806 [self addSuperviewObservers];
1810 - (void)viewWillMoveToWindow:(NSWindow *)window
1812 // Don't do anything if we aren't initialized. This happens
1813 // when decoding a WebView. When WebViews are decoded their subviews
1814 // are created by initWithCoder: and so won't be normally
1815 // initialized. The stub views are discarded by WebView.
1817 // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
1818 [self removeMouseMovedObserver];
1819 [self removeWindowObservers];
1820 [self removeSuperviewObservers];
1821 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1823 [[self _pluginController] stopAllPlugins];
1827 - (void)viewDidMoveToWindow
1829 // Don't do anything if we aren't initialized. This happens
1830 // when decoding a WebView. When WebViews are decoded their subviews
1831 // are created by initWithCoder: and so won't be normally
1832 // initialized. The stub views are discarded by WebView.
1834 [self _stopAutoscrollTimer];
1835 if ([self window]) {
1836 _private->lastScrollPosition = [[self superview] bounds].origin;
1837 [self addWindowObservers];
1838 [self addSuperviewObservers];
1839 [self addMouseMovedObserver];
1840 // Schedule this update, rather than making the call right now.
1841 // The reason is that placing the caret in the just-installed view requires
1842 // the HTML/XML document to be available on the WebCore side, but it is not
1843 // at the time this code is running. However, it will be there on the next
1844 // crank of the run loop. Doing this helps to make a blinking caret appear
1845 // in a new, empty window "automatic".
1846 [self performSelector:@selector(updateFocusDisplay) withObject:nil afterDelay:0];
1848 [[self _pluginController] startAllPlugins];
1850 _private->lastScrollPosition = NSZeroPoint;
1852 _private->inWindow = YES;
1854 // Reset when we are moved out of a window after being moved into one.
1855 // Without this check, we reset ourselves before we even start.
1856 // This is only needed because viewDidMoveToWindow is called even when
1857 // the window is not changing (bug in AppKit).
1858 if (_private->inWindow) {
1860 _private->inWindow = NO;
1866 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
1868 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
1871 - (void)viewDidMoveToHostWindow
1873 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
1877 - (void)addSubview:(NSView *)view
1879 [super addSubview:view];
1881 if ([WebPluginController isPlugInView:view]) {
1882 [[self _pluginController] addPlugin:view];
1886 - (void)reapplyStyles
1888 if (!_private->needsToApplyStyles) {
1893 double start = CFAbsoluteTimeGetCurrent();
1896 [[self _bridge] reapplyStylesForDeviceType:
1897 _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
1900 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1901 LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
1904 _private->needsToApplyStyles = NO;
1907 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
1908 // minPageWidth==0 implies a non-printing layout
1909 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
1911 [self reapplyStyles];
1913 // Ensure that we will receive mouse move events. Is this the best place to put this?
1914 [[self window] setAcceptsMouseMovedEvents: YES];
1915 [[self window] _setShouldPostEventNotifications: YES];
1917 if (!_private->needsLayout) {
1922 double start = CFAbsoluteTimeGetCurrent();
1925 LOG(View, "%@ doing layout", self);
1927 if (minPageWidth > 0.0) {
1928 [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
1930 [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
1932 _private->needsLayout = NO;
1934 if (!_private->printing) {
1935 // get size of the containing dynamic scrollview, so
1936 // appearance and disappearance of scrollbars will not show up
1938 NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
1939 if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
1940 [[self _bridge] sendResizeEvent];
1942 _private->laidOutAtLeastOnce = YES;
1943 _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
1944 _private->lastLayoutFrameSize = newLayoutFrameSize;
1948 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1949 LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
1955 [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
1958 - (NSMenu *)menuForEvent:(NSEvent *)event
1960 [_private->compController endRevertingChange:NO moveLeft:NO];
1962 if ([[self _bridge] sendContextMenuEvent:event]) {
1965 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
1966 NSDictionary *element = [self elementAtPoint:point];
1967 return [[self _webView] _menuForElement:element];
1970 // Search from the end of the currently selected location, or from the beginning of the
1971 // document if nothing is selected.
1972 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag;
1974 return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
1977 - (DOMRange *)_documentRange
1979 return [[[self _bridge] DOMDocument] _documentRange];
1982 - (NSString *)string
1984 return [[self _bridge] stringForRange:[self _documentRange]];
1987 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
1989 NSAttributedString *attributedString = nil;
1990 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
1992 double start = CFAbsoluteTimeGetCurrent();
1994 attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
1996 double duration = CFAbsoluteTimeGetCurrent() - start;
1997 LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
2000 return attributedString;
2003 - (NSAttributedString *)attributedString
2005 WebBridge *bridge = [self _bridge];
2006 DOMDocument *document = [bridge DOMDocument];
2007 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
2008 if (attributedString == nil) {
2009 attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
2011 return attributedString;
2014 - (NSString *)selectedString
2016 return [[self _bridge] selectedString];
2019 - (NSAttributedString *)selectedAttributedString
2021 WebBridge *bridge = [self _bridge];
2022 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
2023 if (attributedString == nil) {
2024 attributedString = [bridge selectedAttributedString];
2026 return attributedString;
2031 [[self _bridge] selectAll];
2034 // Remove the selection.
2037 [[self _bridge] deselectAll];
2040 - (void)deselectText
2042 [[self _bridge] deselectText];
2047 return [[self _webView] drawsBackground];
2050 - (void)setNeedsDisplay:(BOOL)flag
2052 LOG(View, "%@ flag = %d", self, (int)flag);
2053 [super setNeedsDisplay: flag];
2056 - (void)setNeedsLayout: (BOOL)flag
2058 LOG(View, "%@ flag = %d", self, (int)flag);
2059 _private->needsLayout = flag;
2063 - (void)setNeedsToApplyStyles: (BOOL)flag
2065 LOG(View, "%@ flag = %d", self, (int)flag);
2066 _private->needsToApplyStyles = flag;
2069 - (void)drawRect:(NSRect)rect
2071 LOG(View, "%@ drawing", self);
2073 // Work around AppKit bug <rdar://problem/3875305> rect passed to drawRect: is too large.
2074 // Ignore the passed-in rect and instead union in the rectangles from getRectsBeingDrawn.
2075 // This does a better job of clipping out rects that are entirely outside the visible area.
2076 const NSRect *rects;
2078 [self getRectsBeingDrawn:&rects count:&count];
2080 // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2081 // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2082 // The reason for the workaround is that this method is called explicitly from the code
2083 // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2087 for (i = 0; i < count; ++i) {
2088 rect = NSUnionRect(rect, rects[i]);
2090 if (rect.size.height == 0 || rect.size.width == 0) {
2095 BOOL subviewsWereSetAside = _private->subviewsSetAside;
2096 if (subviewsWereSetAside) {
2097 [self _restoreSubviews];
2101 double start = CFAbsoluteTimeGetCurrent();
2104 [NSGraphicsContext saveGraphicsState];
2107 ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2109 [(WebClipView *)[self superview] setAdditionalClip:rect];
2112 WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
2113 if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
2114 textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
2115 [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
2118 if ([self _transparentBackground]) {
2119 [[NSColor clearColor] set];
2123 //double start = CFAbsoluteTimeGetCurrent();
2124 [[self _bridge] drawRect:rect];
2125 //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
2127 if (textRendererFactoryIfCoalescing != nil) {
2128 [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
2131 [(WebClipView *)[self superview] resetAdditionalClip];
2133 [NSGraphicsContext restoreGraphicsState];
2135 [(WebClipView *)[self superview] resetAdditionalClip];
2136 [NSGraphicsContext restoreGraphicsState];
2137 ERROR("Exception caught while drawing: %@", localException);
2138 [localException raise];
2142 NSRect vframe = [self frame];
2143 [[NSColor blackColor] set];
2145 path = [NSBezierPath bezierPath];
2146 [path setLineWidth:(float)0.1];
2147 [path moveToPoint:NSMakePoint(0, 0)];
2148 [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2151 path = [NSBezierPath bezierPath];
2152 [path setLineWidth:(float)0.1];
2153 [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2154 [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2160 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2161 LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2164 if (subviewsWereSetAside) {
2165 [self _setAsideSubviews];
2169 // Turn off the additional clip while computing our visibleRect.
2170 - (NSRect)visibleRect
2172 if (!([[self superview] isKindOfClass:[WebClipView class]]))
2173 return [super visibleRect];
2175 WebClipView *clipView = (WebClipView *)[self superview];
2177 BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2178 if (!hasAdditionalClip) {
2179 return [super visibleRect];
2182 NSRect additionalClip = [clipView additionalClip];
2183 [clipView resetAdditionalClip];
2184 NSRect visibleRect = [super visibleRect];
2185 [clipView setAdditionalClip:additionalClip];
2194 - (void)windowDidBecomeKey:(NSNotification *)notification
2196 ASSERT([notification object] == [self window]);
2197 [self addMouseMovedObserver];
2198 [self updateFocusDisplay];
2201 - (void)windowDidResignKey: (NSNotification *)notification
2203 ASSERT([notification object] == [self window]);
2204 [_private->compController endRevertingChange:NO moveLeft:NO];
2205 [self removeMouseMovedObserver];
2206 [self updateFocusDisplay];
2209 - (void)windowWillClose:(NSNotification *)notification
2211 [_private->compController endRevertingChange:NO moveLeft:NO];
2212 [[self _pluginController] destroyAllPlugins];
2215 - (void)scrollWheel:(NSEvent *)event
2217 if (![[self _bridge] scrollOverflowWithScrollWheelEvent:event]) {
2218 [[self nextResponder] scrollWheel:event];
2222 - (BOOL)_isSelectionEvent:(NSEvent *)event
2224 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2225 return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2228 - (void)_setMouseDownEvent:(NSEvent *)event
2230 ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2232 if (event == _private->mouseDownEvent) {
2237 [_private->mouseDownEvent release];
2238 _private->mouseDownEvent = event;
2240 [_private->firstResponderAtMouseDownTime release];
2241 _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2244 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2246 [self _setMouseDownEvent:event];
2248 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2251 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
2252 // the purposes of this method we want to really query the deepest view, so we forward to it.
2253 forceRealHitTest = YES;
2254 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2255 forceRealHitTest = NO;
2257 if ([hitView isKindOfClass:[self class]]) {
2258 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2259 [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2260 return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2262 return [hitView acceptsFirstMouse:event];
2266 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2268 [self _setMouseDownEvent:event];
2270 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
2271 // the purposes of this method we want to really query the deepest view, so we forward to it.
2272 forceRealHitTest = YES;
2273 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2274 forceRealHitTest = NO;
2276 if ([hitView isKindOfClass:[self class]]) {
2277 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2278 return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2280 return [hitView shouldDelayWindowOrderingForEvent:event];
2284 - (void)mouseDown:(NSEvent *)event
2286 _private->handlingMouseDownEvent = YES;
2288 // Record the mouse down position so we can determine drag hysteresis.
2289 [self _setMouseDownEvent:event];
2291 // TEXTINPUT: if there is marked text and the current input
2292 // manager wants to handle mouse events, we need to make sure to
2293 // pass it to them. If not, then we need to notify the input
2294 // manager when the marked text is abandoned (user clicks outside
2297 [_private->compController endRevertingChange:NO moveLeft:NO];
2299 // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2300 // We don't want to pass them along to KHTML a second time.
2301 if (!([event modifierFlags] & NSControlKeyMask)) {
2302 _private->ignoringMouseDraggedEvents = NO;
2304 // Don't do any mouseover while the mouse is down.
2305 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2307 // Let KHTML get a chance to deal with the event. This will call back to us
2308 // to start the autoscroll timer if appropriate.
2309 [[self _bridge] mouseDown:event];
2312 [_private->firstResponderAtMouseDownTime release];
2313 _private->firstResponderAtMouseDownTime = nil;
2315 _private->handlingMouseDownEvent = NO;
2318 - (void)dragImage:(NSImage *)dragImage
2320 offset:(NSSize)offset
2321 event:(NSEvent *)event
2322 pasteboard:(NSPasteboard *)pasteboard
2324 slideBack:(BOOL)slideBack
2326 [self _stopAutoscrollTimer];
2328 _private->initiatedDrag = YES;
2329 [[self _webView] _setInitiatedDrag:YES];
2331 // Retain this view during the drag because it may be released before the drag ends.
2334 [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2337 - (void)mouseDragged:(NSEvent *)event
2339 // TEXTINPUT: if there is marked text and the current input
2340 // manager wants to handle mouse events, we need to make sure to
2343 if (!_private->ignoringMouseDraggedEvents) {
2344 [[self _bridge] mouseDragged:event];
2348 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2350 if (_private->webCoreDragOp == NSDragOperationNone) {
2351 return (NSDragOperationGeneric | NSDragOperationCopy);
2353 return _private->webCoreDragOp;
2357 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2359 NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2360 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2361 [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2364 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2366 NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2367 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2368 [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2370 _private->initiatedDrag = NO;
2371 [[self _webView] _setInitiatedDrag:NO];
2373 // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2374 _private->ignoringMouseDraggedEvents = YES;
2376 // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2377 // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2378 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2379 location:windowMouseLoc
2380 modifierFlags:[[NSApp currentEvent] modifierFlags]
2381 timestamp:[NSDate timeIntervalSinceReferenceDate]
2382 windowNumber:[[self window] windowNumber]
2383 context:[[NSApp currentEvent] context]
2384 eventNumber:0 clickCount:0 pressure:0];
2385 [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2387 // Balance the previous retain from when the drag started.
2391 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2393 ASSERT(_private->draggingImageURL);
2395 NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2398 // FIXME: Report an error if we fail to create a file.
2399 NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2400 path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
2401 if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2402 ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2405 return [NSArray arrayWithObject:[path lastPathComponent]];
2408 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2410 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2411 NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2412 [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2413 if ([types count] == 0) {
2415 } else if ([types count] == 1 &&
2416 [types containsObject:NSFilenamesPboardType] &&
2417 ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2421 NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2422 NSDictionary *element = [self elementAtPoint:point];
2423 if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2424 if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2425 // Can't drag onto the selection being dragged.
2436 return _private->initiatedDrag &&
2437 ([self _isEditable] && [self _hasSelection]) &&
2438 ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2441 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2443 return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2446 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2448 NSDragOperation operation = NSDragOperationNone;
2450 if (actionMask & WebDragDestinationActionDHTML) {
2451 operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2453 _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2455 if ((actionMask & WebDragDestinationActionEdit) &&
2456 !_private->webCoreHandlingDrag
2457 && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2458 if ([self _isNSColorDrag:draggingInfo]) {
2459 operation = NSDragOperationGeneric;
2462 WebView *webView = [self _webView];
2463 [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2464 operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2467 [[self _webView] removeDragCaret];
2473 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2475 [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2476 [[self _webView] removeDragCaret];
2479 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2481 WebView *webView = [self _webView];
2482 WebBridge *bridge = [self _bridge];
2483 if (_private->webCoreHandlingDrag) {
2484 ASSERT(actionMask & WebDragDestinationActionDHTML);
2485 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2486 [bridge concludeDragForDraggingInfo:draggingInfo];
2488 } else if (actionMask & WebDragDestinationActionEdit) {
2489 if ([self _isNSColorDrag:draggingInfo]) {
2490 NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2493 DOMCSSStyleDeclaration *style = [self _emptyStyle];
2494 [style setProperty:@"color" :[self _colorAsString:color] :@""];
2495 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2496 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2497 [bridge applyStyle:style withUndoAction:WebUndoActionSetColor];
2503 BOOL didInsert = NO;
2504 if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2505 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2506 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES];
2507 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2508 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2509 if ([self _isMoveDrag]) {
2510 BOOL smartMove = [[self _bridge] selectionGranularity] == WebSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2511 [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2513 [bridge setSelectionToDragCaret];
2514 [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
2519 [webView removeDragCaret];
2526 - (NSDictionary *)elementAtPoint:(NSPoint)point
2528 NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2529 NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2531 // Convert URL strings to NSURLs
2532 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2533 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2535 WebFrameView *webFrameView = [self _web_parentWebFrameView];
2536 ASSERT(webFrameView);
2537 WebFrame *webFrame = [webFrameView webFrame];
2540 NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2541 if ([frameName length] == 0) {
2542 [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2544 WebFrame *wf = [webFrame findFrameNamed:frameName];
2546 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2548 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2551 [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2554 return [elementInfo autorelease];
2557 - (void)mouseUp:(NSEvent *)event
2559 // TEXTINPUT: if there is marked text and the current input
2560 // manager wants to handle mouse events, we need to make sure to
2563 [self _stopAutoscrollTimer];
2564 [[self _bridge] mouseUp:event];
2565 [self _updateMouseoverWithFakeEvent];
2568 - (void)mouseMovedNotification:(NSNotification *)notification
2570 [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2573 - (BOOL)supportsTextEncoding
2578 - (NSView *)nextValidKeyView
2581 if (![self isHiddenOrHasHiddenAncestor]) {
2582 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2585 view = [super nextValidKeyView];
2590 - (NSView *)previousValidKeyView
2593 if (![self isHiddenOrHasHiddenAncestor]) {
2594 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2597 view = [super previousValidKeyView];
2602 - (BOOL)becomeFirstResponder
2605 if (![[self _webView] _isPerformingProgrammaticFocus]) {
2606 switch ([[self window] keyViewSelectionDirection]) {
2607 case NSDirectSelection:
2609 case NSSelectingNext:
2610 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2612 case NSSelectingPrevious:
2613 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2618 [[self window] makeFirstResponder:view];
2620 [self updateFocusDisplay];
2621 _private->startNewKillRingSequence = YES;
2625 // This approach could be relaxed when dealing with 3228554.
2626 // Some alteration to the selection behavior was done to deal with 3672088.
2627 - (BOOL)resignFirstResponder
2629 BOOL resign = [super resignFirstResponder];
2631 [_private->compController endRevertingChange:NO moveLeft:NO];
2632 _private->resigningFirstResponder = YES;
2633 if (![self maintainsInactiveSelection]) {
2634 if ([[self _webView] _isPerformingProgrammaticFocus]) {
2635 [self deselectText];
2641 [self updateFocusDisplay];
2642 _private->resigningFirstResponder = NO;
2647 //------------------------------------------------------------------------------------
2648 // WebDocumentView protocol
2649 //------------------------------------------------------------------------------------
2650 - (void)setDataSource:(WebDataSource *)dataSource
2654 - (void)dataSourceUpdated:(WebDataSource *)dataSource
2658 // Does setNeedsDisplay:NO as a side effect when printing is ending.
2659 // pageWidth != 0 implies we will relayout to a new width
2660 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
2662 WebFrame *frame = [self _frame];
2663 NSArray *subframes = [frame childFrames];
2664 unsigned n = [subframes count];
2666 for (i = 0; i != n; ++i) {
2667 WebFrame *subframe = [subframes objectAtIndex:i];
2668 WebFrameView *frameView = [subframe frameView];
2669 if ([[subframe dataSource] _isDocumentHTML]) {
2670 [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
2674 if (printing != _private->printing) {
2675 [_private->pageRects release];
2676 _private->pageRects = nil;
2677 _private->printing = printing;
2678 [self setNeedsToApplyStyles:YES];
2679 [self setNeedsLayout:YES];
2680 [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2682 [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
2684 // Can't do this when starting printing or nested printing won't work, see 3491427.
2685 [self setNeedsDisplay:NO];
2690 // This is needed for the case where the webview is embedded in the view that's being printed.
2691 // It shouldn't be called when the webview is being printed directly.
2692 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
2694 // This helps when we print as part of a larger print process.
2695 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
2696 BOOL wasInPrintingMode = _private->printing;
2697 if (!wasInPrintingMode) {
2698 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2701 [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
2703 if (!wasInPrintingMode) {
2704 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2708 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
2710 NSPrintInfo *printInfo = [printOperation printInfo];
2711 return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
2714 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2716 float viewWidth = NSWidth([self bounds]);
2717 if (viewWidth < 1) {
2718 ERROR("%@ has no width when printing", self);
2722 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2723 float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
2724 float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
2725 return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
2728 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
2729 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
2730 // if AppKit makes it SPI/API.
2731 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2733 return [self _scaleFactorForPrintOperation:printOperation];
2736 - (void)setPageWidthForPrinting:(float)pageWidth
2738 [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
2739 [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
2743 // Return the number of pages available for printing
2744 - (BOOL)knowsPageRange:(NSRangePointer)range {
2745 // Must do this explicit display here, because otherwise the view might redisplay while the print
2746 // sheet was up, using printer fonts (and looking different).
2747 [self displayIfNeeded];
2748 [[self window] setAutodisplay:NO];
2750 // If we are a frameset just print with the layout we have onscreen, otherwise relayout
2751 // according to the paper size
2752 float minLayoutWidth = 0.0;
2753 float maxLayoutWidth = 0.0;
2754 if (![[self _bridge] isFrameSet]) {
2755 float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
2756 minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
2757 maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
2759 [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
2761 // There is a theoretical chance that someone could do some drawing between here and endDocument,
2762 // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
2763 // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
2765 range->location = 1;
2766 NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
2767 float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
2768 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2769 [_private->pageRects release];
2770 NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
2771 printHeight:[self _calculatePrintHeight]/totalScaleFactor];
2772 // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
2773 // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
2774 // a blank page (with correct-looking header and footer if that option is on), which matches
2775 // the behavior of IE and Camino at least.
2776 if ([newPageRects count] == 0) {
2777 newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
2779 _private->pageRects = [newPageRects retain];
2781 range->length = [_private->pageRects count];
2786 // Return the drawing rectangle for a particular page number
2787 - (NSRect)rectForPage:(int)page {
2788 return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
2791 - (void)drawPageBorderWithSize:(NSSize)borderSize
2793 ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));
2794 [[self _webView] _drawHeaderAndFooter];
2797 - (void)beginDocument
2800 [super beginDocument];
2802 // Exception during [super beginDocument] means that endDocument will not get called,
2803 // so we need to clean up our "print mode" here.
2804 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2805 [[self window] setAutodisplay:YES];
2811 [super endDocument];
2812 // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO
2813 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2814 [[self window] setAutodisplay:YES];
2817 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
2819 // Work around this bug:
2820 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
2821 [NSKeyBindingManager sharedKeyBindingManager];
2823 // Use the isEditable state to determine whether or not to process tab key events.
2824 // The idea here is that isEditable will be NO when this WebView is being used
2825 // in a browser, and we desire the behavior where tab moves to the next element
2826 // in tab order. If isEditable is YES, it is likely that the WebView is being
2827 // embedded as the whole view, as in Mail, and tabs should input tabs as expected
2828 // in a text editor.
2829 if (![[self _webView] isEditable] && [event _web_isTabKeyEvent])
2832 // Now process the key normally
2833 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2837 - (void)keyDown:(NSEvent *)event
2839 BOOL callSuper = NO;
2841 _private->keyDownEvent = event;
2843 WebBridge *bridge = [self _bridge];
2844 if ([bridge interceptKeyEvent:event toView:self]) {
2845 // WebCore processed a key event, bail on any outstanding complete: UI
2846 [_private->compController endRevertingChange:YES moveLeft:NO];
2847 } else if (_private->compController && [_private->compController filterKeyDown:event]) {
2848 // Consumed by complete: popup window
2850 // We're going to process a key event, bail on any outstanding complete: UI
2851 [_private->compController endRevertingChange:YES moveLeft:NO];
2852 if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
2853 // Consumed by key bindings manager.
2859 [super keyDown:event];
2861 [NSCursor setHiddenUntilMouseMoves:YES];
2864 _private->keyDownEvent = nil;
2867 - (void)keyUp:(NSEvent *)event
2869 if (![[self _bridge] interceptKeyEvent:event toView:self]) {
2870 [super keyUp:event];
2874 - (id)accessibilityAttributeValue:(NSString*)attributeName
2876 if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
2877 id accTree = [[self _bridge] accessibilityTree];
2879 return [NSArray arrayWithObject: accTree];
2882 return [super accessibilityAttributeValue:attributeName];
2885 - (id)accessibilityFocusedUIElement
2887 id accTree = [[self _bridge] accessibilityTree];
2889 return [accTree accessibilityFocusedUIElement];
2894 - (id)accessibilityHitTest:(NSPoint)point
2896 id accTree = [[self _bridge] accessibilityTree];
2898 NSPoint windowCoord = [[self window] convertScreenToBase: point];
2899 return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
2905 - (void)centerSelectionInVisibleArea:(id)sender
2907 [[self _bridge] centerSelectionInVisibleArea];
2910 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
2912 WebBridge *bridge = [self _bridge];
2913 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
2914 WebView *webView = [self _webView];
2915 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2916 [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
2920 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
2922 WebBridge *bridge = [self _bridge];
2923 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
2924 WebView *webView = [self _webView];
2925 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2926 [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
2930 - (void)moveBackward:(id)sender
2932 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
2935 - (void)moveBackwardAndModifySelection:(id)sender
2937 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
2940 - (void)moveDown:(id)sender
2942 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
2945 - (void)moveDownAndModifySelection:(id)sender
2947 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
2950 - (void)moveForward:(id)sender
2952 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
2955 - (void)moveForwardAndModifySelection:(id)sender
2957 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
2960 - (void)moveLeft:(id)sender
2962 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
2965 - (void)moveLeftAndModifySelection:(id)sender
2967 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
2970 - (void)moveRight:(id)sender
2972 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
2975 - (void)moveRightAndModifySelection:(id)sender
2977 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
2980 - (void)moveToBeginningOfDocument:(id)sender
2982 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2985 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
2987 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2990 - (void)moveToBeginningOfLine:(id)sender
2992 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToLineBoundary];
2995 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
2997 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3000 - (void)moveToBeginningOfParagraph:(id)sender
3002 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3005 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
3007 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3010 - (void)moveToEndOfDocument:(id)sender
3012 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3015 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
3017 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3020 - (void)moveToEndOfLine:(id)sender
3022 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToLineBoundary];
3025 - (void)moveToEndOfLineAndModifySelection:(id)sender
3027 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToLineBoundary];
3030 - (void)moveToEndOfParagraph:(id)sender
3032 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3035 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
3037 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3040 - (void)moveParagraphBackwardAndModifySelection:(id)sender
3042 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByParagraph];
3045 - (void)moveParagraphForwardAndModifySelection:(id)sender
3047 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByParagraph];
3050 - (void)moveUp:(id)sender
3052 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
3055 - (void)moveUpAndModifySelection:(id)sender
3057 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
3060 - (void)moveWordBackward:(id)sender
3062 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
3065 - (void)moveWordBackwardAndModifySelection:(id)sender
3067 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
3070 - (void)moveWordForward:(id)sender
3072 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
3075 - (void)moveWordForwardAndModifySelection:(id)sender
3077 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
3080 - (void)moveWordLeft:(id)sender
3082 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
3085 - (void)moveWordLeftAndModifySelection:(id)sender
3087 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
3090 - (void)moveWordRight:(id)sender
3092 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
3095 - (void)moveWordRightAndModifySelection:(id)sender
3097 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
3100 - (void)pageUp:(id)sender
3102 WebFrameView *frameView = [self _web_parentWebFrameView];
3103 if (frameView == nil)
3105 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:-[frameView _verticalPageScrollDistance]];
3108 - (void)pageDown:(id)sender
3110 WebFrameView *frameView = [self _web_parentWebFrameView];
3111 if (frameView == nil)
3113 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:[frameView _verticalPageScrollDistance]];
3116 - (void)pageUpAndModifySelection:(id)sender
3118 WebFrameView *frameView = [self _web_parentWebFrameView];
3119 if (frameView == nil)
3121 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:-[frameView _verticalPageScrollDistance]];
3124 - (void)pageDownAndModifySelection:(id)sender
3126 WebFrameView *frameView = [self _web_parentWebFrameView];
3127 if (frameView == nil)
3129 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:[frameView _verticalPageScrollDistance]];
3132 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
3134 WebBridge *bridge = [self _bridge];
3135 DOMRange *range = [bridge rangeByExpandingSelectionWithGranularity:granularity];
3136 if (range && ![range collapsed]) {
3137 WebView *webView = [self _webView];
3138 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3139 [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity]];
3144 - (void)selectParagraph:(id)sender
3146 [self _expandSelectionToGranularity:WebSelectByParagraph];
3149 - (void)selectLine:(id)sender
3151 [self _expandSelectionToGranularity:WebSelectByLine];
3154 - (void)selectWord:(id)sender
3156 [self _expandSelectionToGranularity:WebSelectByWord];
3159 - (void)copy:(id)sender
3161 if ([[self _bridge] tryDHTMLCopy]) {
3162 return; // DHTML did the whole operation
3164 if (![self _canCopy]) {
3168 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3171 - (void)delete:(id)sender
3173 if (![self _canDelete]) {
3177 [self _deleteSelection];
3180 - (void)cut:(id)sender
3182 WebBridge *bridge = [self _bridge];
3183 if ([bridge tryDHTMLCut]) {
3184 return; // DHTML did the whole operation
3186 if (![self _canCut]) {
3190 DOMRange *range = [self _selectedRange];
3191 if ([self _shouldDeleteRange:range]) {
3192 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3193 [bridge deleteSelectionWithSmartDelete:[self _canSmartCopyOrDelete]];
3197 - (void)paste:(id)sender
3199 if ([[self _bridge] tryDHTMLPaste]) {
3200 return; // DHTML did the whole operation
3202 if (![self _canPaste]) {
3205 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
3208 - (NSData *)_selectionStartFontAttributesAsRTF
3210 NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"x"
3211 attributes:[[self _bridge] fontAttributesForSelectionStart]];
3212 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length]) documentAttributes:nil];
3217 - (NSDictionary *)_fontAttributesFromFontPasteboard
3219 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3220 if (fontPasteboard == nil)
3222 NSData *data = [fontPasteboard dataForType:NSFontPboardType];
3223 if (data == nil || [data length] == 0)
3225 // NSTextView does something more efficient by parsing the attributes only, but that's not available in API.
3226 NSAttributedString *string = [[[NSAttributedString alloc] initWithRTF:data documentAttributes:NULL] autorelease];
3227 if (string == nil || [string length] == 0)
3229 return [string fontAttributesInRange:NSMakeRange(0, 1)];
3232 - (DOMCSSStyleDeclaration *)_emptyStyle
3234 return [[[self _bridge] DOMDocument] createCSSStyleDeclaration];
3237 - (NSString *)_colorAsString:(NSColor *)color
3239 NSColor *rgbColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
3240 // FIXME: If color is non-nil and rgbColor is nil, that means we got some kind
3241 // of fancy color that can't be converted to RGB. Changing that to "transparent"
3242 // might not be great, but it's probably OK.
3243 if (rgbColor == nil)
3244 return @"transparent";
3245 float r = [rgbColor redComponent];
3246 float g = [rgbColor greenComponent];
3247 float b = [rgbColor blueComponent];
3248 float a = [rgbColor alphaComponent];
3250 return @"transparent";
3251 if (r == 0 && g == 0 && b == 0 && a == 1)
3253 if (r == 1 && g == 1 && b == 1 && a == 1)
3255 // FIXME: Lots more named colors. Maybe we could use the table in WebCore?
3257 return [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", r * 255, g * 255, b * 255];
3258 return [NSString stringWithFormat:@"rgba(%.0f,%.0f,%.0f,%f)", r * 255, g * 255, b * 255, a];
3261 - (NSString *)_shadowAsString:(NSShadow *)shadow
3265 NSSize offset = [shadow shadowOffset];
3266 float blurRadius = [shadow shadowBlurRadius];
3267 if (offset.width == 0 && offset.height == 0 && blurRadius == 0)
3269 NSColor *color = [shadow shadowColor];
3272 // FIXME: Handle non-integral values here?
3273 if (blurRadius == 0)
3274 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height];
3275 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height, blurRadius];
3278 - (DOMCSSStyleDeclaration *)_styleFromFontAttributes:(NSDictionary *)dictionary
3280 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3282 NSColor *color = [dictionary objectForKey:NSBackgroundColorAttributeName];
3283 [style setBackgroundColor:[self _colorAsString:color]];
3285 NSFont *font = [dictionary objectForKey:NSFontAttributeName];
3287 [style setFontFamily:@"Helvetica"];
3288 [style setFontSize:@"12px"];
3289 [style setFontWeight:@"normal"];
3290 [style setFontStyle:@"normal"];
3292 NSFontManager *fm = [NSFontManager sharedFontManager];
3293 [style setFontFamily:[font familyName]];
3294 [style setFontSize:[NSString stringWithFormat:@"%0.fpx", [font pointSize]]];
3295 if ([fm weightOfFont:font] >= 9) {
3296 [style setFontWeight:@"bold"];
3298 [style setFontWeight:@"normal"];
3300 if (([fm traitsOfFont:font] & NSItalicFontMask) != 0) {
3301 [style setFontStyle:@"italic"];
3303 [style setFontStyle:@"normal"];
3307 color = [dictionary objectForKey:NSForegroundColorAttributeName];
3308 [style setColor:color ? [self _colorAsString:color] : @"black"];
3310 NSShadow *shadow = [dictionary objectForKey:NSShadowAttributeName];
3311 [style setTextShadow:[self _shadowAsString:shadow]];
3313 // FIXME: NSStrikethroughStyleAttributeName
3315 int superscriptInt = [[dictionary objectForKey:NSSuperscriptAttributeName] intValue];
3316 if (superscriptInt > 0)
3317 [style setVerticalAlign:@"super"];
3318 else if (superscriptInt < 0)
3319 [style setVerticalAlign:@"sub"];
3321 [style setVerticalAlign:@"baseline"];
3323 // FIXME: NSUnderlineStyleAttributeName
3328 - (void)_applyStyleToSelection:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
3330 if (style == nil || [style length] == 0 || ![self _canEdit])
3332 WebView *webView = [self _webView];
3333 WebBridge *bridge = [self _bridge];
3334 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3335 [bridge applyStyle:style withUndoAction:undoAction];
3341 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3342 [style setFontWeight:@"bold"];
3343 if ([[self _bridge] selectionStartHasStyle:style])
3344 [style setFontWeight:@"normal"];
3345 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3348 - (void)_toggleItalic
3350 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3351 [style setFontStyle:@"italic"];
3352 if ([[self _bridge] selectionStartHasStyle:style])
3353 [style setFontStyle:@"normal"];
3354 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3357 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
3359 ASSERT([self _webView]);
3360 if (![[[self _webView] preferences] respectStandardStyleKeyEquivalents]) {
3364 if (![self _canEdit])
3367 NSString *string = [event charactersIgnoringModifiers];
3368 if ([string isEqualToString:@"b"]) {
3372 if ([string isEqualToString:@"i"]) {
3373 [self _toggleItalic];
3380 - (BOOL)performKeyEquivalent:(NSEvent *)event
3382 if ([self _handleStyleKeyEquivalent:event]) {
3386 // Pass command-key combos through WebCore if there is a key binding available for
3387 // this event. This lets web pages have a crack at intercepting command-modified keypresses.
3388 // But don't do it if we have already handled the event.
3389 if (event != _private->keyDownEvent
3390 && [self _web_firstResponderIsSelfOrDescendantView]
3391 && [[self _bridge] interceptKeyEvent:event toView:self]) {
3394 return [super performKeyEquivalent:event];
3397 - (void)copyFont:(id)sender
3399 // Put RTF with font attributes on the pasteboard.
3400 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3401 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3402 [fontPasteboard declareTypes:[NSArray arrayWithObject:NSFontPboardType] owner:nil];
3403 [fontPasteboard setData:[self _selectionStartFontAttributesAsRTF] forType:NSFontPboardType];
3406 - (void)pasteFont:(id)sender
3408 // Read RTF with font attributes from the pasteboard.
3409 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3410 [self _applyStyleToSelection:[self _styleFromFontAttributes:[self _fontAttributesFromFontPasteboard]] withUndoAction:WebUndoActionPasteFont];
3413 - (void)pasteAsPlainText:(id)sender
3415 if (![self _canEdit])
3418 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
3419 NSString *text = [pasteboard stringForType:NSStringPboardType];
3420 WebBridge *bridge = [self _bridge];
3421 if ([self _shouldReplaceSelectionWithText:text givenAction:WebViewInsertActionPasted]) {
3422 [bridge replaceSelectionWithText:text selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
3426 - (void)pasteAsRichText:(id)sender
3428 // Since rich text always beats plain text when both are on the pasteboard, it's not
3429 // clear how this is different from plain old paste.
3430 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:NO];
3433 - (NSFont *)_originalFontA
3435 return [[NSFontManager sharedFontManager] fontWithFamily:@"Helvetica" traits:0 weight:5 size:10];
3438 - (NSFont *)_originalFontB
3440 return [[NSFontManager sharedFontManager] fontWithFamily:@"Times" traits:(NSBoldFontMask | NSItalicFontMask) weight:10 size:12];
3443 - (void)_addToStyle:(DOMCSSStyleDeclaration *)style fontA:(NSFont *)a fontB:(NSFont *)b
3445 if (a == nil || b == nil)
3448 NSFontManager *fm = [NSFontManager sharedFontManager];
3450 NSFont *oa = [self _originalFontA];
3452 NSString *fa = [a familyName];
3453 NSString *fb = [b familyName];
3454 if ([fa isEqualToString:fb]) {
3455 [style setFontFamily:fa];
3458 int sa = [a pointSize];
3459 int sb = [b pointSize];
3460 int soa = [oa pointSize];
3462 [style setFontSize:[NSString stringWithFormat:@"%dpx", sa]];
3463 } else if (sa < soa) {
3464 // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel smaller
3465 } else if (sa > soa) {
3466 // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel larger
3469 int wa = [fm weightOfFont:a];
3470 int wb = [fm weightOfFont:b];
3473 [style setFontWeight:@"bold"];
3475 [style setFontWeight:@"normal"];
3479 BOOL ia = ([fm traitsOfFont:a] & NSItalicFontMask) != 0;
3480 BOOL ib = ([fm traitsOfFont:b] & NSItalicFontMask) != 0;
3483 [style setFontStyle:@"italic"];
3485 [style setFontStyle:@"normal"];
3490 - (DOMCSSStyleDeclaration *)_styleFromFontManagerOperation
3492 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3494 NSFontManager *fm = [NSFontManager sharedFontManager];
3496 NSFont *oa = [self _originalFontA];
3497 NSFont *ob = [self _originalFontB];
3498 [self _addToStyle:style fontA:[fm convertFont:oa] fontB:[fm convertFont:ob]];
3503 - (void)changeFont:(id)sender
3505 [self _applyStyleToSelection:[self _styleFromFontManagerOperation] withUndoAction:WebUndoActionSetFont];
3508 - (DOMCSSStyleDeclaration *)_styleForAttributeChange:(id)sender
3510 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3512 NSShadow *shadow = [[NSShadow alloc] init];
3513 [shadow setShadowOffset:NSMakeSize(1, 1)];
3515 NSDictionary *oa = [NSDictionary dictionaryWithObjectsAndKeys:
3516 [self _originalFontA], NSFontAttributeName,
3518 NSDictionary *ob = [NSDictionary dictionaryWithObjectsAndKeys:
3519 [NSColor blackColor], NSBackgroundColorAttributeName,
3520 [self _originalFontB], NSFontAttributeName,
3521 [NSColor whiteColor], NSForegroundColorAttributeName,
3522 shadow, NSShadowAttributeName,
3523 [NSNumber numberWithInt:NSUnderlineStyleSingle], NSStrikethroughStyleAttributeName,
3524 [NSNumber numberWithInt:1], NSSuperscriptAttributeName,
3525 [NSNumber numberWithInt:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,
3532 NSObliquenessAttributeName /* float; skew to be applied to glyphs, default 0: no skew */
3533 // font-style, but that is just an on-off switch
3535 NSExpansionAttributeName /* float; log of expansion factor to be applied to glyphs, default 0: no expansion */
3538 NSKernAttributeName /* float, amount to modify default kerning, if 0, kerning off */
3539 // letter-spacing? probably not good enough
3541 NSUnderlineColorAttributeName /* NSColor, default nil: same as foreground color */
3542 NSStrikethroughColorAttributeName /* NSColor, default nil: same as foreground color */
3543 // text-decoration-color?
3545 NSLigatureAttributeName /* int, default 1: default ligatures, 0: no ligatures, 2: all ligatures */
3546 NSBaselineOffsetAttributeName /* float, in points; offset from baseline, default 0 */
3547 NSStrokeWidthAttributeName /* float, in percent of font point size, default 0: no stroke; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0) */
3548 NSStrokeColorAttributeName /* NSColor, default nil: same as foreground color */
3553 NSDictionary *a = [sender convertAttributes:oa];
3554 NSDictionary *b = [sender convertAttributes:ob];
3556 NSColor *ca = [a objectForKey:NSBackgroundColorAttributeName];
3557 NSColor *cb = [b objectForKey:NSBackgroundColorAttributeName];
3559 [style setBackgroundColor:[self _colorAsString:ca]];
3562 [self _addToStyle:style fontA:[a objectForKey:NSFontAttributeName] fontB:[b objectForKey:NSFontAttributeName]];
3564 ca = [a objectForKey:NSForegroundColorAttributeName];
3565 cb = [b objectForKey:NSForegroundColorAttributeName];
3567 [style setColor:[self _colorAsString:ca]];
3570 NSShadow *sha = [a objectForKey:NSShadowAttributeName];
3572 [style setTextShadow:[self _shadowAsString:sha]];
3573 } else if ([b objectForKey:NSShadowAttributeName] == nil) {
3574 [style setTextShadow:@"none"];
3577 int sa = [[a objectForKey:NSStrikethroughStyleAttributeName] intValue];
3578 int sb = [[b objectForKey:NSStrikethroughStyleAttributeName] intValue];
3580 if (sa == NSUnderlineStyleNone)
3581 [style setTextDecoration:@"none"]; // we really mean "no line-through" rather than "none"
3583 [style setTextDecoration:@"line-through"]; // we really mean "add line-through" rather than "line-through"
3586 sa = [[a objectForKey:NSSuperscriptAttributeName] intValue];
3587 sb = [[b objectForKey:NSSuperscriptAttributeName] intValue];
3590 [style setVerticalAlign:@"super"];
3592 [style setVerticalAlign:@"sub"];
3594 [style setVerticalAlign:@"baseline"];
3597 int ua = [[a objectForKey:NSUnderlineStyleAttributeName] intValue];
3598 int ub = [[b objectForKey:NSUnderlineStyleAttributeName] intValue];
3600 if (ua == NSUnderlineStyleNone)
3601 [style setTextDecoration:@"none"]; // we really mean "no underline" rather than "none"
3603 [style setTextDecoration:@"underline"]; // we really mean "add underline" rather than "underline"
3609 - (void)changeAttributes:(id)sender
3611 [self _applyStyleToSelection:[self _styleForAttributeChange:sender] withUndoAction:WebUndoActionChangeAttributes];
3614 - (DOMCSSStyleDeclaration *)_styleFromColorPanelWithSelector:(SEL)selector
3616 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3618 ASSERT([style respondsToSelector:selector]);
3619 [style performSelector:selector withObject:[self _colorAsString:[[NSColorPanel sharedColorPanel] color]]];
3624 - (WebUndoAction)_undoActionFromColorPanelWithSelector:(SEL)selector
3626 if (selector == @selector(setBackgroundColor:)) {
3627 return WebUndoActionSetBackgroundColor;
3630 return WebUndoActionSetColor;
3633 - (void)_changeCSSColorUsingSelector:(SEL)selector inRange:(DOMRange *)range
3635 DOMCSSStyleDeclaration *style = [self _styleFromColorPanelWithSelector:selector];
3636 WebView *webView = [self _webView];
3637 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:range]) {
3638 [[self _bridge] applyStyle:style withUndoAction:[self _undoActionFromColorPanelWithSelector:selector]];
3642 - (void)changeDocumentBackgroundColor:(id)sender
3644 // Mimicking NSTextView, this method sets the background color for the
3645 // entire document. There is no NSTextView API for setting the background
3646 // color on the selected range only. Note that this method is currently
3647 // never called from the UI (see comment in changeColor:).
3648 // FIXME: this actually has no effect when called, probably due to 3654850. _documentRange seems
3649 // to do the right thing because it works in startSpeaking:, and I know setBackgroundColor: does the
3650 // right thing because I tested it with [self _selectedRange].
3651 // FIXME: This won't actually apply the style to the entire range here, because it ends up calling
3652 // [bridge applyStyle:], which operates on the current selection. To make this work right, we'll
3653 // need to save off the selection, temporarily set it to the entire range, make the change, then
3654 // restore the old selection.
3655 [self _changeCSSColorUsingSelector:@selector(setBackgroundColor:) inRange:[self _documentRange]];
3658 - (void)changeColor:(id)sender
3660 // FIXME: in NSTextView, this method calls changeDocumentBackgroundColor: when a
3661 // private call has earlier been made by [NSFontFontEffectsBox changeColor:], see 3674493.
3662 // AppKit will have to be revised to allow this to work with anything that isn't an
3663 // NSTextView. However, this might not be required for Tiger, since the background-color
3664 // changing box in the font panel doesn't work in Mail (3674481), though it does in TextEdit.
3665 [self _applyStyleToSelection:[self _styleFromColorPanelWithSelector:@selector(setColor:)]
3666 withUndoAction:WebUndoActionSetColor];
3669 - (void)_alignSelectionUsingCSSValue:(NSString *)CSSAlignmentValue withUndoAction:(WebUndoAction)undoAction
3671 if (![self _canEdit])
3674 // FIXME 3675191: This doesn't work yet. Maybe it's blocked by 3654850, or maybe something other than
3675 // just applyStyle: needs to be called for block-level attributes like this.
3676 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3677 [style setTextAlign:CSSAlignmentValue];
3678 [self _applyStyleToSelection:style withUndoAction:undoAction];
3681 - (void)alignCenter:(id)sender
3683 [self _alignSelectionUsingCSSValue:@"center" withUndoAction:WebUndoActionCenter];
3686 - (void)alignJustified:(id)sender
3688 [self _alignSelectionUsingCSSValue:@"justify" withUndoAction:WebUndoActionJustify];
3691 - (void)alignLeft:(id)sender
3693 [self _alignSelectionUsingCSSValue:@"left" withUndoAction:WebUndoActionAlignLeft];
3696 - (void)alignRight:(id)sender
3698 [self _alignSelectionUsingCSSValue:@"right" withUndoAction:WebUndoActionAlignRight];
3701 - (void)insertTab:(id)sender
3703 [self insertText:@"\t"];
3706 - (void)insertBacktab:(id)sender
3708 // Doing nothing matches normal NSTextView behavior. If we ever use WebView for a field-editor-type purpose
3709 // we might add code here.
3712 - (void)insertNewline:(id)sender
3714 if (![self _canEdit])
3717 // Perhaps we should make this delegate call sensitive to the real DOM operation we actually do.
3718 WebBridge *bridge = [self _bridge];
3719 if ([self _shouldReplaceSelectionWithText:@"\n" givenAction:WebViewInsertActionTyped]) {
3720 [bridge insertParagraphSeparator];
3724 - (void)insertLineBreak:(id)sender
3726 if (![self _canEdit])
3729 // Perhaps we should make this delegate call sensitive to the real DOM operation we actually do.
3730 WebBridge *bridge = [self _bridge];
3731 if ([self _shouldReplaceSelectionWithText:@"\n" givenAction:WebViewInsertActionTyped]) {
3732 [bridge insertLineBreak];
3736 - (void)insertParagraphSeparator:(id)sender
3738 if (![self _canEdit])
3741 // Perhaps we should make this delegate call sensitive to the real DOM operation we actually do.
3742 WebBridge *bridge = [self _bridge];
3743 if ([self _shouldReplaceSelectionWithText:@"\n" givenAction:WebViewInsertActionTyped]) {
3744 [bridge insertParagraphSeparator];
3748 - (void)_changeWordCaseWithSelector:(SEL)selector
3750 if (![self _canEdit])
3753 WebBridge *bridge = [self _bridge];
3754 [self selectWord:nil];
3755 NSString *word = [[bridge selectedString] performSelector:selector];
3756 // FIXME: Does this need a different action context other than "typed"?
3757 if ([self _shouldReplaceSelectionWithText:word givenAction:WebViewInsertActionTyped]) {
3758 [bridge replaceSelectionWithText:word selectReplacement:NO smartReplace:NO];
3762 - (void)uppercaseWord:(id)sender
3764 [self _changeWordCaseWithSelector:@selector(uppercaseString)];
3767 - (void)lowercaseWord:(id)sender
3769 [self _changeWordCaseWithSelector:@selector(lowercaseString)];
3772 - (void)capitalizeWord:(id)sender
3774 [self _changeWordCaseWithSelector:@selector(capitalizedString)];
3777 - (BOOL)_deleteWithDirection:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity killRing:(BOOL)killRing
3779 // Delete the selection, if there is one.
3780 // If not, make a selection using the passed-in direction and granularity.
3781 if (![self _canEdit])
3786 BOOL smartDeleteOK = NO;
3787 if ([self _hasSelection]) {
3788 range = [self _selectedRange];
3789 smartDeleteOK = YES;
3791 WebBridge *bridge = [self _bridge];
3792 range = [bridge rangeByAlteringCurrentSelection:WebSelectByExtending direction:direction granularity:granularity];
3793 if (range == nil || [range collapsed])
3795 switch (direction) {
3796 case WebSelectForward:
3797 case WebSelectRight:
3799 case WebSelectBackward:
3805 [self _deleteRange:range preflight:YES killRing:killRing prepend:prepend smartDeleteOK:smartDeleteOK];
3809 - (void)deleteForward:(id)sender
3811 [self _deleteWithDirection:WebSelectForward granularity:WebSelectByCharacter killRing:NO];
3814 - (void)deleteBackward:(id)sender
3816 if (![self _isEditable])
3818 if ([self _hasSelection]) {
3819 [self _deleteSelection];
3821 // FIXME: We are not calling the delegate here. Why can't we just call _deleteRange here?
3822 [[self _bridge] deleteKeyPressed];
3826 - (void)deleteBackwardByDecomposingPreviousCharacter:(id)sender
3828 ERROR("unimplemented, doing deleteBackward instead");
3829 [self deleteBackward:sender];
3832 - (void)deleteWordForward:(id)sender
3834 [self _deleteWithDirection:WebSelectForward granularity:WebSelectByWord killRing:YES];
3837 - (void)deleteWordBackward:(id)sender
3839 [self _deleteWithDirection:WebSelectBackward granularity:WebSelectByWord killRing:YES];
3842 - (void)deleteToBeginningOfLine:(id)sender
3844 [self _deleteWithDirection:WebSelectBackward granularity:WebSelectToLineBoundary killRing:YES];
3847 - (void)deleteToEndOfLine:(id)sender
3849 // FIXME: To match NSTextView, this command should delete the newline at the end of
3850 // a paragraph if you are at the end of a paragraph (like deleteToEndOfParagraph does below).
3851 [self _deleteWithDirection:WebSelectForward granularity:WebSelectToLineBoundary killRing:YES];
3854 - (void)deleteToBeginningOfParagraph:(id)sender
3856 [self _deleteWithDirection:WebSelectBackward granularity:WebSelectToParagraphBoundary killRing:YES];
3859 - (void)deleteToEndOfParagraph:(id)sender
3861 // Despite the name of the method, this should delete the newline if the caret is at the end of a paragraph.
3862 // If deletion to the end of the paragraph fails, we delete one character forward, which will delete the newline.
3863 if (![self _deleteWithDirection:WebSelectForward granularity:WebSelectToParagraphBoundary killRing:YES])
3864 [self _deleteWithDirection:WebSelectForward granularity:WebSelectByCharacter killRing:YES];
3867 - (void)complete:(id)sender
3869 if (![self _canEdit])
3872 if (!_private->compController) {
3873 _private->compController = [[WebTextCompleteController alloc] initWithHTMLView:self];
3875 [_private->compController doCompletion];
3878 - (void)checkSpelling:(id)sender
3880 // WebCore does everything but update the spelling panel
3881 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3883 ERROR("No NSSpellChecker");
3886 NSString *badWord = [[self _bridge] advanceToNextMisspelling];
3888 [checker updateSpellingPanelWithMisspelledWord:badWord];
3892 - (void)showGuessPanel:(id)sender
3894 // WebCore does everything but update the spelling panel
3895 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3897 ERROR("No NSSpellChecker");
3900 NSString *badWord = [[self _bridge] advanceToNextMisspellingStartingJustBeforeSelection];
3902 [checker updateSpellingPanelWithMisspelledWord:badWord];
3904 [[checker spellingPanel] orderFront:sender];
3907 - (void)_changeSpellingToWord:(NSString *)newWord
3909 if (![self _canEdit])
3912 // Don't correct to empty string. (AppKit checked this, we might as well too.)
3913 if (![NSSpellChecker sharedSpellChecker]) {
3914 ERROR("No NSSpellChecker");
3918 if ([newWord isEqualToString:@""]) {
3922 if ([self _shouldReplaceSelectionWithText:newWord givenAction:WebViewInsertActionPasted]) {
3923 [[self _bridge] replaceSelectionWithText:newWord selectReplacement:YES smartReplace:NO];
3927 - (void)changeSpelling:(id)sender
3929 [self _changeSpellingToWord:[[sender selectedCell] stringValue]];
3932 - (void)ignoreSpelling:(id)sender
3934 if (![self _canEdit])
3937 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3939 ERROR("No NSSpellChecker");
3943 NSString *stringToIgnore = [sender stringValue];
3944 unsigned int length = [stringToIgnore length];
3945 if (stringToIgnore && length > 0) {
3946 [checker ignoreWord:stringToIgnore inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
3947 // FIXME: Need to clear misspelling marker if the currently selected word is the one we are to ignore?
3951 - (void)performFindPanelAction:(id)sender
3953 // Implementing this will probably require copying all of NSFindPanel.h and .m.
3954 // We need *almost* the same thing as AppKit, but not quite.
3955 ERROR("unimplemented");
3958 - (void)startSpeaking:(id)sender
3960 WebBridge *bridge = [self _bridge];
3961 DOMRange *range = [self _selectedRange];
3962 if (!range || [range collapsed]) {
3963 range = [self _documentRange];
3965 [NSApp speakString:[bridge stringForRange:range]];
3968 - (void)stopSpeaking:(id)sender
3970 [NSApp stopSpeaking:sender];
3973 - (void)insertNewlineIgnoringFieldEditor:(id)sender
3975 [self insertNewline:sender];
3978 - (void)insertTabIgnoringFieldEditor:(id)sender
3980 [self insertTab:sender];
3983 - (void)subscript:(id)sender
3985 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3986 [style setVerticalAlign:@"sub"];
3987 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSubscript];
3990 - (void)superscript:(id)sender
3992 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3993 [style setVerticalAlign:@"super"];
3994 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSuperscript];
3997 - (void)unscript:(id)sender
3999 DOMCSSStyleDeclaration *style = [self _emptyStyle];
4000 [style setVerticalAlign:@"baseline"];
4001 [self _applyStyleToSelection:style withUndoAction:WebUndoActionUnscript];
4004 - (void)underline:(id)sender
4006 // Despite the name, this method is actually supposed to toggle underline.
4007 // FIXME: This currently clears overline, line-through, and blink as an unwanted side effect.
4008 DOMCSSStyleDeclaration *style = [self _emptyStyle];
4009 [style setTextDecoration:@"underline"];
4010 if ([[self _bridge] selectionStartHasStyle:style])
4011 [style setTextDecoration:@"none"];
4012 [self _applyStyleToSelection:style withUndoAction:WebUndoActionUnderline];
4015 - (void)yank:(id)sender
4017 if (![self _canEdit])
4020 [self insertText:_NSYankFromKillRing()];
4021 _NSSetKillRingToYankedState();
4024 - (void)yankAndSelect:(id)sender
4026 if (![self _canEdit])
4029 [self _insertText:_NSYankPreviousFromKillRing() selectInsertedText:YES];
4030 _NSSetKillRingToYankedState();
4033 - (void)setMark:(id)sender
4035 [[self _bridge] setMarkDOMRange:[self _selectedRange]];
4038 static DOMRange *unionDOMRanges(DOMRange *a, DOMRange *b)
4042 DOMRange *s = [a compareBoundaryPoints:DOM_START_TO_START :b] <= 0 ? a : b;
4043 DOMRange *e = [a compareBoundaryPoints:DOM_END_TO_END :b] <= 0 ? b : a;
4044 DOMRange *r = [[[a startContainer] ownerDocument] createRange];
4045 [r setStart:[s startContainer] :[s startOffset]];
4046 [r setEnd:[e endContainer] :[e endOffset]];
4050 - (void)deleteToMark:(id)sender
4052 if (![self _canEdit])
4055 DOMRange *mark = [[self _bridge] markDOMRange];
4057 [self delete:sender];
4059 DOMRange *selection = [self _selectedRange];
4062 r = unionDOMRanges(mark, selection);
4063 } @catch (NSException *exception) {
4066 [self _deleteRange:r preflight:YES killRing:YES prepend:YES smartDeleteOK:NO];
4068 [self setMark:sender];
4071 - (void)selectToMark:(id)sender
4073 WebBridge *bridge = [self _bridge];
4074 DOMRange *mark = [bridge markDOMRange];
4079 DOMRange *selection = [self _selectedRange];
4081 [bridge setSelectedDOMRange:unionDOMRanges(mark, selection) affinity:NSSelectionAffinityUpstream];
4082 } @catch (NSException *exception) {
4087 - (void)swapWithMark:(id)sender
4089 if (![self _canEdit])
4092 WebBridge *bridge = [self _bridge];
4093 DOMRange *mark = [bridge markDOMRange];
4098 DOMRange *selection = [self _selectedRange];
4100 [bridge setSelectedDOMRange:mark affinity:NSSelectionAffinityUpstream];
4101 } @catch (NSException *exception) {
4105 [bridge setMarkDOMRange:selection];
4108 - (void)transpose:(id)sender
4110 if (![self _canEdit])
4113 WebBridge *bridge = [self _bridge];
4114 DOMRange *r = [bridge rangeOfCharactersAroundCaret];