0092e6d72458ccab60a4524f913f6e2849f97a5c
[WebKit.git] / WebKit / WebView.subproj / WebHTMLView.m
1 /*
2  * Copyright (C) 2005 Apple Computer, Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer. 
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution. 
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission. 
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #import <WebKit/WebHTMLView.h>
30
31 #import <WebKit/DOM.h>
32 #import <WebKit/DOMExtensions.h>
33 #import <WebKit/DOMPrivate.h>
34 #import <WebKit/WebArchive.h>
35 #import <WebKit/WebBridge.h>
36 #import <WebKit/WebClipView.h>
37 #import <WebKit/WebDataProtocol.h>
38 #import <WebKit/WebDataSourcePrivate.h>
39 #import <WebKit/WebDocumentInternal.h>
40 #import <WebKit/WebDOMOperationsPrivate.h>
41 #import <WebKit/WebEditingDelegate.h>
42 #import <WebKit/WebException.h>
43 #import <WebKit/WebFramePrivate.h>
44 #import <WebKit/WebFrameViewInternal.h>
45 #import <WebKit/WebHTMLViewInternal.h>
46 #import <WebKit/WebHTMLRepresentationPrivate.h>
47 #import <WebKit/WebImageRenderer.h>
48 #import <WebKit/WebImageRendererFactory.h>
49 #import <WebKit/WebKitLogging.h>
50 #import <WebKit/WebKitNSStringExtras.h>
51 #import <WebKit/WebNetscapePluginEmbeddedView.h>
52 #import <WebKit/WebNSEventExtras.h>
53 #import <WebKit/WebNSFileManagerExtras.h>
54 #import <WebKit/WebNSImageExtras.h>
55 #import <WebKit/WebNSObjectExtras.h>
56 #import <WebKit/WebNSPasteboardExtras.h>
57 #import <WebKit/WebNSPrintOperationExtras.h>
58 #import <WebKit/WebNSURLExtras.h>
59 #import <WebKit/WebNSViewExtras.h>
60 #import <WebKit/WebPluginController.h>
61 #import <WebKit/WebPreferences.h>
62 #import <WebKit/WebPreferencesPrivate.h>
63 #import <WebKit/WebResourcePrivate.h>
64 #import <WebKit/WebStringTruncator.h>
65 #import <WebKit/WebTextRenderer.h>
66 #import <WebKit/WebTextRendererFactory.h>
67 #import <WebKit/WebUIDelegatePrivate.h>
68 #import <WebKit/WebViewInternal.h>
69 #import <WebKit/WebViewPrivate.h>
70
71 #import <AppKit/NSAccessibility.h>
72 #import <AppKit/NSGraphicsContextPrivate.h>
73 #import <AppKit/NSResponder_Private.h>
74
75 #import <Foundation/NSURLFileTypeMappings.h>
76
77 #import <CoreGraphics/CGContextGState.h>
78
79 // Included to help work around this bug:
80 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
81 #import <AppKit/NSKeyBindingManager.h>
82
83 // Included so usage of _NSSoftLinkingGetFrameworkFuncPtr will compile
84 #import <mach-o/dyld.h> 
85
86
87 // need to declare this because AppKit does not make it available as API or SPI
88 extern NSString *NSMarkedClauseSegmentAttributeName; 
89 extern NSString *NSTextInputReplacementRangeAttributeName; 
90
91 // Kill ring calls. Would be better to use NSKillRing.h, but that's not available in SPI.
92 void _NSInitializeKillRing(void);
93 void _NSAppendToKillRing(NSString *);
94 void _NSPrependToKillRing(NSString *);
95 NSString *_NSYankFromKillRing(void);
96 NSString *_NSYankPreviousFromKillRing(void);
97 void _NSNewKillRingSequence(void);
98 void _NSSetKillRingToYankedState(void);
99 void _NSResetKillRingOperationFlag(void);
100
101 @interface NSView (AppKitSecretsIKnowAbout)
102 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
103 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
104 - (NSRect)_dirtyRect;
105 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
106 - (void)_propagateDirtyRectsToOpaqueAncestors;
107 @end
108
109 @interface NSApplication (AppKitSecretsIKnowAbout)
110 - (void)speakString:(NSString *)string;
111 @end
112
113 @interface NSWindow (AppKitSecretsIKnowAbout)
114 - (id)_newFirstResponderAfterResigning;
115 @end
116
117 @interface NSAttributedString (AppKitSecretsIKnowAbout)
118 - (id)_initWithDOMRange:(DOMRange *)domRange;
119 - (DOMDocumentFragment *)_documentFromRange:(NSRange)range document:(DOMDocument *)document documentAttributes:(NSDictionary *)dict subresources:(NSArray **)subresources;
120 @end
121
122 @interface NSSpellChecker (CurrentlyPrivateForTextView)
123 - (void)learnWord:(NSString *)word;
124 @end
125
126 // By imaging to a width a little wider than the available pixels,
127 // thin pages will be scaled down a little, matching the way they
128 // print in IE and Camino. This lets them use fewer sheets than they
129 // would otherwise, which is presumably why other browsers do this.
130 // Wide pages will be scaled down more than this.
131 #define PrintingMinimumShrinkFactor     1.25
132
133 // This number determines how small we are willing to reduce the page content
134 // in order to accommodate the widest line. If the page would have to be
135 // reduced smaller to make the widest line fit, we just clip instead (this
136 // behavior matches MacIE and Mozilla, at least)
137 #define PrintingMaximumShrinkFactor     2.0
138
139 #define AUTOSCROLL_INTERVAL             0.1
140
141 #define DRAG_LABEL_BORDER_X             4.0
142 #define DRAG_LABEL_BORDER_Y             2.0
143 #define DRAG_LABEL_RADIUS               5.0
144 #define DRAG_LABEL_BORDER_Y_OFFSET              2.0
145
146 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP        120.0
147 #define MAX_DRAG_LABEL_WIDTH                    320.0
148
149 #define DRAG_LINK_LABEL_FONT_SIZE   11.0
150 #define DRAG_LINK_URL_FONT_SIZE   10.0
151
152 #ifndef OMIT_TIGER_FEATURES
153 #define USE_APPKIT_FOR_ATTRIBUTED_STRINGS
154 #endif
155
156 // Any non-zero value will do, but using something recognizable might help us debug some day.
157 #define TRACKING_RECT_TAG 0xBADFACE
158
159 // FIXME: This constant is copied from AppKit's _NXSmartPaste constant.
160 #define WebSmartPastePboardType @"NeXT smart paste pasteboard type"
161
162 #define STANDARD_WEIGHT 5
163 #define MIN_BOLD_WEIGHT 9
164 #define STANDARD_BOLD_WEIGHT 10
165
166 typedef enum {
167     deleteSelectionAction,
168     deleteKeyAction,
169     forwardDeleteKeyAction
170 } WebDeletionAction;
171
172 static BOOL forceRealHitTest = NO;
173
174 // Used to avoid linking with ApplicationServices framework for _DCMDictionaryServiceWindowShow
175 void *_NSSoftLinkingGetFrameworkFuncPtr(NSString *inUmbrellaFrameworkName,
176                                         NSString *inFrameworkName,
177                                         const char *inFuncName,
178                                         const struct mach_header **ioCachedFrameworkImageHeaderPtr);
179
180
181 @interface WebHTMLView (WebTextSizing) <_web_WebDocumentTextSizing>
182 @end
183
184 @interface WebHTMLView (WebHTMLViewFileInternal)
185 - (BOOL)_imageExistsAtPaths:(NSArray *)paths;
186 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText chosePlainText:(BOOL *)chosePlainText;
187 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
188 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
189 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action;
190 - (float)_calculatePrintHeight;
191 - (void)_updateTextSizeMultiplier;
192 - (DOMRange *)_selectedRange;
193 - (BOOL)_shouldDeleteRange:(DOMRange *)range;
194 - (void)_deleteRange:(DOMRange *)range 
195             killRing:(BOOL)killRing 
196              prepend:(BOOL)prepend 
197        smartDeleteOK:(BOOL)smartDeleteOK
198       deletionAction:(WebDeletionAction)deletionAction;
199 - (void)_deleteSelection;
200 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard;
201 - (NSView *)_hitViewForEvent:(NSEvent *)event;
202 - (void)_writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard cachedAttributedString:(NSAttributedString *)attributedString;
203 @end
204
205 @interface WebHTMLView (WebForwardDeclaration) // FIXME: Put this in a normal category and stop doing the forward declaration trick.
206 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize;
207 @end
208
209 @interface WebHTMLView (WebNSTextInputSupport) <NSTextInput>
210 - (void)_updateSelectionForInputManager;
211 - (void)_insertText:(NSString *)text selectInsertedText:(BOOL)selectText;
212 @end
213
214 @interface WebHTMLView (WebEditingStyleSupport)
215 - (DOMCSSStyleDeclaration *)_emptyStyle;
216 - (NSString *)_colorAsString:(NSColor *)color;
217 @end
218
219 @interface NSView (WebHTMLViewFileInternal)
220 - (void)_web_setPrintingModeRecursive;
221 - (void)_web_clearPrintingModeRecursive;
222 - (void)_web_layoutIfNeededRecursive;
223 - (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
224 @end
225
226 @interface NSMutableDictionary (WebHTMLViewFileInternal)
227 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
228 @end
229
230 // Handles the complete: text command
231 @interface WebTextCompleteController : NSObject
232 {
233 @private
234     WebHTMLView *_view;
235     NSWindow *_popupWindow;
236     NSTableView *_tableView;
237     NSArray *_completions;
238     NSString *_originalString;
239     int prefixLength;
240 }
241 - (id)initWithHTMLView:(WebHTMLView *)view;
242 - (void)doCompletion;
243 - (void)endRevertingChange:(BOOL)revertChange moveLeft:(BOOL)goLeft;
244 - (BOOL)filterKeyDown:(NSEvent *)event;
245 - (void)_reflectSelection;
246 @end
247
248 @implementation WebHTMLViewPrivate
249
250 - (void)dealloc
251 {
252     ASSERT(autoscrollTimer == nil);
253     ASSERT(autoscrollTriggerEvent == nil);
254     
255     [mouseDownEvent release];
256     [draggingImageURL release];
257     [pluginController release];
258     [toolTip release];
259     [compController release];
260     [firstResponderAtMouseDownTime release];
261
262     [super dealloc];
263 }
264
265 @end
266
267 @implementation WebHTMLView (WebHTMLViewFileInternal)
268
269 - (BOOL)_imageExistsAtPaths:(NSArray *)paths
270 {
271     NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
272     NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
273     NSEnumerator *enumerator = [paths objectEnumerator];
274     NSString *path;
275     
276     while ((path = [enumerator nextObject]) != nil) {
277         NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
278         if ([imageMIMETypes containsObject:MIMEType]) {
279             return YES;
280         }
281     }
282     
283     return NO;
284 }
285
286 - (DOMDocumentFragment *)_documentFragmentWithPaths:(NSArray *)paths
287 {
288     DOMDocumentFragment *fragment = [[[self _bridge] DOMDocument] createDocumentFragment];
289     NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
290     NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
291     NSEnumerator *enumerator = [paths objectEnumerator];
292     WebDataSource *dataSource = [self _dataSource];
293     NSString *path;
294     
295     while ((path = [enumerator nextObject]) != nil) {
296         NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
297         if ([imageMIMETypes containsObject:MIMEType]) {
298             WebResource *resource = [[WebResource alloc] initWithData:[NSData dataWithContentsOfFile:path]
299                                                                   URL:[NSURL fileURLWithPath:path]
300                                                              MIMEType:MIMEType 
301                                                      textEncodingName:nil
302                                                             frameName:nil];
303             if (resource) {
304                 [fragment appendChild:[dataSource _imageElementWithImageResource:resource]];
305                 [resource release];
306             }
307         }
308     }
309     
310     return [fragment firstChild] != nil ? fragment : nil;
311 }
312
313 + (NSArray *)_excludedElementsForAttributedStringConversion
314 {
315     static NSArray *elements = nil;
316     if (elements == nil) {
317         elements = [[NSArray alloc] initWithObjects:
318             // Omit style since we want style to be inline so the fragment can be easily inserted.
319             @"style",
320             // Omit xml so the result is not XHTML.
321             @"xml", 
322             // Omit tags that will get stripped when converted to a fragment anyway.
323             @"doctype", @"html", @"head", @"body",
324             // Omit deprecated tags.
325             @"applet", @"basefont", @"center", @"dir", @"font", @"isindex", @"menu", @"s", @"strike", @"u",
326             // Omit object so no file attachments are part of the fragment.
327             @"object", nil];
328     }
329     return elements;
330 }
331
332 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText chosePlainText:(BOOL *)chosePlainText
333 {
334     NSArray *types = [pasteboard types];
335     *chosePlainText = NO;
336
337     if ([types containsObject:WebArchivePboardType]) {
338         WebArchive *archive = [[WebArchive alloc] initWithData:[pasteboard dataForType:WebArchivePboardType]];
339         if (archive) {
340             DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithArchive:archive];
341             [archive release];
342             if (fragment) {
343                 return fragment;
344             }
345         }
346     }
347     
348     if ([types containsObject:NSFilenamesPboardType]) {
349         DOMDocumentFragment *fragment = [self _documentFragmentWithPaths:[pasteboard propertyListForType:NSFilenamesPboardType]];
350         if (fragment != nil) {
351             return fragment;
352         }
353     }
354     
355     NSURL *URL;
356     
357     if ([types containsObject:NSHTMLPboardType]) {
358         NSString *HTMLString = [pasteboard stringForType:NSHTMLPboardType];
359         // This is a hack to make Microsoft's HTML pasteboard data work. See 3778785.
360         if ([HTMLString hasPrefix:@"Version:"]) {
361             NSRange range = [HTMLString rangeOfString:@"<html" options:NSCaseInsensitiveSearch];
362             if (range.location != NSNotFound) {
363                 HTMLString = [HTMLString substringFromIndex:range.location];
364             }
365         }
366         if ([HTMLString length] != 0) {
367             return [[self _bridge] documentFragmentWithMarkupString:HTMLString baseURLString:nil];
368         }
369     }
370         
371 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
372     NSAttributedString *string = nil;
373     if ([types containsObject:NSRTFDPboardType]) {
374         string = [[NSAttributedString alloc] initWithRTFD:[pasteboard dataForType:NSRTFDPboardType] documentAttributes:NULL];
375     }
376     if (string == nil && [types containsObject:NSRTFPboardType]) {
377         string = [[NSAttributedString alloc] initWithRTF:[pasteboard dataForType:NSRTFPboardType] documentAttributes:NULL];
378     }
379     if (string != nil) {
380         NSDictionary *documentAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:
381             [[self class] _excludedElementsForAttributedStringConversion], NSExcludedElementsDocumentAttribute,
382             self, @"WebResourceHandler", nil];
383         NSArray *subresources;
384         DOMDocumentFragment *fragment = [string _documentFromRange:NSMakeRange(0, [string length]) 
385                                                           document:[[self _bridge] DOMDocument] 
386                                                 documentAttributes:documentAttributes
387                                                       subresources:&subresources];
388         [documentAttributes release];
389         [string release];
390         return fragment;
391     }
392 #endif
393     
394     if ([types containsObject:NSTIFFPboardType]) {
395         WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSTIFFPboardType]
396                                                               URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.tiff"]
397                                                          MIMEType:@"image/tiff" 
398                                                  textEncodingName:nil
399                                                         frameName:nil];
400         DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
401         [resource release];
402         return fragment;
403     }
404     
405     if ([types containsObject:NSPICTPboardType]) {
406         WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSPICTPboardType]
407                                                               URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.pict"]
408                                                          MIMEType:@"image/pict" 
409                                                  textEncodingName:nil
410                                                         frameName:nil];
411         DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
412         [resource release];
413         return fragment;
414     }    
415     
416     if ((URL = [NSURL URLFromPasteboard:pasteboard])) {
417         NSString *URLString = [URL _web_userVisibleString];
418         if ([URLString length] > 0) {
419             return [[self _bridge] documentFragmentWithText:URLString];
420         }
421     }
422     
423     if (allowPlainText && [types containsObject:NSStringPboardType]) {
424         *chosePlainText = YES;
425         return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
426     }
427     
428     return nil;
429 }
430
431 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
432 - (WebResource *)resourceForData:(NSData *)data preferredFilename:(NSString *)name
433 {
434     // This method is called by [NSAttributedString _documentFromRange::::] 
435     // which uses the URL of the resource for the fragment that it returns.
436     NSString *extension = [name pathExtension];
437     NSString *MIMEType = nil;
438     if ([extension length] != 0) {
439         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
440     }
441     // Only support image resources.
442     if (MIMEType == nil || ![[[WebImageRendererFactory sharedFactory] supportedMIMETypes] containsObject:MIMEType]) {
443         return nil;
444     }
445     NSURL *URL = [NSURL _web_URLWithUserTypedString:[NSString stringWithFormat:@"/%@", name] relativeToURL:[NSURL _web_uniqueWebDataURL]];
446     WebResource *resource = [[[WebResource alloc] initWithData:data
447                                                            URL:URL
448                                                       MIMEType:MIMEType 
449                                               textEncodingName:nil
450                                                      frameName:nil] autorelease];
451     [[self _dataSource] addSubresource:resource];
452     return resource;
453 }
454 #endif
455
456 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
457 {
458     BOOL chosePlainText;
459     DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:allowPlainText chosePlainText:&chosePlainText];
460     WebBridge *bridge = [self _bridge];
461     if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[self _selectedRange] givenAction:WebViewInsertActionPasted]) {
462         [bridge replaceSelectionWithFragment:fragment selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard] matchStyle:chosePlainText];
463     }
464 }
465
466 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
467 {
468     WebView *webView = [self _webView];
469     DOMNode *child = [fragment firstChild];
470     if ([fragment lastChild] == child && [child isKindOfClass:[DOMCharacterData class]]) {
471         return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:[(DOMCharacterData *)child data] replacingDOMRange:range givenAction:action];
472     } else {
473         return [[webView _editingDelegateForwarder] webView:webView shouldInsertNode:fragment replacingDOMRange:range givenAction:action];
474     }
475 }
476
477 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action
478 {
479     WebView *webView = [self _webView];
480     DOMRange *selectedRange = [self _selectedRange];
481     return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:selectedRange givenAction:action];
482 }
483
484 // Calculate the vertical size of the view that fits on a single page
485 - (float)_calculatePrintHeight
486 {
487     // Obtain the print info object for the current operation
488     NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
489     
490     // Calculate the page height in points
491     NSSize paperSize = [pi paperSize];
492     return paperSize.height - [pi topMargin] - [pi bottomMargin];
493 }
494
495 - (void)_updateTextSizeMultiplier
496 {
497     [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];    
498 }
499
500 - (DOMRange *)_selectedRange
501 {
502     return [[self _bridge] selectedDOMRange];
503 }
504
505 - (BOOL)_shouldDeleteRange:(DOMRange *)range
506 {
507     if (range == nil || [range collapsed])
508         return NO;
509     
510     if (![[self _bridge] canDeleteRange:range])
511         return NO;
512         
513     WebView *webView = [self _webView];
514     return [[webView _editingDelegateForwarder] webView:webView shouldDeleteDOMRange:range];
515 }
516
517 - (void)_deleteRange:(DOMRange *)range 
518             killRing:(BOOL)killRing 
519              prepend:(BOOL)prepend 
520        smartDeleteOK:(BOOL)smartDeleteOK 
521       deletionAction:(WebDeletionAction)deletionAction
522 {
523     if (![self _shouldDeleteRange:range]) {
524         return;
525     }
526
527     WebBridge *bridge = [self _bridge];
528     BOOL smartDelete = smartDeleteOK ? [self _canSmartCopyOrDelete] : NO;
529
530     BOOL startNewKillRingSequence = _private->startNewKillRingSequence;
531
532     if (killRing) {
533         if (startNewKillRingSequence) {
534             _NSNewKillRingSequence();
535         }
536         NSString *string = [bridge stringForRange:range];
537         if (prepend) {
538             _NSPrependToKillRing(string);
539         } else {
540             _NSAppendToKillRing(string);
541         }
542         startNewKillRingSequence = NO;
543     }
544
545     switch (deletionAction) {
546         case deleteSelectionAction:
547             [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:YES];
548             [bridge deleteSelectionWithSmartDelete:smartDelete];
549             break;
550         case deleteKeyAction:
551             [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:NO];
552             [bridge deleteKeyPressedWithSmartDelete:smartDelete];
553             break;
554         case forwardDeleteKeyAction:
555             [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:NO];
556             [bridge forwardDeleteKeyPressedWithSmartDelete:smartDelete];
557             break;
558     }
559
560     _private->startNewKillRingSequence = startNewKillRingSequence;
561 }
562
563 - (void)_deleteSelection
564 {
565     [self _deleteRange:[self _selectedRange]
566               killRing:YES 
567                prepend:NO
568          smartDeleteOK:YES
569         deletionAction:deleteSelectionAction];
570 }
571
572 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard
573 {
574     return [[self _webView] smartInsertDeleteEnabled] && [[pasteboard types] containsObject:WebSmartPastePboardType];
575 }
576
577 - (NSView *)_hitViewForEvent:(NSEvent *)event
578 {
579     // Usually, we hack AK's hitTest method to catch all events at the topmost WebHTMLView.  
580     // Callers of this method, however, want to query the deepest view instead.
581     forceRealHitTest = YES;
582     NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
583     forceRealHitTest = NO;    
584     return hitView;
585 }
586
587 // This method is copied from NSTextView
588 - (NSAttributedString *)_stripAttachmentCharactersFromAttributedString:(NSAttributedString *)originalAttributedString
589 {
590     NSRange attachmentRange;
591     NSString *originalString = [originalAttributedString string];
592     static NSString *attachmentCharString = nil;
593     
594     if (!attachmentCharString) {
595         unichar chars[2];
596         if (!attachmentCharString) {
597             chars[0] = NSAttachmentCharacter;
598             chars[1] = 0;
599             attachmentCharString = [[NSString alloc] initWithCharacters:chars length:1];
600         }
601     }
602     
603     attachmentRange = [originalString rangeOfString:attachmentCharString];
604     if (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
605         NSMutableAttributedString *newAttributedString = [[originalAttributedString mutableCopyWithZone:NULL] autorelease];
606         
607         while (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
608             [newAttributedString replaceCharactersInRange:attachmentRange withString:@""];
609             attachmentRange = [[newAttributedString string] rangeOfString:attachmentCharString];
610         }
611         return newAttributedString;
612     } else {
613         return originalAttributedString;
614     }
615 }
616
617 - (void)_writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard cachedAttributedString:(NSAttributedString *)attributedString
618 {
619     // Put HTML on the pasteboard.
620     if ([types containsObject:WebArchivePboardType]) {
621         WebArchive *archive = [self _selectedArchive];
622         [pasteboard setData:[archive data] forType:WebArchivePboardType];
623     }
624     
625     // Put the attributed string on the pasteboard (RTF/RTFD format).
626     if ([types containsObject:NSRTFDPboardType]) {
627         if (attributedString == nil) {
628             attributedString = [self selectedAttributedString];
629         }        
630         NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
631         [pasteboard setData:RTFDData forType:NSRTFDPboardType];
632     }        
633     if ([types containsObject:NSRTFPboardType]) {
634         if (attributedString == nil) {
635             attributedString = [self selectedAttributedString];
636         }
637         if ([attributedString containsAttachments]) {
638             attributedString = [self _stripAttachmentCharactersFromAttributedString:attributedString];
639         }
640         NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
641         [pasteboard setData:RTFData forType:NSRTFPboardType];
642     }
643     
644     // Put plain string on the pasteboard.
645     if ([types containsObject:NSStringPboardType]) {
646         // Map &nbsp; to a plain old space because this is better for source code, other browsers do it,
647         // and because HTML forces you to do this any time you want two spaces in a row.
648         NSMutableString *s = [[self selectedString] mutableCopy];
649         const unichar NonBreakingSpaceCharacter = 0xA0;
650         NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
651         [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
652         [pasteboard setString:s forType:NSStringPboardType];
653         [s release];
654     }
655     
656     if ([self _canSmartCopyOrDelete] && [types containsObject:WebSmartPastePboardType]) {
657         [pasteboard setData:nil forType:WebSmartPastePboardType];
658     }
659 }
660
661 @end
662
663 @implementation WebHTMLView (WebPrivate)
664
665 - (void)_reset
666 {
667     [WebImageRenderer stopAnimationsInView:self];
668 }
669
670 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
671 {
672     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
673         location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
674         modifierFlags:[flagsChangedEvent modifierFlags]
675         timestamp:[flagsChangedEvent timestamp]
676         windowNumber:[flagsChangedEvent windowNumber]
677         context:[flagsChangedEvent context]
678         eventNumber:0 clickCount:0 pressure:0];
679
680     // Pretend it's a mouse move.
681     [[NSNotificationCenter defaultCenter]
682         postNotificationName:NSMouseMovedNotification object:self
683         userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
684 }
685
686 - (void)_updateMouseoverWithFakeEvent
687 {
688     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
689         location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
690         modifierFlags:[[NSApp currentEvent] modifierFlags]
691         timestamp:[NSDate timeIntervalSinceReferenceDate]
692         windowNumber:[[self window] windowNumber]
693         context:[[NSApp currentEvent] context]
694         eventNumber:0 clickCount:0 pressure:0];
695     
696     [self _updateMouseoverWithEvent:fakeEvent];
697 }
698
699 - (void)_frameOrBoundsChanged
700 {
701     if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
702         [self setNeedsLayout:YES];
703         [self setNeedsDisplay:YES];
704         [_private->compController endRevertingChange:NO moveLeft:NO];
705     }
706
707     NSPoint origin = [[self superview] bounds].origin;
708     if (!NSEqualPoints(_private->lastScrollPosition, origin)) {
709         [[self _bridge] sendScrollEvent];
710         [_private->compController endRevertingChange:NO moveLeft:NO];
711     }
712     _private->lastScrollPosition = origin;
713
714     SEL selector = @selector(_updateMouseoverWithFakeEvent);
715     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
716     [self performSelector:selector withObject:nil afterDelay:0];
717 }
718
719 - (void)_setAsideSubviews
720 {
721     ASSERT(!_private->subviewsSetAside);
722     ASSERT(_private->savedSubviews == nil);
723     _private->savedSubviews = _subviews;
724     _subviews = nil;
725     _private->subviewsSetAside = YES;
726  }
727  
728  - (void)_restoreSubviews
729  {
730     ASSERT(_private->subviewsSetAside);
731     ASSERT(_subviews == nil);
732     _subviews = _private->savedSubviews;
733     _private->savedSubviews = nil;
734     _private->subviewsSetAside = NO;
735 }
736
737 // This is called when we are about to draw, but before our dirty rect is propagated to our ancestors.
738 // That's the perfect time to do a layout, except that ideally we'd want to be sure that we're dirty
739 // before doing it. As a compromise, when we're opaque we do the layout only when actually asked to
740 // draw, but when we're transparent we do the layout at this stage so views behind us know that they
741 // need to be redrawn (in case the layout causes some things to get dirtied).
742 - (void)_propagateDirtyRectsToOpaqueAncestors
743 {
744     if (![[self _webView] drawsBackground]) {
745         [self _web_layoutIfNeededRecursive];
746     }
747     [super _propagateDirtyRectsToOpaqueAncestors];
748 }
749
750 // Don't let AppKit even draw subviews. We take care of that.
751 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
752 {
753     // This helps when we print as part of a larger print process.
754     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
755     BOOL wasInPrintingMode = _private->printing;
756     BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
757     if (wasInPrintingMode != isPrinting) {
758         if (isPrinting) {
759             [self _web_setPrintingModeRecursive];
760         } else {
761             [self _web_clearPrintingModeRecursive];
762         }
763     }
764
765     [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
766
767     [self _setAsideSubviews];
768     [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
769         rectIsVisibleRectForView:visibleView topView:topView];
770     [self _restoreSubviews];
771
772     if (wasInPrintingMode != isPrinting) {
773         if (wasInPrintingMode) {
774             [self _web_setPrintingModeRecursive];
775         } else {
776             [self _web_clearPrintingModeRecursive];
777         }
778     }
779 }
780
781 // Don't let AppKit even draw subviews. We take care of that.
782 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
783 {
784     BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
785
786     BOOL wasInPrintingMode = _private->printing;
787     BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
788
789     if (needToSetAsideSubviews) {
790         // This helps when we print as part of a larger print process.
791         // If the WebHTMLView itself is what we're printing, then we will never have to do this.
792         if (wasInPrintingMode != isPrinting) {
793             if (isPrinting) {
794                 [self _web_setPrintingModeRecursive];
795             } else {
796                 [self _web_clearPrintingModeRecursive];
797             }
798         }
799
800         NSRect boundsBeforeLayout = [self bounds];
801         [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
802
803         // If layout changes the view's bounds, then we need to recompute the visRect.
804         // That's because the visRect passed to us was based on the bounds at the time
805         // we were called. This method is only displayed to draw "all", so it's safe
806         // to just call visibleRect to compute the entire rectangle.
807         if (!NSEqualRects(boundsBeforeLayout, [self bounds])) {
808             visRect = [self visibleRect];
809         }
810
811         [self _setAsideSubviews];
812     }
813     
814     [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
815     
816     if (needToSetAsideSubviews) {
817         if (wasInPrintingMode != isPrinting) {
818             if (wasInPrintingMode) {
819                 [self _web_setPrintingModeRecursive];
820             } else {
821                 [self _web_clearPrintingModeRecursive];
822             }
823         }
824
825         [self _restoreSubviews];
826     }
827 }
828
829 - (BOOL)_insideAnotherHTMLView
830 {
831     NSView *view = self;
832     while ((view = [view superview])) {
833         if ([view isKindOfClass:[WebHTMLView class]]) {
834             return YES;
835         }
836     }
837     return NO;
838 }
839
840 - (void)scrollPoint:(NSPoint)point
841 {
842     // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
843     // If we get called during the handling of a key down event, we assume the call came from
844     // NSTextView, and ignore it and use our own code to decide how to page up and page down
845     // We are smarter about how far to scroll, and we have "superview scrolling" logic.
846     NSEvent *event = [[self window] currentEvent];
847     if ([event type] == NSKeyDown) {
848         const unichar pageUp = NSPageUpFunctionKey;
849         if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
850             [self tryToPerform:@selector(scrollPageUp:) with:nil];
851             return;
852         }
853         const unichar pageDown = NSPageDownFunctionKey;
854         if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
855             [self tryToPerform:@selector(scrollPageDown:) with:nil];
856             return;
857         }
858     }
859     
860     [super scrollPoint:point];
861 }
862
863 - (NSView *)hitTest:(NSPoint)point
864 {
865     // WebHTMLView objects handle all left mouse clicks for objects inside them.
866     // That does not include left mouse clicks with the control key held down.
867     BOOL captureHitsOnSubviews;
868     if (forceRealHitTest) {
869         captureHitsOnSubviews = NO;
870     } else {
871         NSEvent *event = [[self window] currentEvent];
872         captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
873     }
874     if (!captureHitsOnSubviews) {
875         return [super hitTest:point];
876     }
877     if ([[self superview] mouse:point inRect:[self frame]]) {
878         return self;
879     }
880     return nil;
881 }
882
883 static WebHTMLView *lastHitView = nil;
884
885 - (void)_clearLastHitViewIfSelf
886 {
887     if (lastHitView == self) {
888         lastHitView = nil;
889     }
890 }
891
892 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
893 {
894     ASSERT(_private->trackingRectOwner == nil);
895     _private->trackingRectOwner = owner;
896     _private->trackingRectUserData = data;
897     return TRACKING_RECT_TAG;
898 }
899
900 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
901 {
902     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
903     ASSERT(_private->trackingRectOwner == nil);
904     _private->trackingRectOwner = owner;
905     _private->trackingRectUserData = data;
906     return TRACKING_RECT_TAG;
907 }
908
909 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
910 {
911     ASSERT(count == 1);
912     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
913     ASSERT(_private->trackingRectOwner == nil);
914     _private->trackingRectOwner = owner;
915     _private->trackingRectUserData = userDataList[0];
916     trackingNums[0] = TRACKING_RECT_TAG;
917 }
918
919 - (void)removeTrackingRect:(NSTrackingRectTag)tag
920 {
921     if (tag == 0)
922         return;
923     ASSERT(tag == TRACKING_RECT_TAG);
924     if (_private != nil) {
925         _private->trackingRectOwner = nil;
926     }
927 }
928
929 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
930 {
931     int i;
932     for (i = 0; i < count; ++i) {
933         int tag = tags[i];
934         if (tag == 0)
935             continue;
936         ASSERT(tag == TRACKING_RECT_TAG);
937         if (_private != nil) {
938             _private->trackingRectOwner = nil;
939         }
940     }
941 }
942
943 - (void)_sendToolTipMouseExited
944 {
945     // Nothing matters except window, trackingNumber, and userData.
946     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
947         location:NSMakePoint(0, 0)
948         modifierFlags:0
949         timestamp:0
950         windowNumber:[[self window] windowNumber]
951         context:NULL
952         eventNumber:0
953         trackingNumber:TRACKING_RECT_TAG
954         userData:_private->trackingRectUserData];
955     [_private->trackingRectOwner mouseExited:fakeEvent];
956 }
957
958 - (void)_sendToolTipMouseEntered
959 {
960     // Nothing matters except window, trackingNumber, and userData.
961     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
962         location:NSMakePoint(0, 0)
963         modifierFlags:0
964         timestamp:0
965         windowNumber:[[self window] windowNumber]
966         context:NULL
967         eventNumber:0
968         trackingNumber:TRACKING_RECT_TAG
969         userData:_private->trackingRectUserData];
970     [_private->trackingRectOwner mouseEntered:fakeEvent];
971 }
972
973 - (void)_setToolTip:(NSString *)string
974 {
975     NSString *toolTip = [string length] == 0 ? nil : string;
976     NSString *oldToolTip = _private->toolTip;
977     if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
978         return;
979     }
980     if (oldToolTip) {
981         [self _sendToolTipMouseExited];
982         [oldToolTip release];
983     }
984     _private->toolTip = [toolTip copy];
985     if (toolTip) {
986         [self removeAllToolTips];
987         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
988         [self addToolTipRect:wideOpenRect owner:self userData:NULL];
989         [self _sendToolTipMouseEntered];
990     }
991 }
992
993 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
994 {
995     return [[_private->toolTip copy] autorelease];
996 }
997
998 - (void)_updateMouseoverWithEvent:(NSEvent *)event
999 {
1000     [self retain];
1001     
1002     WebHTMLView *view = nil;
1003     if ([event window] == [self window]) {
1004         NSView *hitView = [self _hitViewForEvent:event];
1005         while (hitView) {
1006             if ([hitView isKindOfClass:[WebHTMLView class]]) {
1007                 view = (WebHTMLView *)hitView;
1008                 break;
1009             }
1010             hitView = [hitView superview];
1011         }
1012     }
1013
1014     if (lastHitView != view && lastHitView != nil) {
1015         // If we are moving out of a view (or frame), let's pretend the mouse moved
1016         // all the way out of that view. But we have to account for scrolling, because
1017         // khtml doesn't understand our clipping.
1018         NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
1019         float yScroll = visibleRect.origin.y;
1020         float xScroll = visibleRect.origin.x;
1021
1022         event = [NSEvent mouseEventWithType:NSMouseMoved
1023                          location:NSMakePoint(-1 - xScroll, -1 - yScroll )
1024                          modifierFlags:[[NSApp currentEvent] modifierFlags]
1025                          timestamp:[NSDate timeIntervalSinceReferenceDate]
1026                          windowNumber:[[self window] windowNumber]
1027                          context:[[NSApp currentEvent] context]
1028                          eventNumber:0 clickCount:0 pressure:0];
1029         [[lastHitView _bridge] mouseMoved:event];
1030     }
1031
1032     lastHitView = view;
1033     
1034     NSDictionary *element;
1035     if (view == nil) {
1036         element = nil;
1037     } else {
1038         [[view _bridge] mouseMoved:event];
1039
1040         NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
1041         element = [view elementAtPoint:point];
1042     }
1043
1044     // Have the web view send a message to the delegate so it can do status bar display.
1045     [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
1046
1047     // Set a tool tip; it won't show up right away but will if the user pauses.
1048     NSString *newToolTip = nil;
1049     if (_private->showsURLsInToolTips) {
1050         newToolTip = [[element objectForKey:WebCoreElementLinkURLKey] _web_userVisibleString];
1051     }
1052     if (newToolTip == nil) {
1053         newToolTip = [element objectForKey:WebCoreElementTitleKey];
1054     }
1055     [self _setToolTip:newToolTip];
1056     
1057     [self release];
1058 }
1059
1060 + (NSArray *)_insertablePasteboardTypes
1061 {
1062     static NSArray *types = nil;
1063     if (!types) {
1064         types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
1065             NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType, 
1066             NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
1067     }
1068     return types;
1069 }
1070
1071 + (NSArray *)_selectionPasteboardTypes
1072 {
1073     // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
1074     return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil];
1075 }
1076
1077 - (WebArchive *)_selectedArchive
1078 {
1079     NSArray *nodes;
1080 #if !LOG_DISABLED        
1081     double start = CFAbsoluteTimeGetCurrent();
1082 #endif
1083     NSString *markupString = [[self _bridge] markupStringFromRange:[self _selectedRange] nodes:&nodes];
1084 #if !LOG_DISABLED
1085     double duration = CFAbsoluteTimeGetCurrent() - start;
1086     LOG(Timing, "copying markup took %f seconds.", duration);
1087 #endif
1088     
1089     WebArchive *archive = [[self _dataSource] _archiveWithMarkupString:markupString nodes:nodes];
1090
1091     if ([[self _bridge] isFrameSet]) {
1092         // Wrap the frameset document in an iframe so it can be pasted into
1093         // another document (which will have a body or frameset of its own). 
1094         NSString *iframeMarkup = [[NSString alloc] initWithFormat:@"<iframe frameborder=\"no\" marginwidth=\"0\" marginheight=\"0\" width=\"98%%\" height=\"98%%\" src=\"%@\"></iframe>", [[[self _dataSource] response] URL]];
1095         WebResource *iframeResource = [[WebResource alloc] initWithData:[iframeMarkup dataUsingEncoding:NSUTF8StringEncoding]
1096                                                                   URL:[NSURL URLWithString:@"about:blank"]
1097                                                              MIMEType:@"text/html"
1098                                                      textEncodingName:@"UTF-8"
1099                                                             frameName:nil];
1100         
1101         NSArray *subframeArchives = [NSArray arrayWithObject:archive];
1102         archive = [[[WebArchive alloc] initWithMainResource:iframeResource subresources:nil subframeArchives:subframeArchives] autorelease];
1103         
1104         [iframeResource release];
1105         [iframeMarkup release];
1106     }
1107
1108     return archive;
1109 }
1110
1111 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
1112 {
1113     ASSERT([self _hasSelection]);
1114     NSArray *types = [self pasteboardTypesForSelection];
1115     
1116     // Don't write RTFD to the pasteboard when the copied attributed string has no attachments.
1117     NSAttributedString *attributedString = [self selectedAttributedString];
1118     NSMutableArray *mutableTypes = nil;
1119     if (![attributedString containsAttachments]) {
1120         mutableTypes = [types mutableCopy];
1121         [mutableTypes removeObject:NSRTFDPboardType];
1122         types = mutableTypes;
1123     }
1124     
1125     [pasteboard declareTypes:types owner:nil];
1126     [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:attributedString];
1127     [mutableTypes release];
1128 }
1129
1130 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
1131 {
1132     NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
1133
1134     BOOL drawURLString = YES;
1135     BOOL clipURLString = NO, clipLabelString = NO;
1136     
1137     NSString *label = [element objectForKey: WebElementLinkLabelKey];
1138     NSString *urlString = [linkURL _web_userVisibleString];
1139     
1140     if (!label) {
1141         drawURLString = NO;
1142         label = urlString;
1143     }
1144     
1145     NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
1146                                                    toHaveTrait:NSBoldFontMask];
1147     NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
1148     NSSize labelSize;
1149     labelSize.width = [label _web_widthWithFont: labelFont];
1150     labelSize.height = [labelFont ascender] - [labelFont descender];
1151     if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
1152         labelSize.width = MAX_DRAG_LABEL_WIDTH;
1153         clipLabelString = YES;
1154     }
1155     
1156     NSSize imageSize, urlStringSize;
1157     imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
1158     imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
1159     if (drawURLString) {
1160         urlStringSize.width = [urlString _web_widthWithFont: urlFont];
1161         urlStringSize.height = [urlFont ascender] - [urlFont descender];
1162         imageSize.height += urlStringSize.height;
1163         if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
1164             imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
1165             clipURLString = YES;
1166         } else {
1167             imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
1168         }
1169     }
1170     NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
1171     [dragImage lockFocus];
1172     
1173     [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
1174     
1175     // Drag a rectangle with rounded corners/
1176     NSBezierPath *path = [NSBezierPath bezierPath];
1177     [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1178     [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1179     [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1180     [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1181     
1182     [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
1183     [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1184     [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1185     [path fill];
1186         
1187     NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
1188     NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
1189     if (drawURLString) {
1190         if (clipURLString)
1191             urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
1192
1193         [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender]) 
1194              withTopColor:topColor bottomColor:bottomColor font:urlFont];
1195     }
1196
1197     if (clipLabelString)
1198         label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
1199     [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
1200              withTopColor:topColor bottomColor:bottomColor font:labelFont];
1201     
1202     [dragImage unlockFocus];
1203     
1204     return dragImage;
1205 }
1206
1207 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
1208 {
1209     NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
1210     NSDictionary *element = [self elementAtPoint:mouseDownPoint];
1211
1212     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1213     NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
1214     BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
1215
1216     [_private->draggingImageURL release];
1217     _private->draggingImageURL = nil;
1218
1219     NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
1220     _private->webCoreDragOp = op;     // will be DragNone if WebCore doesn't care
1221     NSImage *dragImage = nil;
1222     NSPoint dragLoc = { 0, 0 }; // quiet gcc 4.0 warning
1223
1224     // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
1225     // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
1226     // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
1227     if (wcDragImage) {
1228         dragImage = wcDragImage;
1229         // wcDragLoc is the cursor position relative to the lower-left corner of the image.
1230         // We add in the Y dimension because we are a flipped view, so adding moves the image down.
1231         if (linkURL) {
1232             // see HACK below
1233             dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
1234         } else {
1235             dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
1236         }
1237         _private->dragOffset = wcDragLoc;
1238     }
1239     
1240     WebView *webView = [self _webView];
1241     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
1242     WebImageRenderer *image = [element objectForKey:WebElementImageKey];
1243     BOOL startedDrag = YES;  // optimism - we almost always manage to start the drag
1244
1245     // note per kwebster, the offset arg below is always ignored in positioning the image
1246     if (imageURL != nil && image != nil && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1247         id source = self;
1248         if (!dhtmlWroteData) {
1249             // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
1250             DOMHTMLElement *imageElement = [element objectForKey:WebElementDOMNodeKey];
1251             ASSERT(imageElement != nil);
1252             [webView setSelectedDOMRange:[[[self _bridge] DOMDocument] _createRangeWithNode:imageElement] affinity:NSSelectionAffinityDownstream];
1253             _private->draggingImageURL = [imageURL retain];
1254             source = [pasteboard _web_declareAndWriteDragImage:image
1255                                                            URL:linkURL ? linkURL : imageURL
1256                                                          title:[element objectForKey:WebElementImageAltStringKey]
1257                                                        archive:[imageElement webArchive]
1258                                                         source:self];
1259         }
1260         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
1261         if (dragImage == nil) {
1262             [self _web_dragImage:[element objectForKey:WebElementImageKey]
1263                             rect:[[element objectForKey:WebElementImageRectKey] rectValue]
1264                            event:_private->mouseDownEvent
1265                       pasteboard:pasteboard
1266                           source:source
1267                           offset:&_private->dragOffset];
1268         } else {
1269             [self dragImage:dragImage
1270                          at:dragLoc
1271                      offset:NSZeroSize
1272                       event:_private->mouseDownEvent
1273                  pasteboard:pasteboard
1274                      source:source
1275                   slideBack:YES];
1276         }
1277     } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1278         if (!dhtmlWroteData) {
1279             NSArray *types = [NSPasteboard _web_writableTypesForURL];
1280             [pasteboard declareTypes:types owner:self];
1281             [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];            
1282         }
1283         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1284         if (dragImage == nil) {
1285             dragImage = [self _dragImageForLinkElement:element];
1286             NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1287             dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1288             _private->dragOffset.x = offset.width;
1289             _private->dragOffset.y = -offset.height;        // inverted because we are flipped
1290         }
1291         // HACK:  We should pass the mouseDown event instead of the mouseDragged!  This hack gets rid of
1292         // a flash of the image at the mouseDown location when the drag starts.
1293         [self dragImage:dragImage
1294                      at:dragLoc
1295                  offset:NSZeroSize
1296                   event:mouseDraggedEvent
1297              pasteboard:pasteboard
1298                  source:self
1299               slideBack:YES];
1300     } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1301         if (!dhtmlWroteData) {
1302             [self _writeSelectionToPasteboard:pasteboard];
1303         }
1304         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1305         if (dragImage == nil) {
1306             dragImage = [self _selectionDraggingImage];
1307             NSRect draggingRect = [self _selectionDraggingRect];
1308             dragLoc = NSMakePoint(NSMinX(draggingRect), NSMaxY(draggingRect));
1309             _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1310             _private->dragOffset.y = dragLoc.y - mouseDownPoint.y;        // inverted because we are flipped
1311         }
1312         [self dragImage:dragImage
1313                      at:dragLoc
1314                  offset:NSZeroSize
1315                   event:_private->mouseDownEvent
1316              pasteboard:pasteboard
1317                  source:self
1318               slideBack:YES];
1319     } else if (srcIsDHTML) {
1320         ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1321         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1322         if (dragImage == nil) {
1323             // WebCore should have given us an image, but we'll make one up
1324             NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1325             dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1326             NSSize imageSize = [dragImage size];
1327             dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width/2, mouseDownPoint.y + imageSize.height/2);
1328             _private->dragOffset.x = imageSize.width/2;
1329             _private->dragOffset.y = imageSize.height/2;        // inverted because we are flipped
1330         }
1331         [self dragImage:dragImage
1332                      at:dragLoc
1333                  offset:NSZeroSize
1334                   event:_private->mouseDownEvent
1335              pasteboard:pasteboard
1336                  source:self
1337               slideBack:YES];
1338     } else {
1339         // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1340         // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1341         startedDrag = NO;
1342     }
1343     return startedDrag;
1344 }
1345
1346 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1347 {
1348     [self autoscroll:event];
1349     [self _startAutoscrollTimer:event];
1350 }
1351
1352 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1353 {
1354     NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1355     NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint];
1356
1357     ASSERT([self _webView]);
1358     if ([mouseDownElement objectForKey: WebElementImageKey] != nil &&
1359         [mouseDownElement objectForKey: WebElementImageURLKey] != nil && 
1360         [[[self _webView] preferences] loadsImagesAutomatically] && 
1361         (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1362         return YES;
1363     }
1364     
1365     if ([mouseDownElement objectForKey:WebElementLinkURLKey] != nil && 
1366         (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1367         return YES;
1368     }
1369     
1370     if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
1371         (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1372         return YES;
1373     }
1374     
1375     return NO;
1376 }
1377
1378 - (WebPluginController *)_pluginController
1379 {
1380     return _private->pluginController;
1381 }
1382
1383 - (void)_web_setPrintingModeRecursive
1384 {
1385     [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1386     [super _web_setPrintingModeRecursive];
1387 }
1388
1389 - (void)_web_clearPrintingModeRecursive
1390 {
1391     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1392     [super _web_clearPrintingModeRecursive];
1393 }
1394
1395 - (void)_layoutIfNeeded
1396 {
1397     ASSERT(!_private->subviewsSetAside);
1398
1399     if ([[self _bridge] needsLayout])
1400         _private->needsLayout = YES;
1401     if (_private->needsToApplyStyles || _private->needsLayout)
1402         [self layout];
1403 }
1404
1405 - (void)_web_layoutIfNeededRecursive
1406 {
1407     [self _layoutIfNeeded];
1408     [super _web_layoutIfNeededRecursive];
1409 }
1410
1411 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1412 {
1413     ASSERT(!_private->subviewsSetAside);
1414     displayRect = NSIntersectionRect(displayRect, [self bounds]);
1415
1416     if (!testDirtyRect || [self needsDisplay]) {
1417         if (testDirtyRect) {
1418             NSRect dirtyRect = [self _dirtyRect];
1419             displayRect = NSIntersectionRect(displayRect, dirtyRect);
1420         }
1421         if (!NSIsEmptyRect(displayRect)) {
1422             [self _layoutIfNeeded];
1423         }
1424     }
1425
1426     [super _web_layoutIfNeededRecursive:displayRect testDirtyRect:NO];
1427 }
1428
1429 - (NSRect)_selectionRect
1430 {
1431     return [[self _bridge] selectionRect];
1432 }
1433
1434 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1435 {
1436     if (_private->autoscrollTimer == nil) {
1437         _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1438             target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1439         _private->autoscrollTriggerEvent = [triggerEvent retain];
1440     }
1441 }
1442
1443 - (void)_stopAutoscrollTimer
1444 {
1445     NSTimer *timer = _private->autoscrollTimer;
1446     _private->autoscrollTimer = nil;
1447     [_private->autoscrollTriggerEvent release];
1448     _private->autoscrollTriggerEvent = nil;
1449     [timer invalidate];
1450     [timer release];
1451 }
1452
1453 - (void)_autoscroll
1454 {
1455     int isStillDown;
1456     
1457     // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1458     // a mouse up event.
1459     PSstilldown([_private->autoscrollTriggerEvent eventNumber], &isStillDown);
1460     if (!isStillDown){
1461         [self _stopAutoscrollTimer];
1462         return;
1463     }
1464
1465     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1466         location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1467         modifierFlags:[[NSApp currentEvent] modifierFlags]
1468         timestamp:[NSDate timeIntervalSinceReferenceDate]
1469         windowNumber:[[self window] windowNumber]
1470         context:[[NSApp currentEvent] context]
1471         eventNumber:0 clickCount:0 pressure:0];
1472     [self mouseDragged:fakeEvent];
1473 }
1474
1475 - (BOOL)_canCopy
1476 {
1477     // Copying can be done regardless of whether you can edit.
1478     return [self _hasSelection];
1479 }
1480
1481 - (BOOL)_canCut
1482 {
1483     return [self _hasSelection] && [self _isEditable];
1484 }
1485
1486 - (BOOL)_canDelete
1487 {
1488     return [self _hasSelection] && [self _isEditable];
1489 }
1490
1491 - (BOOL)_canPaste
1492 {
1493     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1494 }
1495
1496 - (BOOL)_canEdit
1497 {
1498     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1499 }
1500
1501 - (BOOL)_hasSelection
1502 {
1503     return [[self _bridge] selectionState] == WebSelectionStateRange;
1504 }
1505
1506 - (BOOL)_hasSelectionOrInsertionPoint
1507 {
1508     return [[self _bridge] selectionState] != WebSelectionStateNone;
1509 }
1510
1511 - (BOOL)_isEditable
1512 {
1513     return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1514 }
1515
1516 - (BOOL)_isSelectionMisspelled
1517 {
1518     NSString *selectedString = [self selectedString];
1519     unsigned length = [selectedString length];
1520     if (length == 0) {
1521         return NO;
1522     }
1523     NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1524                                                                     startingAt:0
1525                                                                       language:nil
1526                                                                           wrap:NO
1527                                                         inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1528                                                                      wordCount:NULL];
1529     return range.length == length;
1530 }
1531
1532 - (NSArray *)_guessesForMisspelledSelection
1533 {
1534     ASSERT([[self selectedString] length] != 0);
1535     return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1536 }
1537
1538 - (void)_changeSpellingFromMenu:(id)sender
1539 {
1540     ASSERT([[self selectedString] length] != 0);
1541     [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1542 }
1543
1544 - (void)_ignoreSpellingFromMenu:(id)sender
1545 {
1546     ASSERT([[self selectedString] length] != 0);
1547     [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1548 }
1549
1550 - (void)_learnSpellingFromMenu:(id)sender
1551 {
1552     ASSERT([[self selectedString] length] != 0);
1553     [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1554 }
1555
1556 #ifndef OMIT_TIGER_FEATURES
1557 - (void)_searchWithGoogleFromMenu:(id)sender
1558 {
1559     // This should only be called when there's a selection, but play it safe.
1560     if (![self _hasSelection]) {
1561         return;
1562     }
1563     
1564     NSPasteboard *pboard = [NSPasteboard pasteboardWithUniqueName];
1565     if ([self writeSelectionToPasteboard:pboard types:[NSArray arrayWithObject:NSStringPboardType]]) {
1566         // FIXME: seems fragile to use the service by name, but this is what AppKit does
1567         NSPerformService(@"Search With Google", pboard);
1568     }
1569 }
1570
1571 - (void)_searchWithSpotlightFromMenu:(id)sender
1572 {
1573     // This should only be called when there's a selection, but play it safe.
1574     if (![self _hasSelection]) {
1575         return;
1576     }
1577
1578     (void)HISearchWindowShow((CFStringRef)[self selectedString], kNilOptions);
1579 }
1580 - (void)_lookUpInDictionaryFromMenu:(id)sender
1581 {
1582     // This should only be called when there's a selection, but play it safe.
1583     if (![self _hasSelection]) {
1584         return;
1585     }
1586     
1587     // Soft link to dictionary-display function to avoid linking another framework (ApplicationServices/LangAnalysis)
1588     static OSStatus (*__dictionaryServiceWindowShow)(id inWordString, NSRect inWordBoundary, UInt16 inLineDirection) = NULL;
1589     static const struct mach_header *frameworkImageHeader = NULL;
1590     static BOOL lookedForFunction = NO;
1591     if (!lookedForFunction) {
1592         __dictionaryServiceWindowShow = _NSSoftLinkingGetFrameworkFuncPtr(@"ApplicationServices", @"LangAnalysis", "_DCMDictionaryServiceWindowShow", &frameworkImageHeader);
1593         lookedForFunction = YES;
1594     }
1595     if (!__dictionaryServiceWindowShow) {
1596         ERROR("Couldn't find _DCMDictionaryServiceWindowShow"); 
1597         return;
1598     }
1599     
1600     // FIXME: must check for right-to-left here
1601     NSWritingDirection writingDirection = NSWritingDirectionLeftToRight;
1602     
1603     NSAttributedString *attrString = [self selectedAttributedString];
1604     // FIXME: the dictionary API expects the rect for the first line of selection. Passing
1605     // the rect for the entire selection, as we do here, positions the pop-up window near
1606     // the bottom of the selection rather than at the selected word.
1607     NSRect rect = [self convertRect:[[self _bridge] visibleSelectionRect] toView:nil];
1608     rect.origin = [[self window] convertBaseToScreen:rect.origin];
1609     NSData *data = [attrString RTFFromRange:NSMakeRange(0, [attrString length]) documentAttributes:nil];
1610     (void)__dictionaryServiceWindowShow(data, rect, (writingDirection == NSWritingDirectionRightToLeft) ? 1 : 0);
1611 }
1612 #endif
1613
1614 #if APPKIT_CODE_FOR_REFERENCE
1615
1616 - (void)_openLinkFromMenu:(id)sender
1617 {
1618     NSTextStorage *text = _getTextStorage(self);
1619     NSRange charRange = [self selectedRange];
1620     if (charRange.location != NSNotFound && charRange.length > 0) {
1621         id link = [text attribute:NSLinkAttributeName atIndex:charRange.location effectiveRange:NULL];
1622         if (link) {
1623             [self clickedOnLink:link atIndex:charRange.location];
1624         } else {
1625             NSString *string = [[text string] substringWithRange:charRange];
1626             link = [NSURL URLWithString:string];
1627             if (link) [[NSWorkspace sharedWorkspace] openURL:link];
1628         }
1629     }
1630 }
1631
1632 #endif
1633
1634 - (BOOL)_transparentBackground
1635 {
1636     return _private->transparentBackground;
1637 }
1638
1639 - (void)_setTransparentBackground:(BOOL)f
1640 {
1641     _private->transparentBackground = f;
1642 }
1643
1644 - (NSImage *)_selectionDraggingImage
1645 {
1646     if ([self _hasSelection]) {
1647         NSImage *dragImage = [[self _bridge] selectionImage];
1648         [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1649         return dragImage;
1650     }
1651     return nil;
1652 }
1653
1654 - (NSRect)_selectionDraggingRect
1655 {
1656     if ([self _hasSelection]) {
1657         return [[self _bridge] visibleSelectionRect];
1658     }
1659     return NSZeroRect;
1660 }
1661
1662 @end
1663
1664 @implementation NSView (WebHTMLViewFileInternal)
1665
1666 - (void)_web_setPrintingModeRecursive
1667 {
1668     [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1669 }
1670
1671 - (void)_web_clearPrintingModeRecursive
1672 {
1673     [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1674 }
1675
1676 - (void)_web_layoutIfNeededRecursive
1677 {
1678     [_subviews makeObjectsPerformSelector:@selector(_web_layoutIfNeededRecursive)];
1679 }
1680
1681 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1682 {
1683     unsigned index, count;
1684     for (index = 0, count = [_subviews count]; index < count; index++) {
1685         NSView *subview = [_subviews objectAtIndex:index];
1686         NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1687         [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1688     }
1689 }
1690
1691 @end
1692
1693 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1694
1695 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1696 {
1697     if (object == nil) {
1698         [self removeObjectForKey:key];
1699     } else {
1700         [self setObject:object forKey:key];
1701     }
1702 }
1703
1704 @end
1705
1706 // The following is a workaround for
1707 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1708 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1709 // Since the category will be searched before the real class, we'll prevent the flag from being
1710 // set on the tool tip panel.
1711
1712 @interface NSToolTipPanel : NSPanel
1713 @end
1714
1715 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1716 @end
1717
1718 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1719
1720 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1721 {
1722     // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1723 }
1724
1725 @end
1726
1727
1728 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
1729 @end
1730
1731 @interface NSArray (WebHTMLView)
1732 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1733 @end
1734
1735 @implementation WebHTMLView
1736
1737 + (void)initialize
1738 {
1739     [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes] 
1740                              returnTypes:[[self class] _insertablePasteboardTypes]];
1741     _NSInitializeKillRing();
1742 }
1743
1744 - (void)_resetCachedWebPreferences:(NSNotification *)ignored
1745 {
1746     WebPreferences *preferences = [[self _webView] preferences];
1747     // Check for nil because we might not yet have an associated webView when this is called
1748     if (preferences == nil) {
1749         preferences = [WebPreferences standardPreferences];
1750     }
1751     _private->showsURLsInToolTips = [preferences showsURLsInToolTips];
1752 }
1753
1754 - (id)initWithFrame:(NSRect)frame
1755 {
1756     [super initWithFrame:frame];
1757     
1758     // Make all drawing go through us instead of subviews.
1759     if (NSAppKitVersionNumber >= 711) {
1760         [self _setDrawsOwnDescendants:YES];
1761     }
1762     
1763     _private = [[WebHTMLViewPrivate alloc] init];
1764
1765     _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1766     _private->needsLayout = YES;
1767     [self _resetCachedWebPreferences:nil];
1768     [[NSNotificationCenter defaultCenter] 
1769             addObserver:self selector:@selector(_resetCachedWebPreferences:) 
1770                    name:WebPreferencesChangedNotification object:nil];
1771     
1772     return self;
1773 }
1774
1775 - (void)dealloc
1776 {
1777     [self _clearLastHitViewIfSelf];
1778     [self _reset];
1779     [[NSNotificationCenter defaultCenter] removeObserver:self];
1780     [_private->pluginController destroyAllPlugins];
1781     [_private release];
1782     _private = nil;
1783     [super dealloc];
1784 }
1785
1786 - (void)finalize
1787 {
1788     [self _clearLastHitViewIfSelf];
1789     [self _reset];
1790     [[NSNotificationCenter defaultCenter] removeObserver:self];
1791     [_private->pluginController destroyAllPlugins];
1792     _private = nil;
1793     [super finalize];
1794 }
1795
1796 - (IBAction)takeFindStringFromSelection:(id)sender
1797 {
1798     if (![self _hasSelection]) {
1799         NSBeep();
1800         return;
1801     }
1802
1803     [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1804 }
1805
1806 - (NSArray *)pasteboardTypesForSelection
1807 {
1808     if ([self _canSmartCopyOrDelete]) {
1809         NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1810         [types addObject:WebSmartPastePboardType];
1811         return types;
1812     } else {
1813         return [[self class] _selectionPasteboardTypes];
1814     }
1815 }
1816
1817 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1818 {
1819     [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:nil];
1820 }
1821
1822 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1823 {
1824     [pasteboard declareTypes:types owner:nil];
1825     [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
1826     return YES;
1827 }
1828
1829 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
1830 {
1831     [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
1832     return YES;
1833 }
1834
1835 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1836 {
1837     if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
1838         return self;
1839     } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
1840         return self;
1841     }
1842     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
1843 }
1844
1845 - (void)selectAll:(id)sender
1846 {
1847     [self selectAll];
1848 }
1849
1850 - (void)jumpToSelection:(id)sender
1851 {
1852     [[self _bridge] jumpToSelection];
1853 }
1854
1855 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item 
1856 {
1857     SEL action = [item action];
1858     WebBridge *bridge = [self _bridge];
1859
1860     if (action == @selector(alignCenter:)
1861             || action == @selector(alignLeft:)
1862             || action == @selector(alignJustified:)
1863             || action == @selector(alignRight:)
1864             || action == @selector(changeAttributes:)
1865             || action == @selector(changeBaseWritingDirection:) // FIXME: check menu item based on writing direction
1866             || action == @selector(changeColor:)
1867             || action == @selector(changeFont:)
1868             || action == @selector(changeSpelling:)
1869             || action == @selector(_changeSpellingFromMenu:)
1870             || action == @selector(checkSpelling:)
1871             || action == @selector(complete:)
1872             || action == @selector(deleteBackward:)
1873             || action == @selector(deleteBackwardByDecomposingPreviousCharacter:)
1874             || action == @selector(deleteForward:)
1875             || action == @selector(deleteToBeginningOfLine:)
1876             || action == @selector(deleteToBeginningOfParagraph:)
1877             || action == @selector(deleteToEndOfLine:)
1878             || action == @selector(deleteToEndOfParagraph:)
1879             || action == @selector(deleteToMark:)
1880             || action == @selector(deleteWordBackward:)
1881             || action == @selector(deleteWordForward:)
1882             || action == @selector(insertBacktab:)
1883             || action == @selector(insertLineBreak:)
1884             || action == @selector(insertNewline:)
1885             || action == @selector(insertNewlineIgnoringFieldEditor:)
1886             || action == @selector(insertParagraphSeparator:)
1887             || action == @selector(insertTab:)
1888             || action == @selector(insertTabIgnoringFieldEditor:)
1889             || action == @selector(moveBackward:)
1890             || action == @selector(moveBackwardAndModifySelection:)
1891             || action == @selector(moveDown:)
1892             || action == @selector(moveDownAndModifySelection:)
1893             || action == @selector(moveForward:)
1894             || action == @selector(moveForwardAndModifySelection:)
1895             || action == @selector(moveLeft:)
1896             || action == @selector(moveLeftAndModifySelection:)
1897             || action == @selector(moveParagraphBackwardAndModifySelection:)
1898             || action == @selector(moveParagraphForwardAndModifySelection:)
1899             || action == @selector(moveRight:)
1900             || action == @selector(moveRightAndModifySelection:)
1901             || action == @selector(moveToBeginningOfDocument:)
1902             || action == @selector(moveToBeginningOfDocumentAndModifySelection:)
1903             || action == @selector(moveToBeginningOfLine:)
1904             || action == @selector(moveToBeginningOfLineAndModifySelection:)
1905             || action == @selector(moveToBeginningOfParagraph:)
1906             || action == @selector(moveToBeginningOfParagraphAndModifySelection:)
1907             || action == @selector(moveToEndOfDocument:)
1908             || action == @selector(moveToEndOfDocumentAndModifySelection:)
1909             || action == @selector(moveToEndOfLine:)
1910             || action == @selector(moveToEndOfLineAndModifySelection:)
1911             || action == @selector(moveToEndOfParagraph:)
1912             || action == @selector(moveToEndOfParagraphAndModifySelection:)
1913             || action == @selector(moveUp:)
1914             || action == @selector(moveUpAndModifySelection:)
1915             || action == @selector(moveWordBackward:)
1916             || action == @selector(moveWordBackwardAndModifySelection:)
1917             || action == @selector(moveWordForward:)
1918             || action == @selector(moveWordForwardAndModifySelection:)
1919             || action == @selector(moveWordLeft:)
1920             || action == @selector(moveWordLeftAndModifySelection:)
1921             || action == @selector(moveWordRight:)
1922             || action == @selector(moveWordRightAndModifySelection:)
1923             || action == @selector(pageDown:)
1924             || action == @selector(pageDownAndModifySelection:)
1925             || action == @selector(pageUp:)
1926             || action == @selector(pageUpAndModifySelection:)
1927             || action == @selector(pasteFont:)
1928             || action == @selector(showGuessPanel:)
1929             || action == @selector(toggleBaseWritingDirection:)
1930             || action == @selector(transpose:)
1931             || action == @selector(yank:)
1932             || action == @selector(yankAndSelect:)) {
1933         return [self _canEdit];
1934     } else if (action == @selector(capitalizeWord:)
1935                || action == @selector(lowercaseWord:)
1936                || action == @selector(uppercaseWord:)) {
1937         return [self _hasSelection] && [self _isEditable];
1938     } else if (action == @selector(centerSelectionInVisibleArea:)
1939             || action == @selector(copyFont:)
1940             || action == @selector(setMark:)) {
1941         return [self _hasSelectionOrInsertionPoint];
1942     } else if (action == @selector(changeDocumentBackgroundColor:)) {
1943         return [[self _webView] isEditable];
1944     } else if (action == @selector(copy:)) {
1945         return [bridge mayDHTMLCopy] || [self _canCopy];
1946     } else if (action == @selector(cut:)) {
1947         return [bridge mayDHTMLCut] || [self _canDelete];
1948     } else if (action == @selector(delete:)) {
1949         return [self _canDelete];
1950     } else if (action == @selector(_ignoreSpellingFromMenu:)
1951             || action == @selector(jumpToSelection:)
1952             || action == @selector(_learnSpellingFromMenu:)
1953             || action == @selector(takeFindStringFromSelection:)) {
1954         return [self _hasSelection];
1955     } else if (action == @selector(paste:) || action == @selector(pasteAsPlainText:) || action == @selector(pasteAsRichText:)) {
1956         return [bridge mayDHTMLPaste] || [self _canPaste];
1957     } else if (action == @selector(performFindPanelAction:)) {
1958         // FIXME: Not yet implemented.
1959         return NO;
1960     } else if (action == @selector(selectToMark:)
1961             || action == @selector(swapWithMark:)) {
1962         return [self _hasSelectionOrInsertionPoint] && [[self _bridge] markDOMRange] != nil;
1963     } else if (action == @selector(subscript:)) {
1964         NSMenuItem *menuItem = (NSMenuItem *)item;
1965         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1966             DOMCSSStyleDeclaration *style = [self _emptyStyle];
1967             [style setVerticalAlign:@"sub"];
1968             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1969         }
1970         return [self _canEdit];
1971     } else if (action == @selector(superscript:)) {
1972         NSMenuItem *menuItem = (NSMenuItem *)item;
1973         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1974             DOMCSSStyleDeclaration *style = [self _emptyStyle];
1975             [style setVerticalAlign:@"super"];
1976             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1977         }
1978         return [self _canEdit];
1979     } else if (action == @selector(underline:)) {
1980         NSMenuItem *menuItem = (NSMenuItem *)item;
1981         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1982             DOMCSSStyleDeclaration *style = [self _emptyStyle];
1983             [style setProperty:@"-khtml-text-decorations-in-effect" :@"underline" :@""];
1984             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1985         }
1986         return [self _canEdit];
1987     } else if (action == @selector(unscript:)) {
1988         NSMenuItem *menuItem = (NSMenuItem *)item;
1989         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1990             DOMCSSStyleDeclaration *style = [self _emptyStyle];
1991             [style setVerticalAlign:@"baseline"];
1992             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1993         }
1994         return [self _canEdit];
1995 #ifndef OMIT_TIGER_FEATURES
1996     } else if (action == @selector(_searchWithSpotlightFromMenu:)
1997                || action == @selector(_searchWithGoogleFromMenu:)
1998                || action == @selector(_lookUpInDictionaryFromMenu:)) {
1999         return [self _hasSelection];
2000 #endif
2001     }
2002     
2003     return YES;
2004 }
2005
2006 - (BOOL)acceptsFirstResponder
2007 {
2008     // Don't accept first responder when we first click on this view.
2009     // We have to pass the event down through WebCore first to be sure we don't hit a subview.
2010     // Do accept first responder at any other time, for example from keyboard events,
2011     // or from calls back from WebCore once we begin mouse-down event handling.
2012     NSEvent *event = [NSApp currentEvent];
2013     if ([event type] == NSLeftMouseDown
2014             && !_private->handlingMouseDownEvent
2015             && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
2016         return NO;
2017     }
2018     return YES;
2019 }
2020
2021 - (BOOL)maintainsInactiveSelection
2022 {
2023     // This method helps to determing whether the view should maintain
2024     // an inactive selection when the view is not first responder.
2025     // Traditionally, these views have not maintained such selections,
2026     // clearing them when the view was not first responder. However,
2027     // to fix bugs like this one:
2028     // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even 
2029     //                            when they're not firstResponder"
2030     // it was decided to add a switch to act more like an NSTextView.
2031     // For now, however, the view only acts in this way when the
2032     // web view is set to be editable. This will maintain traditional
2033     // behavior for WebKit clients dating back to before this change,
2034     // and will likely be a decent switch for the long term, since
2035     // clients to ste the web view to be editable probably want it
2036     // to act like a "regular" Cocoa view in terms of its selection
2037     // behavior.
2038     id nextResponder = [[self window] _newFirstResponderAfterResigning];
2039
2040     // Predict the case where we are losing first responder status only to
2041     // gain it back again.  Want to keep the selection in that case.
2042     if ([nextResponder isKindOfClass:[NSScrollView class]]) {
2043         id contentView = [nextResponder contentView];
2044         if (contentView) {
2045             nextResponder = contentView;
2046         }
2047     }
2048     if ([nextResponder isKindOfClass:[NSClipView class]]) {
2049         id documentView = [nextResponder documentView];
2050         if (documentView) {
2051             nextResponder = documentView;
2052         }
2053     }
2054
2055     if (nextResponder == self)
2056         return YES;
2057
2058     if (![[self _webView] maintainsInactiveSelection])
2059         return NO;
2060     
2061     // editable views lose selection when losing first responder status
2062     // to a widget in the same page, but not otherwise
2063     BOOL loseSelection = [nextResponder isKindOfClass:[NSView class]]
2064         && [nextResponder isDescendantOf:[self _webView]];
2065
2066     return !loseSelection;
2067 }
2068
2069 - (void)addMouseMovedObserver
2070 {
2071     // Always add a mouse move observer if the DB requested, or if we're the key window.
2072     if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
2073         [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
2074         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
2075             name:NSMouseMovedNotification object:nil];
2076         [self _frameOrBoundsChanged];
2077     }
2078 }
2079
2080 - (void)removeMouseMovedObserver
2081 {
2082     // Don't remove the observer if we're running the DB
2083     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
2084         return;
2085         
2086     [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
2087     [[NSNotificationCenter defaultCenter] removeObserver:self
2088         name:NSMouseMovedNotification object:nil];
2089 }
2090
2091 - (void)updateFocusState
2092 {
2093     // This method does the job of updating the view based on the view's firstResponder-ness and
2094     // the window key-ness of the window containing this view. This involves three kinds of 
2095     // drawing updates right now, all handled in WebCore in response to the call over the bridge. 
2096     // 
2097     // The three display attributes are as follows:
2098     // 
2099     // 1. The background color used to draw behind selected content (active | inactive color)
2100     // 2. Caret blinking (blinks | does not blink)
2101     // 3. The drawing of a focus ring around links in web pages.
2102     //
2103     // Also, this is responsible for letting the bridge know if the window has gained or lost focus
2104     // so we can send focus and blur events.
2105
2106     WebBridge *bridge = [self _bridge];
2107     BOOL windowIsKey = [[self window] isKeyWindow];
2108
2109     BOOL flag = !_private->resigningFirstResponder && windowIsKey && [self _web_firstResponderCausesFocusDisplay];
2110     [bridge setDisplaysWithFocusAttributes:flag];
2111
2112     [bridge setWindowHasFocus:windowIsKey];
2113 }
2114
2115 - (void)addSuperviewObservers
2116 {
2117     // We watch the bounds of our superview, so that we can do a layout when the size
2118     // of the superview changes. This is different from other scrollable things that don't
2119     // need this kind of thing because their layout doesn't change.
2120     
2121     // We need to pay attention to both height and width because our "layout" has to change
2122     // to extend the background the full height of the space and because some elements have
2123     // sizes that are based on the total size of the view.
2124     
2125     NSView *superview = [self superview];
2126     if (superview && [self window]) {
2127         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
2128             name:NSViewFrameDidChangeNotification object:superview];
2129         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
2130             name:NSViewBoundsDidChangeNotification object:superview];
2131     }
2132 }
2133
2134 - (void)removeSuperviewObservers
2135 {
2136     NSView *superview = [self superview];
2137     if (superview && [self window]) {
2138         [[NSNotificationCenter defaultCenter] removeObserver:self
2139             name:NSViewFrameDidChangeNotification object:superview];
2140         [[NSNotificationCenter defaultCenter] removeObserver:self
2141             name:NSViewBoundsDidChangeNotification object:superview];
2142     }
2143 }
2144
2145 - (void)addWindowObservers
2146 {
2147     NSWindow *window = [self window];
2148     if (window) {
2149         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
2150             name:NSWindowDidBecomeKeyNotification object:window];
2151         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
2152             name:NSWindowDidResignKeyNotification object:window];
2153         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
2154             name:NSWindowWillCloseNotification object:window];
2155     }
2156 }
2157
2158 - (void)removeWindowObservers
2159 {
2160     NSWindow *window = [self window];
2161     if (window) {
2162         [[NSNotificationCenter defaultCenter] removeObserver:self
2163             name:NSWindowDidBecomeKeyNotification object:window];
2164         [[NSNotificationCenter defaultCenter] removeObserver:self
2165             name:NSWindowDidResignKeyNotification object:window];
2166         [[NSNotificationCenter defaultCenter] removeObserver:self
2167             name:NSWindowWillCloseNotification object:window];
2168     }
2169 }
2170
2171 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
2172 {
2173     [self removeSuperviewObservers];
2174 }
2175
2176 - (void)viewDidMoveToSuperview
2177 {
2178     // Do this here in case the text size multiplier changed when a non-HTML
2179     // view was installed.
2180     if ([self superview] != nil) {
2181         [self _updateTextSizeMultiplier];
2182         [self addSuperviewObservers];
2183     }
2184 }
2185
2186 - (void)viewWillMoveToWindow:(NSWindow *)window
2187 {
2188     // Don't do anything if we aren't initialized.  This happens
2189     // when decoding a WebView.  When WebViews are decoded their subviews
2190     // are created by initWithCoder: and so won't be normally
2191     // initialized.  The stub views are discarded by WebView.
2192     if (_private){
2193         // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
2194         [self removeMouseMovedObserver];
2195         [self removeWindowObservers];
2196         [self removeSuperviewObservers];
2197         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2198     
2199         [[self _pluginController] stopAllPlugins];
2200     }
2201 }
2202
2203 - (void)viewDidMoveToWindow
2204 {
2205     // Don't do anything if we aren't initialized.  This happens
2206     // when decoding a WebView.  When WebViews are decoded their subviews
2207     // are created by initWithCoder: and so won't be normally
2208     // initialized.  The stub views are discarded by WebView.
2209     if (_private) {
2210         [self _stopAutoscrollTimer];
2211         if ([self window]) {
2212             _private->lastScrollPosition = [[self superview] bounds].origin;
2213             [self addWindowObservers];
2214             [self addSuperviewObservers];
2215             [self addMouseMovedObserver];
2216
2217             // Schedule this update, rather than making the call right now.
2218             // The reason is that placing the caret in the just-installed view requires
2219             // the HTML/XML document to be available on the WebCore side, but it is not
2220             // at the time this code is running. However, it will be there on the next
2221             // crank of the run loop. Doing this helps to make a blinking caret appear 
2222             // in a new, empty window "automatic".
2223             [self performSelector:@selector(updateFocusState) withObject:nil afterDelay:0];
2224
2225             [[self _pluginController] startAllPlugins];
2226     
2227             _private->lastScrollPosition = NSZeroPoint;
2228             
2229             _private->inWindow = YES;
2230         } else {
2231             // Reset when we are moved out of a window after being moved into one.
2232             // Without this check, we reset ourselves before we even start.
2233             // This is only needed because viewDidMoveToWindow is called even when
2234             // the window is not changing (bug in AppKit).
2235             if (_private->inWindow) {
2236                 [self _reset];
2237                 _private->inWindow = NO;
2238             }
2239         }
2240     }
2241 }
2242
2243 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
2244 {
2245     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
2246 }
2247
2248 - (void)viewDidMoveToHostWindow
2249 {
2250     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
2251 }
2252
2253
2254 - (void)addSubview:(NSView *)view
2255 {
2256     [super addSubview:view];
2257
2258     if ([WebPluginController isPlugInView:view]) {
2259         [[self _pluginController] addPlugin:view];
2260     }
2261 }
2262
2263 - (void)reapplyStyles
2264 {
2265     if (!_private->needsToApplyStyles) {
2266         return;
2267     }
2268     
2269 #ifdef _KWQ_TIMING        
2270     double start = CFAbsoluteTimeGetCurrent();
2271 #endif
2272
2273     [[self _bridge] reapplyStylesForDeviceType:
2274         _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
2275     
2276 #ifdef _KWQ_TIMING        
2277     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2278     LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
2279 #endif
2280
2281     _private->needsToApplyStyles = NO;
2282 }
2283
2284 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
2285 // minPageWidth==0 implies a non-printing layout
2286 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
2287 {
2288     [self reapplyStyles];
2289     
2290     // Ensure that we will receive mouse move events.  Is this the best place to put this?
2291     [[self window] setAcceptsMouseMovedEvents: YES];
2292     [[self window] _setShouldPostEventNotifications: YES];
2293
2294     if (!_private->needsLayout) {
2295         return;
2296     }
2297
2298 #ifdef _KWQ_TIMING        
2299     double start = CFAbsoluteTimeGetCurrent();
2300 #endif
2301
2302     LOG(View, "%@ doing layout", self);
2303
2304     if (minPageWidth > 0.0) {
2305         [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2306     } else {
2307         [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
2308     }
2309     _private->needsLayout = NO;
2310     
2311     if (!_private->printing) {
2312         // get size of the containing dynamic scrollview, so
2313         // appearance and disappearance of scrollbars will not show up
2314         // as a size change
2315         NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
2316         if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
2317             [[self _bridge] sendResizeEvent];
2318         }
2319         _private->laidOutAtLeastOnce = YES;
2320         _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
2321         _private->lastLayoutFrameSize = newLayoutFrameSize;
2322     }
2323
2324 #ifdef _KWQ_TIMING        
2325     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2326     LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
2327 #endif
2328 }
2329
2330 - (void)layout
2331 {
2332     [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
2333 }
2334
2335 - (NSMenu *)menuForEvent:(NSEvent *)event
2336 {
2337     [_private->compController endRevertingChange:NO moveLeft:NO];
2338
2339     if ([[self _bridge] sendContextMenuEvent:event]) {
2340         return nil;
2341     }
2342     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2343     NSDictionary *element = [self elementAtPoint:point];
2344     return [[self _webView] _menuForElement:element];
2345 }
2346
2347 // Search from the end of the currently selected location, or from the beginning of the
2348 // document if nothing is selected.
2349 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2350 {
2351     return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag findInSelection:NO];
2352 }
2353
2354 // Private method that adds a findInSelection parameter; might be public someday
2355 // FIXME: this is currently discovered using respondsToSelector; no SPI or API yet
2356 // FIXME: this needs to be done for other WebDocumentSearching implementors also, such as
2357 // WebPDFView and WebSearchableTextView
2358 - (BOOL)_searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag findInSelection:(BOOL)inSelectionFlag
2359 {
2360     return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag findInSelection:inSelectionFlag];
2361 }
2362
2363 - (DOMRange *)_documentRange
2364 {
2365     return [[[self _bridge] DOMDocument] _documentRange];
2366 }
2367
2368 - (NSString *)string
2369 {
2370     return [[self _bridge] stringForRange:[self _documentRange]];
2371 }
2372
2373 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
2374 {
2375     NSAttributedString *attributedString = nil;
2376 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
2377 #if !LOG_DISABLED        
2378     double start = CFAbsoluteTimeGetCurrent();
2379 #endif    
2380     attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
2381 #if !LOG_DISABLED
2382     double duration = CFAbsoluteTimeGetCurrent() - start;
2383     LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
2384 #endif
2385 #endif
2386     return attributedString;
2387 }
2388
2389 - (NSAttributedString *)attributedString
2390 {
2391     WebBridge *bridge = [self _bridge];
2392     DOMDocument *document = [bridge DOMDocument];
2393     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
2394     if (attributedString == nil) {
2395         attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
2396     }
2397     return attributedString;
2398 }
2399
2400 - (NSString *)selectedString
2401 {
2402     return [[self _bridge] selectedString];
2403 }
2404
2405 - (NSAttributedString *)selectedAttributedString
2406 {
2407     WebBridge *bridge = [self _bridge];
2408     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
2409     if (attributedString == nil) {
2410         attributedString = [bridge selectedAttributedString];
2411     }
2412     return attributedString;
2413 }
2414
2415 - (void)selectAll
2416 {
2417     [[self _bridge] selectAll];
2418 }
2419
2420 // Remove the selection.
2421 - (void)deselectAll
2422 {
2423     [[self _bridge] deselectAll];
2424 }
2425
2426 - (void)deselectText
2427 {
2428     [[self _bridge] deselectText];
2429 }
2430
2431 - (BOOL)isOpaque
2432 {
2433     return [[self _webView] drawsBackground];
2434 }
2435
2436 - (void)setNeedsDisplay:(BOOL)flag
2437 {
2438     LOG(View, "%@ flag = %d", self, (int)flag);
2439     [super setNeedsDisplay: flag];
2440 }
2441
2442 - (void)setNeedsLayout: (BOOL)flag
2443 {
2444     LOG(View, "%@ flag = %d", self, (int)flag);
2445     _private->needsLayout = flag;
2446 }
2447
2448
2449 - (void)setNeedsToApplyStyles: (BOOL)flag
2450 {
2451     LOG(View, "%@ flag = %d", self, (int)flag);
2452     _private->needsToApplyStyles = flag;
2453 }
2454
2455 - (void)drawRect:(NSRect)rect
2456 {
2457     LOG(View, "%@ drawing", self);
2458
2459     // Work around AppKit bug <rdar://problem/3875305> rect passed to drawRect: is too large.
2460     // Ignore the passed-in rect and instead union in the rectangles from getRectsBeingDrawn.
2461     // This does a better job of clipping out rects that are entirely outside the visible area.
2462     const NSRect *rects;
2463     int count;
2464     [self getRectsBeingDrawn:&rects count:&count];
2465
2466     // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2467     // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2468     // The reason for the workaround is that this method is called explicitly from the code
2469     // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2470     if (count > 0) {
2471         rect = NSZeroRect;
2472         int i;
2473         for (i = 0; i < count; ++i) {
2474             rect = NSUnionRect(rect, rects[i]);
2475         }
2476         if (rect.size.height == 0 || rect.size.width == 0) {
2477             return;
2478         }
2479     }
2480
2481     BOOL subviewsWereSetAside = _private->subviewsSetAside;
2482     if (subviewsWereSetAside) {
2483         [self _restoreSubviews];
2484     }
2485
2486 #ifdef _KWQ_TIMING
2487     double start = CFAbsoluteTimeGetCurrent();
2488 #endif
2489
2490     [NSGraphicsContext saveGraphicsState];
2491     NSRectClip(rect);
2492         
2493     ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2494
2495     [(WebClipView *)[self superview] setAdditionalClip:rect];
2496
2497     NS_DURING {
2498         WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
2499         if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
2500             textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
2501             [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
2502         }
2503
2504         if ([self _transparentBackground]) {
2505             [[NSColor clearColor] set];
2506             NSRectFill (rect);
2507         }
2508         
2509         //double start = CFAbsoluteTimeGetCurrent();
2510         [[self _bridge] drawRect:rect];
2511         //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
2512
2513         if (textRendererFactoryIfCoalescing != nil) {
2514             [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
2515         }
2516
2517         [(WebClipView *)[self superview] resetAdditionalClip];
2518
2519         [NSGraphicsContext restoreGraphicsState];
2520     } NS_HANDLER {
2521         [(WebClipView *)[self superview] resetAdditionalClip];
2522         [NSGraphicsContext restoreGraphicsState];
2523         ERROR("Exception caught while drawing: %@", localException);
2524         [localException raise];
2525     } NS_ENDHANDLER
2526
2527 #ifdef DEBUG_LAYOUT
2528     NSRect vframe = [self frame];
2529     [[NSColor blackColor] set];
2530     NSBezierPath *path;
2531     path = [NSBezierPath bezierPath];
2532     [path setLineWidth:(float)0.1];
2533     [path moveToPoint:NSMakePoint(0, 0)];
2534     [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2535     [path closePath];
2536     [path stroke];
2537     path = [NSBezierPath bezierPath];
2538     [path setLineWidth:(float)0.1];
2539     [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2540     [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2541     [path closePath];
2542     [path stroke];
2543 #endif
2544
2545 #ifdef _KWQ_TIMING
2546     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2547     LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2548 #endif
2549
2550     if (subviewsWereSetAside) {
2551         [self _setAsideSubviews];
2552     }
2553 }
2554
2555 // Turn off the additional clip while computing our visibleRect.
2556 - (NSRect)visibleRect
2557 {
2558     if (!([[self superview] isKindOfClass:[WebClipView class]]))
2559         return [super visibleRect];
2560         
2561     WebClipView *clipView = (WebClipView *)[self superview];
2562
2563     BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2564     if (!hasAdditionalClip) {
2565         return [super visibleRect];
2566     }
2567     
2568     NSRect additionalClip = [clipView additionalClip];
2569     [clipView resetAdditionalClip];
2570     NSRect visibleRect = [super visibleRect];
2571     [clipView setAdditionalClip:additionalClip];
2572     return visibleRect;
2573 }
2574
2575 - (BOOL)isFlipped 
2576 {
2577     return YES;
2578 }
2579
2580 - (void)windowDidBecomeKey:(NSNotification *)notification
2581 {
2582     ASSERT([notification object] == [self window]);
2583     [self addMouseMovedObserver];
2584     [self updateFocusState];
2585 }
2586
2587 - (void)windowDidResignKey: (NSNotification *)notification
2588 {
2589     ASSERT([notification object] == [self window]);
2590     [_private->compController endRevertingChange:NO moveLeft:NO];
2591     [self removeMouseMovedObserver];
2592     [self updateFocusState];
2593 }
2594
2595 - (void)windowWillClose:(NSNotification *)notification
2596 {
2597     [_private->compController endRevertingChange:NO moveLeft:NO];
2598     [[self _pluginController] destroyAllPlugins];
2599 }
2600
2601 - (void)scrollWheel:(NSEvent *)event
2602 {
2603     [self retain];
2604     
2605     if (![[self _bridge] sendScrollWheelEvent:event]) {
2606         [[self nextResponder] scrollWheel:event];
2607     }    
2608     
2609     [self release];
2610 }
2611
2612 - (BOOL)_isSelectionEvent:(NSEvent *)event
2613 {
2614     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2615     return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2616 }
2617
2618 - (void)_setMouseDownEvent:(NSEvent *)event
2619 {
2620     ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2621
2622     if (event == _private->mouseDownEvent) {
2623         return;
2624     }
2625
2626     [event retain];
2627     [_private->mouseDownEvent release];
2628     _private->mouseDownEvent = event;
2629
2630     [_private->firstResponderAtMouseDownTime release];
2631     _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2632 }
2633
2634 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2635 {
2636     NSView *hitView = [self _hitViewForEvent:event];
2637     WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2638     [hitHTMLView _setMouseDownEvent:event];
2639     
2640     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2641         return YES;
2642     
2643     if (hitHTMLView != nil) {
2644         [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2645         return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2646     } else {
2647         return [hitView acceptsFirstMouse:event];
2648     }
2649 }
2650
2651 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2652 {
2653     NSView *hitView = [self _hitViewForEvent:event];
2654     WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2655     if (hitHTMLView != nil) {
2656         [hitHTMLView _setMouseDownEvent:event];
2657         return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2658     } else {
2659         return [hitView shouldDelayWindowOrderingForEvent:event];
2660     }
2661 }
2662
2663 - (void)mouseDown:(NSEvent *)event
2664 {
2665     [self retain];
2666
2667     _private->handlingMouseDownEvent = YES;
2668
2669     // Record the mouse down position so we can determine drag hysteresis.
2670     [self _setMouseDownEvent:event];
2671
2672     // TEXTINPUT: if there is marked text and the current input
2673     // manager wants to handle mouse events, we need to make sure to
2674     // pass it to them. If not, then we need to notify the input
2675     // manager when the marked text is abandoned (user clicks outside
2676     // the marked area)
2677
2678     [_private->compController endRevertingChange:NO moveLeft:NO];
2679
2680     // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2681     // We don't want to pass them along to KHTML a second time.
2682     if (!([event modifierFlags] & NSControlKeyMask)) {
2683         _private->ignoringMouseDraggedEvents = NO;
2684
2685         // Don't do any mouseover while the mouse is down.
2686         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2687
2688         // Let KHTML get a chance to deal with the event. This will call back to us
2689         // to start the autoscroll timer if appropriate.
2690         [[self _bridge] mouseDown:event];
2691     }
2692
2693     [_private->firstResponderAtMouseDownTime release];
2694     _private->firstResponderAtMouseDownTime = nil;
2695
2696     _private->handlingMouseDownEvent = NO;
2697     
2698     [self release];
2699 }
2700
2701 - (void)dragImage:(NSImage *)dragImage
2702                at:(NSPoint)at
2703            offset:(NSSize)offset
2704             event:(NSEvent *)event
2705        pasteboard:(NSPasteboard *)pasteboard
2706            source:(id)source
2707         slideBack:(BOOL)slideBack
2708 {   
2709     [self _stopAutoscrollTimer];
2710     
2711     _private->initiatedDrag = YES;
2712     [[self _webView] _setInitiatedDrag:YES];
2713     
2714     // Retain this view during the drag because it may be released before the drag ends.
2715     [self retain];
2716
2717     [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2718 }
2719
2720 - (void)mouseDragged:(NSEvent *)event
2721 {
2722     [self retain];
2723     
2724     // TEXTINPUT: if there is marked text and the current input
2725     // manager wants to handle mouse events, we need to make sure to
2726     // pass it to them.
2727
2728     if (!_private->ignoringMouseDraggedEvents) {
2729         [[self _bridge] mouseDragged:event];
2730     }
2731     
2732     [self release];
2733 }
2734
2735 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2736 {
2737     if (_private->webCoreDragOp == NSDragOperationNone) {
2738         return (NSDragOperationGeneric | NSDragOperationCopy);
2739     } else {
2740         return _private->webCoreDragOp;
2741     }
2742 }
2743
2744 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2745 {
2746     NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2747     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2748     [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2749 }
2750
2751 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2752 {
2753     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2754     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2755     [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2756
2757     _private->initiatedDrag = NO;
2758     [[self _webView] _setInitiatedDrag:NO];
2759     
2760     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2761     _private->ignoringMouseDraggedEvents = YES;
2762     
2763     // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2764     // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2765     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2766                                             location:windowMouseLoc
2767                                        modifierFlags:[[NSApp currentEvent] modifierFlags]
2768                                            timestamp:[NSDate timeIntervalSinceReferenceDate]
2769                                         windowNumber:[[self window] windowNumber]
2770                                              context:[[NSApp currentEvent] context]
2771                                          eventNumber:0 clickCount:0 pressure:0];
2772     [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2773     
2774     // Balance the previous retain from when the drag started.
2775     [self release];
2776 }
2777
2778 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2779 {
2780     ASSERT(_private->draggingImageURL);
2781     
2782     NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2783     ASSERT(wrapper);    
2784     
2785     // FIXME: Report an error if we fail to create a file.
2786     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2787     path = [[NSFileManager defaultManager] _webkit_pathWithUniqueFilenameForPath:path];
2788     if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2789         ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2790     }
2791     
2792     return [NSArray arrayWithObject:[path lastPathComponent]];
2793 }
2794
2795 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2796 {
2797     NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2798     NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2799     [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2800     if ([types count] == 0) {
2801         return NO;
2802     } else if ([types count] == 1 && 
2803                [types containsObject:NSFilenamesPboardType] && 
2804                ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2805         return NO;
2806     }
2807     
2808     NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2809     NSDictionary *element = [self elementAtPoint:point];
2810     if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2811         if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2812             // Can't drag onto the selection being dragged.
2813             return NO;
2814         }
2815         return YES;
2816     }
2817     
2818     return NO;
2819 }
2820
2821 - (BOOL)_isMoveDrag
2822 {
2823     return _private->initiatedDrag && 
2824     ([self _isEditable] && [self _hasSelection]) &&
2825     ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2826 }
2827
2828 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2829 {
2830     return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2831 }
2832
2833 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2834 {
2835     NSDragOperation operation = NSDragOperationNone;
2836     
2837     if (actionMask & WebDragDestinationActionDHTML) {
2838         operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2839     }
2840     _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2841     
2842     if ((actionMask & WebDragDestinationActionEdit) &&
2843         !_private->webCoreHandlingDrag
2844         && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2845         if ([self _isNSColorDrag:draggingInfo]) {
2846             operation = NSDragOperationGeneric;
2847         }
2848         else {
2849             WebView *webView = [self _webView];
2850             [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2851             operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2852         }
2853     } else {
2854         [[self _webView] removeDragCaret];
2855     }
2856     
2857     return operation;
2858 }
2859
2860 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2861 {
2862     [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2863     [[self _webView] removeDragCaret];
2864 }
2865
2866 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2867 {
2868     WebView *webView = [self _webView];
2869     WebBridge *bridge = [self _bridge];
2870     if (_private->webCoreHandlingDrag) {
2871         ASSERT(actionMask & WebDragDestinationActionDHTML);
2872         [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2873         [bridge concludeDragForDraggingInfo:draggingInfo];
2874         return YES;
2875     } else if (actionMask & WebDragDestinationActionEdit) {
2876         if ([self _isNSColorDrag:draggingInfo]) {
2877             NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2878             if (!color)
2879                 return NO;
2880             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2881             [style setProperty:@"color" :[self _colorAsString:color] :@""];
2882             if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2883                 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2884                 [bridge applyStyle:style withUndoAction:WebUndoActionSetColor];
2885                 return YES;
2886             }
2887             return NO;
2888         }
2889         else {
2890             BOOL didInsert = NO;
2891             if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2892                 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2893                 BOOL chosePlainText;
2894                 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES chosePlainText:&chosePlainText];
2895                 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2896                     [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2897                     if ([self _isMoveDrag]) {
2898                         BOOL smartMove = [[self _bridge] selectionGranularity] == WebSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2899                         [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2900                     } else {
2901                         [bridge setSelectionToDragCaret];
2902                         [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard] matchStyle:chosePlainText];
2903                     }
2904                     didInsert = YES;
2905                 }
2906             }
2907             [webView removeDragCaret];
2908             return didInsert;
2909         }
2910     }
2911     return NO;
2912 }
2913
2914 - (NSDictionary *)elementAtPoint:(NSPoint)point
2915 {
2916     NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2917     NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2918     
2919     // Convert URL strings to NSURLs
2920     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2921     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2922     
2923     WebFrameView *webFrameView = [self _web_parentWebFrameView];
2924     ASSERT(webFrameView);
2925     WebFrame *webFrame = [webFrameView webFrame];
2926     
2927     if (webFrame) {
2928         NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2929         if ([frameName length] == 0) {
2930             [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2931         } else {
2932             WebFrame *wf = [webFrame findFrameNamed:frameName];
2933             if (wf != nil)
2934                 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2935             else
2936                 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2937         }
2938         
2939         [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2940     }
2941     
2942     return [elementInfo autorelease];
2943 }
2944
2945 - (void)mouseUp:(NSEvent *)event
2946 {
2947     // TEXTINPUT: if there is marked text and the current input
2948     // manager wants to handle mouse events, we need to make sure to
2949     // pass it to them.
2950
2951     [self retain];
2952     
2953     [self _stopAutoscrollTimer];
2954     [[self _bridge] mouseUp:event];
2955     [self _updateMouseoverWithFakeEvent];
2956
2957     [self release];
2958 }
2959
2960 - (void)mouseMovedNotification:(NSNotification *)notification
2961 {
2962     [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2963 }
2964
2965 - (BOOL)supportsTextEncoding
2966 {
2967     return YES;
2968 }
2969
2970 - (NSView *)nextValidKeyView
2971 {
2972     NSView *view = nil;
2973     BOOL lookInsideWebFrameViews = YES;
2974     if ([self isHiddenOrHasHiddenAncestor]) {
2975         lookInsideWebFrameViews = NO;
2976     } else if ([self _frame] == [[self _webView] mainFrame]) {
2977         // Check for case where first responder is last frame in a frameset, and we are
2978         // the top-level documentView.
2979         NSResponder *firstResponder = [[self window] firstResponder];
2980         if ((firstResponder != self) && [firstResponder isKindOfClass:[WebHTMLView class]] && ([(NSView *)firstResponder nextKeyView] == nil)) {
2981             lookInsideWebFrameViews = NO;
2982         }
2983     }
2984     
2985     if (lookInsideWebFrameViews) {
2986         view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2987     }
2988     
2989     if (view == nil) {
2990         view = [super nextValidKeyView];
2991         // If there's no next view wired up, we must be in the last subframe.
2992         // There's no direct link to the next valid key view; get it from the bridge.
2993         // Note that view == self here when nextKeyView returns nil, due to AppKit oddness.
2994         // We'll check for both nil and self in case the AppKit oddness goes away.
2995         // WebFrameView has this same kind of logic for the previousValidKeyView case.
2996         if (view == nil || view == self) {
2997             ASSERT([self _frame] != [[self _webView] mainFrame]);
2998             ASSERT(lookInsideWebFrameViews);
2999             view = [[self _bridge] nextValidKeyViewOutsideWebFrameViews];
3000         }
3001     }
3002         
3003     return view;
3004 }
3005
3006 - (NSView *)previousValidKeyView
3007 {
3008     NSView *view = nil;
3009     if (![self isHiddenOrHasHiddenAncestor]) {
3010         view = [[self _bridge] previousKeyViewInsideWebFrameViews];
3011     }
3012     if (view == nil) {
3013         view = [super previousValidKeyView];
3014     }
3015     return view;
3016 }
3017
3018 - (BOOL)becomeFirstResponder
3019 {
3020     NSView *view = nil;
3021     if (![[self _webView] _isPerformingProgrammaticFocus]) {
3022         switch ([[self window] keyViewSelectionDirection]) {
3023         case NSDirectSelection:
3024             break;
3025         case NSSelectingNext:
3026             view = [[self _bridge] nextKeyViewInsideWebFrameViews];
3027             break;
3028         case NSSelectingPrevious:
3029             view = [[self _bridge] previousKeyViewInsideWebFrameViews];
3030             break;
3031         }
3032     }
3033     if (view) {
3034         [[self window] makeFirstResponder:view];
3035     }
3036     [self updateFocusState];
3037     [self _updateFontPanel];
3038     _private->startNewKillRingSequence = YES;
3039     return YES;
3040 }
3041
3042 // This approach could be relaxed when dealing with 3228554.
3043 // Some alteration to the selection behavior was done to deal with 3672088.
3044 - (BOOL)resignFirstResponder
3045 {
3046     BOOL resign = [super resignFirstResponder];
3047     if (resign) {
3048         [_private->compController endRevertingChange:NO moveLeft:NO];
3049         _private->resigningFirstResponder = YES;
3050         if (![self maintainsInactiveSelection]) { 
3051             if ([[self _webView] _isPerformingProgrammaticFocus]) {
3052                 [self deselectText];
3053             }
3054             else {
3055                 [self deselectAll];
3056             }
3057         }
3058         [self updateFocusState];
3059         _private->resigningFirstResponder = NO;
3060     }
3061     return resign;
3062 }
3063
3064 //------------------------------------------------------------------------------------
3065 // WebDocumentView protocol
3066 //------------------------------------------------------------------------------------
3067 - (void)setDataSource:(WebDataSource *)dataSource 
3068 {
3069 }
3070
3071 - (void)dataSourceUpdated:(WebDataSource *)dataSource
3072 {
3073 }
3074
3075 // Does setNeedsDisplay:NO as a side effect when printing is ending.
3076 // pageWidth != 0 implies we will relayout to a new width
3077 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
3078 {
3079     WebFrame *frame = [self _frame];
3080     NSArray *subframes = [frame childFrames];
3081     unsigned n = [subframes count];
3082     unsigned i;
3083     for (i = 0; i != n; ++i) {
3084         WebFrame *subframe = [subframes objectAtIndex:i];
3085         WebFrameView *frameView = [subframe frameView];
3086         if ([[subframe dataSource] _isDocumentHTML]) {
3087             [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
3088         }
3089     }
3090
3091     if (printing != _private->printing) {
3092         [_private->pageRects release];
3093         _private->pageRects = nil;
3094         _private->printing = printing;
3095         [self setNeedsToApplyStyles:YES];
3096         [self setNeedsLayout:YES];
3097         [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
3098         if (!printing) {
3099             // Can't do this when starting printing or nested printing won't work, see 3491427.
3100             [self setNeedsDisplay:NO];
3101         }
3102     }
3103 }
3104
3105 - (BOOL)canPrintHeadersAndFooters
3106 {
3107     return YES;
3108 }
3109
3110 // This is needed for the case where the webview is embedded in the view that's being printed.
3111 // It shouldn't be called when the webview is being printed directly.
3112 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
3113 {
3114     // This helps when we print as part of a larger print process.
3115     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
3116     BOOL wasInPrintingMode = _private->printing;
3117     if (!wasInPrintingMode) {
3118         [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3119     }
3120     
3121     [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
3122     
3123     if (!wasInPrintingMode) {
3124         [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3125     }
3126 }
3127
3128 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
3129 {
3130     NSPrintInfo *printInfo = [printOperation printInfo];
3131     return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
3132 }
3133
3134 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
3135 {
3136     float viewWidth = NSWidth([self bounds]);
3137     if (viewWidth < 1) {
3138         ERROR("%@ has no width when printing", self);
3139         return 1.0;
3140     }
3141
3142     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3143     float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
3144     float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
3145     return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
3146 }
3147
3148 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
3149 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
3150 // if AppKit makes it SPI/API.
3151 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation 
3152 {
3153     return [self _scaleFactorForPrintOperation:printOperation];
3154 }
3155
3156 // This is used for Carbon printing. At some point we might want to make this public API.
3157 - (void)setPageWidthForPrinting:(float)pageWidth
3158 {
3159     [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
3160     [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
3161 }
3162
3163
3164 // Return the number of pages available for printing
3165 - (BOOL)knowsPageRange:(NSRangePointer)range {
3166     // Must do this explicit display here, because otherwise the view might redisplay while the print
3167     // sheet was up, using printer fonts (and looking different).
3168     [self displayIfNeeded];
3169     [[self window] setAutodisplay:NO];
3170     
3171     // If we are a frameset just print with the layout we have onscreen, otherwise relayout
3172     // according to the paper size
3173     float minLayoutWidth = 0.0;
3174     float maxLayoutWidth = 0.0;
3175     if (![[self _bridge] isFrameSet]) {
3176         float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
3177         minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
3178         maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
3179     }
3180     [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
3181     [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
3182     
3183     // There is a theoretical chance that someone could do some drawing between here and endDocument,
3184     // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
3185     // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
3186
3187     range->location = 1;
3188     NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
3189     float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
3190     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3191     [_private->pageRects release];
3192     NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
3193                                                                           printHeight:floorf([self _calculatePrintHeight]/totalScaleFactor)];
3194     // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
3195     // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
3196     // a blank page (with correct-looking header and footer if that option is on), which matches
3197     // the behavior of IE and Camino at least.
3198     if ([newPageRects count] == 0) {
3199         newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
3200     }
3201     _private->pageRects = [newPageRects retain];
3202     
3203     range->length = [_private->pageRects count];
3204     
3205     return YES;
3206 }
3207
3208 // Return the drawing rectangle for a particular page number
3209 - (NSRect)rectForPage:(int)page {
3210     return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
3211 }
3212
3213 - (void)drawPageBorderWithSize:(NSSize)borderSize
3214 {
3215     ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));    
3216     [[self _webView] _drawHeaderAndFooter];
3217 }
3218
3219 - (void)beginDocument
3220 {
3221     NS_DURING
3222         [super beginDocument];
3223     NS_HANDLER
3224         // Exception during [super beginDocument] means that endDocument will not get called,
3225         // so we need to clean up our "print mode" here.
3226         [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
3227         [[self window] setAutodisplay:YES];
3228     NS_ENDHANDLER
3229 }
3230
3231 - (void)endDocument
3232 {
3233     [super endDocument];
3234     // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO 
3235     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
3236     [[self window] setAutodisplay:YES];
3237 }
3238
3239 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
3240 {   
3241     // Work around this bug:
3242     // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
3243     [NSKeyBindingManager sharedKeyBindingManager];
3244     
3245     // Use the isEditable state to determine whether or not to process tab key events.
3246     // The idea here is that isEditable will be NO when this WebView is being used
3247     // in a browser, and we desire the behavior where tab moves to the next element
3248     // in tab order. If isEditable is YES, it is likely that the WebView is being
3249     // embedded as the whole view, as in Mail, and tabs should input tabs as expected
3250     // in a text editor.
3251     if (![[self _webView] isEditable] && [event _web_isTabKeyEvent]) 
3252         return NO;
3253     
3254     // Now process the key normally
3255     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
3256     return YES;
3257 }
3258
3259 - (void)keyDown:(NSEvent *)event
3260 {
3261     [self retain];
3262
3263     BOOL callSuper = NO;
3264
3265     _private->keyDownEvent = event;
3266
3267     WebBridge *bridge = [self _bridge];
3268     if ([bridge interceptKeyEvent:event toView:self]) {
3269         // WebCore processed a key event, bail on any outstanding complete: UI
3270         [_private->compController endRevertingChange:YES moveLeft:NO];
3271     } else if (_private->compController && [_private->compController filterKeyDown:event]) {
3272         // Consumed by complete: popup window
3273     } else {
3274         // We're going to process a key event, bail on any outstanding complete: UI
3275         [_private->compController endRevertingChange:YES moveLeft:NO];
3276         if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
3277             // Consumed by key bindings manager.
3278         } else {
3279             callSuper = YES;
3280         }
3281     }
3282     if (callSuper) {
3283         [super keyDown:event];
3284     } else {
3285         [NSCursor setHiddenUntilMouseMoves:YES];
3286     }
3287
3288     _private->keyDownEvent = nil;
3289     
3290     [self release];
3291 }
3292
3293 - (void)keyUp:(NSEvent *)event
3294 {
3295     [self retain];
3296     
3297     if (![[self _bridge] interceptKeyEvent:event toView:self]) {
3298         [super keyUp:event];
3299     }
3300     
3301     [self release];
3302 }
3303
3304 - (id)accessibilityAttributeValue:(NSString*)attributeName
3305 {
3306     if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
3307         id accTree = [[self _bridge] accessibilityTree];
3308         if (accTree)
3309             return [NSArray arrayWithObject: accTree];
3310         return nil;
3311     }
3312     return [super accessibilityAttributeValue:attributeName];
3313 }
3314
3315 - (id)accessibilityFocusedUIElement
3316 {
3317     id accTree = [[self _bridge] accessibilityTree];
3318     if (accTree)
3319         return [accTree accessibilityFocusedUIElement];
3320     else
3321         return self;
3322 }
3323
3324 - (id)accessibilityHitTest:(NSPoint)point
3325 {
3326     id accTree = [[self _bridge] accessibilityTree];
3327     if (accTree) {
3328         NSPoint windowCoord = [[self window] convertScreenToBase: point];
3329         return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
3330     }
3331     else
3332         return self;
3333 }
3334
3335 - (id)_accessibilityParentForSubview:(NSView *)subview
3336 {
3337     id accTree = [[self _bridge] accessibilityTree];
3338     if (!accTree)
3339         return self;
3340         
3341     id parent = [accTree _accessibilityParentForSubview:subview];
3342     if (parent == nil)
3343         return self;
3344
3345     return parent;
3346 }
3347
3348 - (void)centerSelectionInVisibleArea:(id)sender
3349 {
3350     [[self _bridge] centerSelectionInVisibleArea];
3351 }
3352
3353 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
3354 {
3355     WebBridge *bridge = [self _bridge];
3356     DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
3357     WebView *webView = [self _webView];
3358     if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3359         [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
3360     }
3361 }
3362
3363 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
3364 {
3365     WebBridge *bridge = [self _bridge];
3366     DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
3367     WebView *webView = [self _webView];
3368     if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3369         [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
3370     }
3371 }
3372
3373 - (void)moveBackward:(id)sender
3374 {
3375     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
3376 }
3377
3378 - (void)moveBackwardAndModifySelection:(id)sender
3379 {
3380     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
3381 }
3382
3383 - (void)moveDown:(id)sender
3384 {
3385     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
3386 }
3387
3388 - (void)moveDownAndModifySelection:(id)sender
3389 {
3390     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
3391 }
3392
3393 - (void)moveForward:(id)sender
3394 {
3395     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
3396 }
3397
3398 - (void)moveForwardAndModifySelection:(id)sender
3399 {
3400     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
3401 }
3402
3403 - (void)moveLeft:(id)sender
3404 {
3405     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
3406 }
3407
3408 - (void)moveLeftAndModifySelection:(id)sender
3409 {
3410     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
3411 }
3412
3413 - (void)moveRight:(id)sender
3414 {
3415     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
3416 }
3417
3418 - (void)moveRightAndModifySelection:(id)sender
3419 {
3420     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
3421 }
3422
3423 - (void)moveToBeginningOfDocument:(id)sender
3424 {
3425     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
3426 }
3427
3428 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
3429 {
3430     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
3431 }
3432
3433 - (void)moveToBeginningOfLine:(id)sender
3434 {
3435     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3436 }
3437
3438 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
3439 {
3440     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3441 }
3442
3443 - (void)moveToBeginningOfParagraph:(id)sender
3444 {
3445     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3446 }
3447
3448 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
3449 {
3450     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3451 }
3452
3453 - (void)moveToEndOfDocument:(id)sender
3454 {
3455     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3456 }
3457
3458 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
3459 {
3460     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3461 }
3462
3463 - (void)moveToEndOfLine:(id)sender
3464 {
3465     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToLineBoundary];
3466 }
3467
3468 - (void)moveToEndOfLineAndModifySelection:(id)sender
3469 {
3470     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToLineBoundary];
3471 }
3472
3473 - (void)moveToEndOfParagraph:(id)sender
3474 {
3475     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3476 }
3477
3478 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
3479 {
3480     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3481 }
3482
3483 - (void)moveParagraphBackwardAndModifySelection:(id)sender
3484 {
3485     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByParagraph];
3486 }
3487
3488 - (void)moveParagraphForwardAndModifySelection:(id)sender
3489 {
3490     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByParagraph];
3491 }
3492
3493 - (void)moveUp:(id)sender
3494 {
3495     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
3496 }
3497
3498 - (void)moveUpAndModifySelection:(id)sender
3499 {
3500     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
3501 }
3502
3503 - (void)moveWordBackward:(id)sender
3504 {
3505     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
3506 }
3507
3508 - (void)moveWordBackwardAndModifySelection:(id)sender
3509 {
3510     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
3511 }
3512
3513 - (void)moveWordForward:(id)sender
3514 {
3515     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
3516 }
3517
3518 - (void)moveWordForwardAndModifySelection:(id)sender
3519 {
3520     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
3521 }
3522
3523 - (void)moveWordLeft:(id)sender
3524 {
3525     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
3526 }
3527
3528 - (void)moveWordLeftAndModifySelection:(id)sender
3529 {
3530     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
3531 }
3532
3533 - (void)moveWordRight:(id)sender
3534 {
3535     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
3536 }
3537
3538 - (void)moveWordRightAndModifySelection:(id)sender
3539 {
3540     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
3541 }
3542
3543 - (void)pageUp:(id)sender
3544 {
3545     WebFrameView *frameView = [self _web_parentWebFrameView];
3546     if (frameView == nil)
3547         return;
3548     [self _alterCurrentSelection:WebSelectByMoving verticalDistance:-[frameView _verticalPageScrollDistance]];
3549 }
3550
3551 - (void)pageDown:(id)sender
3552 {
3553     WebFrameView *frameView = [self _web_parentWebFrameView];
3554     if (frameView == nil)
3555         return;
3556     [self _alterCurrentSelection:WebSelectByMoving verticalDistance:[frameView _verticalPageScrollDistance]];
3557 }
3558
3559 - (void)pageUpAndModifySelection:(id)sender
3560 {
3561     WebFrameView *frameView = [self _web_parentWebFrameView];
3562     if (frameView == nil)
3563         return;
3564     [self _alterCurrentSelection:WebSelectByExtending verticalDistance:-[frameView _verticalPageScrollDistance]];
3565 }
3566
3567 - (void)pageDownAndModifySelection:(id)sender
3568 {
3569     WebFrameView *frameView = [self _web_parentWebFrameView];
3570     if (frameView == nil)
3571         return;
3572     [self _alterCurrentSelection:WebSelectByExtending verticalDistance:[frameView _verticalPageScrollDistance]];
3573 }
3574
3575 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
3576 {
3577     WebBridge *bridge = [self _bridge];
3578     DOMRange *range = [bridge rangeByExpandingSelectionWithGranularity:granularity];
3579     if (range && ![range collapsed]) {
3580         WebView *webView = [self _webView];
3581         if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3582             [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity] closeTyping:YES];
3583         }
3584     }
3585 }
3586
3587 - (void)selectParagraph:(id)sender
3588 {
3589     [self _expandSelectionToGranularity:WebSelectByParagraph];
3590 }
3591
3592 - (void)selectLine:(id)sender
3593 {
3594     [self _expandSelectionToGranularity:WebSelectByLine];
3595 }
3596
3597 - (void)selectWord:(id)sender
3598 {
3599     [self _expandSelectionToGranularity:WebSelectByWord];
3600 }
3601
3602 - (void)copy:(id)sender
3603 {
3604     if ([[self _bridge] tryDHTMLCopy]) {
3605         return;     // DHTML did the whole operation
3606     }
3607     if (![self _canCopy]) {
3608         NSBeep();
3609         return;
3610     }
3611     [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3612 }
3613
3614 - (void)delete:(id)sender
3615 {
3616     if (![self _canDelete]) {
3617         NSBeep();
3618         return;
3619     }
3620     [self _deleteSelection];
3621 }
3622
3623 - (void)cut:(id)sender
3624 {
3625     WebBridge *bridge = [self _bridge];
3626     if ([bridge tryDHTMLCut]) {
3627         return;     // DHTML did the whole operation
3628     }
3629     if (![self _canCut]) {
3630         NSBeep();
3631         return;
3632     }
3633     DOMRange *range = [self _selectedRange];
3634     if ([self _shouldDeleteRange:range]) {
3635         [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3636         [bridge deleteSelectionWithSmartDelete:[self _canSmartCopyOrDelete]];
3637    }
3638 }
3639
3640 - (void)paste:(id)sender
3641 {
3642     if ([[self _bridge] tryDHTMLPaste]) {
3643         return;     // DHTML did the whole operation
3644     }
3645     if (![self _canPaste]) {
3646         return;
3647     }
3648     [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
3649 }
3650
3651 - (NSData *)_selectionStartFontAttributesAsRTF
3652 {
3653     NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"x"
3654         attributes:[[self _bridge] fontAttributesForSelectionStart]];
3655     NSData *data = [string RTFFromRange:NSMakeRange(0, [string length]) documentAttributes:nil];
3656     [string release];
3657     return data;
3658 }
3659
3660 - (NSDictionary *)_fontAttributesFromFontPasteboard
3661 {
3662     NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3663     if (fontPasteboard == nil)
3664         return nil;
3665     NSData *data = [fontPasteboard dataForType:NSFontPboardType];
3666     if (data == nil || [data length] == 0)
3667         return nil;
3668     // NSTextView does something more efficient by parsing the attributes only, but that's not available in API.
3669     NSAttributedString *string = [[[NSAttributedString alloc] initWithRTF:data documentAttributes:NULL] autorelease];
3670     if (string == nil || [string length] == 0)
3671         return nil;
3672     return [string fontAttributesInRange:NSMakeRange(0, 1)];
3673 }
3674
3675 - (DOMCSSStyleDeclaration *)_emptyStyle
3676 {
3677     return [[[self _bridge] DOMDocument] createCSSStyleDeclaration];
3678 }
3679
3680 - (NSString *)_colorAsString:(NSColor *)color
3681 {
3682     NSColor *rgbColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
3683     // FIXME: If color is non-nil and rgbColor is nil, that means we got some kind
3684     // of fancy color that can't be converted to RGB. Changing that to "transparent"
3685     // might not be great, but it's probably OK.
3686     if (rgbColor == nil)
3687         return @"transparent";
3688     float r = [rgbColor redComponent];
3689     float g = [rgbColor greenComponent];
3690     float b = [rgbColor blueComponent];
3691     float a = [rgbColor alphaComponent];
3692     if (a == 0)
3693         return @"transparent";
3694     if (r == 0 && g == 0 && b == 0 && a == 1)
3695         return @"black";
3696     if (r == 1 && g == 1 && b == 1 && a == 1)
3697         return @"white";
3698     // FIXME: Lots more named colors. Maybe we could use the table in WebCore?
3699     if (a == 1)
3700         return [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", r * 255, g * 255, b * 255];
3701     return [NSString stringWithFormat:@"rgba(%.0f,%.0f,%.0f,%f)", r * 255, g * 255, b * 255, a];
3702 }
3703
3704 - (NSString *)_shadowAsString:(NSShadow *)shadow
3705 {
3706     if (shadow == nil)
3707         return @"none";
3708     NSSize offset = [shadow shadowOffset];
3709     float blurRadius = [shadow shadowBlurRadius];
3710     if (offset.width == 0 && offset.height == 0 && blurRadius == 0)
3711         return @"none";
3712     NSColor *color = [shadow shadowColor];
3713     if (color == nil)
3714         return @"none";
3715     // FIXME: Handle non-integral values here?
3716     if (blurRadius == 0)
3717         return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height];
3718     return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height, blurRadius];
3719 }
3720
3721 - (DOMCSSStyleDeclaration *)_styleFromFontAttributes:(NSDictionary *)dictionary
3722 {
3723     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3724
3725     NSColor *color = [dictionary objectForKey:NSBackgroundColorAttributeName];
3726     [style setBackgroundColor:[self _colorAsString:color]];
3727
3728     NSFont *font = [dictionary objectForKey:NSFontAttributeName];
3729     if (font == nil) {
3730         [style setFontFamily:@"Helvetica"];
3731         [style setFontSize:@"12px"];
3732         [style setFontWeight:@"normal"];
3733         [style setFontStyle:@"normal"];
3734     } else {
3735         NSFontManager *fm = [NSFontManager sharedFontManager];
3736         // FIXME: Need more sophisticated escaping code if we want to handle family names
3737         // with characters like single quote or backslash in their names.
3738         [style setFontFamily:[NSString stringWithFormat:@"'%@'", [font familyName]]];
3739         [style setFontSize:[NSString stringWithFormat:@"%0.fpx", [font pointSize]]];
3740         if ([fm weightOfFont:font] >= MIN_BOLD_WEIGHT) {
3741             [style setFontWeight:@"bold"];
3742         } else {
3743             [style setFontWeight:@"normal"];
3744         }
3745         if (([fm traitsOfFont:font] & NSItalicFontMask) != 0) {
3746             [style setFontStyle:@"italic"];
3747         } else {
3748             [style setFontStyle:@"normal"];
3749         }
3750     }
3751
3752     color = [dictionary objectForKey:NSForegroundColorAttributeName];
3753     [style setColor:color ? [self _colorAsString:color] : @"black"];
3754
3755     NSShadow *shadow = [dictionary objectForKey:NSShadowAttributeName];
3756     [style setTextShadow:[self _shadowAsString:shadow]];
3757
3758     int strikethroughInt = [[dictionary objectForKey:NSStrikethroughStyleAttributeName] intValue];
3759
3760     int superscriptInt = [[dictionary objectForKey:NSSuperscriptAttributeName] intValue];
3761     if (superscriptInt > 0)
3762         [style setVerticalAlign:@"super"];
3763     else if (superscriptInt < 0)
3764         [style setVerticalAlign:@"sub"];
3765     else
3766         [style setVerticalAlign:@"baseline"];
3767     int underlineInt = [[dictionary objectForKey:NSUnderlineStyleAttributeName] intValue];
3768     // FIXME: Underline wins here if we have both (see bug 3790443).
3769     if (strikethroughInt == NSUnderlineStyleNone && underlineInt == NSUnderlineStyleNone)
3770         [style setProperty:@"-khtml-text-decorations-in-effect" :@"none" :@""];
3771     else if (underlineInt == NSUnderlineStyleNone)
3772         [style setProperty:@"-khtml-text-decorations-in-effect" :@"line-through" :@""];
3773     else
3774         [style setProperty:@"-khtml-text-decorations-in-effect" :@"underline" :@""];
3775
3776     return style;
3777 }
3778
3779 - (void)_applyStyleToSelection:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
3780 {
3781     if (style == nil || [style length] == 0 || ![self _canEdit])
3782         return;
3783     WebView *webView = [self _webView];
3784     WebBridge *bridge = [self _bridge];
3785     if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3786         [bridge applyStyle:style withUndoAction:undoAction];
3787     }
3788 }
3789
3790 - (void)_applyParagraphStyleToSelection:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
3791 {
3792     if (style == nil || [style length] == 0 || ![self _canEdit])
3793         return;
3794     WebView *webView = [self _webView];
3795     WebBridge *bridge = [self _bridge];
3796     if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3797         [bridge applyParagraphStyle:style withUndoAction:undoAction];
3798     }
3799 }
3800
3801 - (void)_toggleBold
3802 {
3803     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3804     [style setFontWeight:@"bold"];
3805     if ([[self _bridge] selectionStartHasStyle:style])
3806         [style setFontWeight:@"normal"];
3807     [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3808 }
3809
3810 - (void)_toggleItalic
3811 {
3812     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3813     [style setFontStyle:@"italic"];
3814     if ([[self _bridge] selectionStartHasStyle:style])
3815         [style setFontStyle:@"normal"];
3816     [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3817 }
3818
3819 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
3820 {
3821     ASSERT([self _webView]);
3822     if (![[[self _webView] preferences] respectStandardStyleKeyEquivalents]) {
3823         return NO;
3824     }
3825     
3826     if (![self _canEdit])
3827         return NO;
3828     
3829     NSString *string = [event charactersIgnoringModifiers];
3830     if ([string isEqualToString:@"b"]) {
3831         [self _toggleBold];
3832         return YES;
3833     }
3834     if ([string isEqualToString:@"i"]) {
3835         [self _toggleItalic];
3836         return YES;
3837     }
3838     
3839     return NO;
3840 }
3841
3842 - (BOOL)performKeyEquivalent:(NSEvent *)event
3843 {
3844     if ([self _handleStyleKeyEquivalent:event]) {
3845         return YES;
3846     }
3847     
3848     BOOL ret;
3849     
3850     [self retain];
3851     
3852     // Pass command-key combos through WebCore if there is a key binding available for
3853     // this event. This lets web pages have a crack at intercepting command-modified keypresses.
3854     // But don't do it if we have already handled the event.
3855     if (event != _private->keyDownEvent
3856             && [self _web_firstResponderIsSelfOrDescendantView]
3857             && [[self _bridge] interceptKeyEvent:event toView:self]) {
3858         
3859         ret = YES;
3860     }
3861     else
3862         ret = [super performKeyEquivalent:event];
3863     
3864     [self release];
3865     
3866     return ret;
3867 }
3868
3869 - (void)copyFont:(id)sender
3870 {
3871     // Put RTF with font attributes on the pasteboard.
3872     // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3873     NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3874     [fontPasteboard declareTypes:[NSArray arrayWithObject:NSFontPboardType] owner:nil];
3875     [fontPasteboard setData:[self _selectionStartFontAttributesAsRTF] forType:NSFontPboardType];
3876 }
3877
3878 - (void)pasteFont:(id)sender
3879 {
3880     // Read RTF with font attributes from the pasteboard.
3881     // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3882     [self _applyStyleToSelection:[self _styleFromFontAttributes:[self _fontAttributesFromFontPasteboard]] withUndoAction:WebUndoActionPasteFont];
3883 }
3884
3885 - (void)pasteAsPlainText:(id)sender
3886 {
3887     if (![self _canEdit])
3888         return;
3889         
3890     NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
3891     NSString *text = [pasteboard stringForType:NSStringPboardType];
3892     WebBridge *bridge = [self _bridge];
3893     if ([self _shouldReplaceSelectionWithText:text givenAction:WebViewInsertActionPasted]) {
3894         [bridge replaceSelectionWithText:text selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
3895     }
3896 }
3897
3898 - (void)pasteAsRichText:(id)sender
3899 {
3900     // Since rich text always beats plain text when both are on the pasteboard, it's not
3901     // clear how this is different from plain old paste.
3902     [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:NO];
3903 }
3904
3905 - (NSFont *)_originalFontA
3906 {
3907     return [[NSFontManager sharedFontManager] fontWithFamily:@"Helvetica" traits:0 weight:STANDARD_WEIGHT size:10];
3908 }
3909
3910 - (NSFont *)_originalFontB
3911 {
3912     return [[NSFontManager sharedFontManager] fontWithFamily:@"Times" traits:(NSBoldFontMask | NSItalicFontMask) weight:STANDARD_BOLD_WEIGHT size:12];
3913 }
3914
3915 - (void)_addToStyle:(DOMCSSStyleDeclaration *)style fontA:(NSFont *)a fontB:(NSFont *)b
3916 {
3917     // Since there's no way to directly ask NSFontManager what style change it's going to do
3918     // we instead pass two "specimen" fonts to it and let it change them. We then deduce what
3919     // style change it was doing by looking at what happened to each of the two fonts.
3920     // So if it was making the text bold, both fonts will be bold after the fact.
3921
3922     if (a == nil || b == nil)
3923         return;
3924
3925     NSFontManager *fm = [NSFontManager sharedFontManager];
3926
3927     NSFont *oa = [self _originalFontA];
3928
3929     NSString *aFamilyName = [a familyName];
3930     NSString *bFamilyName = [b familyName];
3931
3932     int aPointSize = [a pointSize];
3933     int bPointSize = [b pointSize];
3934
3935     int aWeight = [fm weightOfFont:a];
3936     int bWeight = [fm weightOfFont:b];
3937
3938     BOOL aIsBold = aWeight >= MIN_BOLD_WEIGHT;
3939
3940     BOOL aIsItalic = ([fm traitsOfFont:a] & NSItalicFontMask) != 0;
3941     BOOL bIsItalic = ([fm traitsOfFont:b] & NSItalicFontMask) != 0;
3942
3943     if ([aFamilyName isEqualToString:bFamilyName]) {
3944         NSString *familyNameForCSS = aFamilyName;
3945
3946         // The family name may not be specific enough to get us the font specified.
3947         // In some cases, the only way to get exactly what we are looking for is to use
3948         // the Postscript name.
3949         
3950         // Find the font the same way the rendering code would later if it encountered this CSS.
3951         WebTextRendererFactory *factory = [WebTextRendererFactory sharedFactory];
3952         NSFontTraitMask traits = 0;
3953         if (aIsBold)
3954             traits |= NSBoldFontMask;
3955         if (aIsItalic)
3956             traits |= NSItalicFontMask;
3957         NSFont *foundFont = [factory cachedFontFromFamily:aFamilyName traits:traits size:aPointSize];
3958
3959         // If we don't find a font with the same Postscript name, then we'll have to use the
3960         // Postscript name to make the CSS specific enough.
3961         if (![[foundFont fontName] isEqualToString:[a fontName]]) {
3962             familyNameForCSS = [a fontName];
3963         }
3964
3965         // FIXME: Need more sophisticated escaping code if we want to handle family names
3966         // with characters like single quote or backslash in their names.
3967         [style setFontFamily:[NSString stringWithFormat:@"'%@'", familyNameForCSS]];
3968     }
3969
3970     int soa = [oa pointSize];
3971     if (aPointSize == bPointSize) {
3972         [style setFontSize:[NSString stringWithFormat:@"%dpx", aPointSize]];
3973     } else if (aPointSize < soa) {
3974         [style _setFontSizeDelta:@"-1px"];
3975     } else if (aPointSize > soa) {
3976         [style _setFontSizeDelta:@"1px"];
3977     }
3978
3979     if (aWeight == bWeight) {
3980         if (aIsBold) {
3981             [style setFontWeight:@"bold"];
3982         } else {
3983             [style setFontWeight:@"normal"];
3984         }
3985     }
3986
3987     if (aIsItalic == bIsItalic) {
3988         if (aIsItalic) {
3989             [style setFontStyle:@"italic"];
3990         } else {
3991             [style setFontStyle:@"normal"];
3992         }
3993     }
3994 }
3995
3996 - (DOMCSSStyleDeclaration *)_styleFromFontManagerOperation
3997 {
3998     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3999
4000     NSFontManager *fm = [NSFontManager sharedFontManager];
4001
4002     NSFont *oa = [self _originalFontA];
4003     NSFont *ob = [self _originalFontB];    
4004     [self _addToStyle:style fontA:[fm convertFont:oa] fontB:[fm convertFont:ob]];
4005
4006     return style;
4007 }
4008
4009 - (void)changeFont:(id)sender
4010 {
4011     [self _applyStyleToSelection:[self _styleFromFontManagerOperation] withUndoAction:WebUndoActionSetFont];
4012 }
4013
4014 - (DOMCSSStyleDeclaration *)_styleForAttributeChange:(id)sender
4015 {
4016     DOMCSSStyleDeclaration *style = [self _emptyStyle];
4017
4018     NSShadow *shadow = [[NSShadow alloc] init];
4019     [shadow setShadowOffset:NSMakeSize(1, 1)];
4020
4021     NSDictionary *oa = [NSDictionary dictionaryWithObjectsAndKeys:
4022         [self _originalFontA], NSFontAttributeName,
4023         nil];
4024     NSDictionary *ob = [NSDictionary dictionaryWithObjectsAndKeys:
4025         [NSColor blackColor], NSBackgroundColorAttributeName,
4026         [self _originalFontB], NSFontAttributeName,
4027         [NSColor whiteColor], NSForegroundColorAttributeName,
4028         shadow, NSShadowAttributeName,
4029         [NSNumber numberWithInt:NSUnderlineStyleSingle], NSStrikethroughStyleAttributeName,
4030         [NSNumber numberWithInt:1], NSSuperscriptAttributeName,
4031         [NSNumber numberWithInt:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,
4032         nil];
4033
4034     [shadow release];
4035
4036 #if 0
4037
4038 NSObliquenessAttributeName        /* float; skew to be applied to glyphs, default 0: no skew */
4039     // font-style, but that is just an on-off switch
4040
4041 NSExpansionAttributeName          /* float; log of expansion factor to be applied to glyphs, default 0: no expansion */
4042     // font-stretch?
4043
4044 NSKernAttributeName               /* float, amount to modify default kerning, if 0, kerning off */
4045     // letter-spacing? probably not good enough
4046
4047 NSUnderlineColorAttributeName     /* NSColor, default nil: same as foreground color */
4048 NSStrikethroughColorAttributeName /* NSColor, default nil: same as foreground color */
4049     // text-decoration-color?
4050
4051 NSLigatureAttributeName           /* int, default 1: default ligatures, 0: no ligatures, 2: all ligatures */
4052 NSBaselineOffsetAttributeName     /* float, in points; offset from baseline, default 0 */
4053 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) */
4054 NSStrokeColorAttributeName        /* NSColor, default nil: same as foreground color */
4055     // need extensions?
4056
4057 #endif
4058     
4059     NSDictionary *a = [sender convertAttributes:oa];
4060     NSDictionary *b = [sender convertAttributes:ob];
4061
4062     NSColor *ca = [a objectForKey:NSBackgroundColorAttributeName];
4063     NSColor *cb = [b objectForKey:NSBackgroundColorAttributeName];
4064     if (ca == cb) {
4065         [style setBackgroundColor:[self _colorAsString:ca]];
4066     }
4067
4068     [self _addToStyle:style fontA:[a objectForKey:NSFontAttributeName] fontB:[b objectForKey:NSFontAttributeName]];
4069
4070     ca = [a objectForKey:NSForegroundColorAttributeName];
4071     cb = [b objectForKey:NSForegroundColorAttributeName];
4072     if (ca == cb) {
4073         [style setColor:[self _colorAsString:ca]];
4074     }
4075
4076     NSShadow *sha = [a objectForKey:NSShadowAttributeName];
4077     if (sha) {
4078         [style setTextShadow:[self _shadowAsString:sha]];
4079     } else if ([b objectForKey:NSShadowAttributeName] == nil) {
4080         [style setTextShadow:@"none"];
4081     }
4082
4083     int sa = [[a objectForKey:NSStrikethroughStyleAttributeName] intValue];
4084     int sb = [[b objectForKey:NSStrikethroughStyleAttributeName] intValue];
4085     if (sa == sb) {
4086         if (sa == NSUnderlineStyleNone)
4087             [style setProperty:@"-khtml-text-decorations-in-effect" :@"none" :@""]; 
4088             // we really mean "no line-through" rather than "none"
4089         else
4090             [style setProperty:@"-khtml-text-decorations-in-effect" :@"line-through" :@""];
4091             // we really mean "add line-through" rather than "line-through"
4092     }
4093
4094     sa = [[a objectForKey:NSSuperscriptAttributeName] intValue];
4095     sb = [[b objectForKey:NSSuperscriptAttributeName] intValue];
4096     if (sa == sb) {
4097         if (sa > 0)
4098             [style setVerticalAlign:@"super"];
4099         else if (sa < 0)
4100             [style setVerticalAlign:@"sub"];
4101         else
4102             [style setVerticalAlign:@"baseline"];
4103     }
4104
4105     int ua = [[a objectForKey:NSUnderlineStyleAttributeName] intValue];
4106     int ub = [[b objectForKey:NSUnderlineStyleAttributeName] intValue];
4107     if (ua == ub) {
4108         if (ua == NSUnderlineStyleNone)
4109             [style setProperty:@"-khtml-text-decorations-in-effect" :@"none" :@""];
4110             // we really mean "no underline" rather than "none"
4111         else
4112             [style setProperty:@"-khtml-text-decorations-in-effect" :@"underline" :@""];
4113             // we really mean "add underline" rather than "underline"
4114     }
4115
4116     return style;
4117 }
4118
4119 - (void)changeAttributes:(id)sender
4120 {
4121     [self _applyStyleToSelection:[self _styleForAttributeChange:sender] withUndoAction:WebUndoActionChangeAttributes];
4122 }
4123
4124 - (DOMCSSStyleDeclaration *)_styleFromColorPanelWithSelector:(SEL)selector
4125 {
4126     DOMCSSStyleDeclaration *style = [self _emptyStyle];
4127
4128     ASSERT([style respondsToSelector:selector]);
4129     [style performSelector:selector withObject:[self _colorAsString:[[NSColorPanel sharedColorPanel] color]]];
4130     
4131     return style;
4132 }
4133
4134 - (WebUndoAction)_undoActionFromColorPanelWithSelector:(SEL)selector
4135 {
4136     if (selector == @selector(setBackgroundColor:)) {