2011-02-01 Martin Robinson <mrobinson@igalia.com>
[WebKit-https.git] / Source / WebKit2 / UIProcess / API / mac / WKView.mm
1 /*
2  * Copyright (C) 2010 Apple 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  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "WKView.h"
28
29 #import "ChunkedUpdateDrawingAreaProxy.h"
30 #import "DataReference.h"
31 #import "DrawingAreaProxyImpl.h"
32 #import "FindIndicator.h"
33 #import "FindIndicatorWindow.h"
34 #import "LayerBackedDrawingAreaProxy.h"
35 #import "LayerTreeContext.h"
36 #import "Logging.h"
37 #import "NativeWebKeyboardEvent.h"
38 #import "PDFViewController.h"
39 #import "PageClientImpl.h"
40 #import "PasteboardTypes.h"
41 #import "Region.h"
42 #import "RunLoop.h"
43 #import "TextChecker.h"
44 #import "TextCheckerState.h"
45 #import "WKAPICast.h"
46 #import "WKPrintingView.h"
47 #import "WKStringCF.h"
48 #import "WKTextInputWindowController.h"
49 #import "WKViewInternal.h"
50 #import "WKViewPrivate.h"
51 #import "WebContext.h"
52 #import "WebEventFactory.h"
53 #import "WebPage.h"
54 #import "WebPageProxy.h"
55 #import "WebProcessManager.h"
56 #import "WebProcessProxy.h"
57 #import "WebSystemInterface.h"
58 #import <QuartzCore/QuartzCore.h>
59 #import <WebCore/ColorMac.h>
60 #import <WebCore/DragController.h>
61 #import <WebCore/DragData.h>
62 #import <WebCore/FloatRect.h>
63 #import <WebCore/IntRect.h>
64 #import <WebCore/KeyboardEvent.h>
65 #import <WebCore/PlatformMouseEvent.h>
66 #import <WebCore/PlatformScreen.h>
67 #import <WebKitSystemInterface.h>
68 #import <wtf/RefPtr.h>
69 #import <wtf/RetainPtr.h>
70
71 // FIXME (WebKit2) <rdar://problem/8728860> WebKit2 needs to be localized
72 #define UI_STRING(__str, __desc) [NSString stringWithUTF8String:__str]
73
74 @interface NSApplication (Details)
75 - (void)speakString:(NSString *)string;
76 @end
77
78 @interface NSWindow (Details)
79 - (NSRect)_growBoxRect;
80 - (BOOL)_updateGrowBoxForWindowFrameChange;
81 @end
82
83 extern "C" {
84     // Need to declare this attribute name because AppKit exports it but does not make it available in API or SPI headers.
85     // <rdar://problem/8631468> tracks the request to make it available. This code should be removed when the bug is closed.
86     extern NSString *NSTextInputReplacementRangeAttributeName;
87 }
88
89 using namespace WebKit;
90 using namespace WebCore;
91
92 namespace WebKit {
93
94 typedef id <NSValidatedUserInterfaceItem> ValidationItem;
95 typedef Vector<RetainPtr<ValidationItem> > ValidationVector;
96 typedef HashMap<String, ValidationVector> ValidationMap;
97
98 }
99
100 @interface WKViewData : NSObject {
101 @public
102     OwnPtr<PageClientImpl> _pageClient;
103     RefPtr<WebPageProxy> _page;
104
105     // For ToolTips.
106     NSToolTipTag _lastToolTipTag;
107     id _trackingRectOwner;
108     void* _trackingRectUserData;
109
110 #if USE(ACCELERATED_COMPOSITING)
111     NSView *_layerHostingView;
112 #endif
113
114     RetainPtr<id> _remoteAccessibilityChild;
115     
116     // For asynchronous validation.
117     ValidationMap _validationMap;
118
119     OwnPtr<PDFViewController> _pdfViewController;
120
121     OwnPtr<FindIndicatorWindow> _findIndicatorWindow;
122     // We keep here the event when resending it to
123     // the application to distinguish the case of a new event from one 
124     // that has been already sent to WebCore.
125     NSEvent *_keyDownEventBeingResent;
126     Vector<KeypressCommand> _commandsList;
127
128     // The identifier of the plug-in we want to send complex text input to, or 0 if there is none.
129     uint64_t _pluginComplexTextInputIdentifier;
130
131     Vector<CompositionUnderline> _underlines;
132     unsigned _selectionStart;
133     unsigned _selectionEnd;
134
135     bool _inBecomeFirstResponder;
136     bool _inResignFirstResponder;
137     NSEvent *_mouseDownEvent;
138     BOOL _ignoringMouseDraggedEvents;
139     BOOL _dragHasStarted;
140
141 #if ENABLE(GESTURE_EVENTS)
142     id _endGestureMonitor;
143 #endif
144 }
145 @end
146
147 @implementation WKViewData
148 @end
149
150 @interface NSObject (NSTextInputContextDetails)
151 - (BOOL)wantsToHandleMouseEvents;
152 - (BOOL)handleMouseEvent:(NSEvent *)event;
153 @end
154
155 @implementation WKView
156
157 static bool useNewDrawingArea()
158 {
159     static bool useNewDrawingArea = getenv("USE_NEW_DRAWING_AREA");
160
161     return useNewDrawingArea;
162 }
163
164 - (id)initWithFrame:(NSRect)frame
165 {
166     return [self initWithFrame:frame contextRef:toAPI(WebContext::sharedProcessContext())];
167 }
168
169 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef
170 {   
171     return [self initWithFrame:frame contextRef:contextRef pageGroupRef:nil];
172 }
173
174 - (void)_registerDraggedTypes
175 {
176     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:PasteboardTypes::forEditing()];
177     [types addObjectsFromArray:PasteboardTypes::forURL()];
178     [self registerForDraggedTypes:[types allObjects]];
179     [types release];
180 }
181
182 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef
183 {
184     self = [super initWithFrame:frame];
185     if (!self)
186         return nil;
187
188     InitWebCoreSystemInterface();
189     RunLoop::initializeMainRunLoop();
190
191     NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame
192                                                                 options:(NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect)
193                                                                   owner:self
194                                                                userInfo:nil];
195     [self addTrackingArea:trackingArea];
196     [trackingArea release];
197
198     _data = [[WKViewData alloc] init];
199
200     _data->_pageClient = PageClientImpl::create(self);
201     _data->_page = toImpl(contextRef)->createWebPage(_data->_pageClient.get(), toImpl(pageGroupRef));
202     _data->_page->initializeWebPage();
203     _data->_mouseDownEvent = nil;
204     _data->_ignoringMouseDraggedEvents = NO;
205
206     [self _registerDraggedTypes];
207
208     WebContext::statistics().wkViewCount++;
209
210 #if !defined(BUILDING_ON_SNOW_LEOPARD)
211     NSData *remoteToken = (NSData *)WKAXRemoteTokenForElement(self);
212     CoreIPC::DataReference dataToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteToken bytes]), [remoteToken length]);
213     _data->_page->sendAccessibilityPresenterToken(dataToken);
214 #endif
215     
216     return self;
217 }
218
219 - (void)dealloc
220 {
221     _data->_page->close();
222
223     [_data release];
224
225     WebContext::statistics().wkViewCount--;
226
227     [super dealloc];
228 }
229
230 - (WKPageRef)pageRef
231 {
232     return toAPI(_data->_page.get());
233 }
234
235 - (void)setDrawsBackground:(BOOL)drawsBackground
236 {
237     _data->_page->setDrawsBackground(drawsBackground);
238 }
239
240 - (BOOL)drawsBackground
241 {
242     return _data->_page->drawsBackground();
243 }
244
245 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
246 {
247     _data->_page->setDrawsTransparentBackground(drawsTransparentBackground);
248 }
249
250 - (BOOL)drawsTransparentBackground
251 {
252     return _data->_page->drawsTransparentBackground();
253 }
254
255 - (BOOL)acceptsFirstResponder
256 {
257     return YES;
258 }
259
260 - (BOOL)becomeFirstResponder
261 {
262     NSSelectionDirection direction = [[self window] keyViewSelectionDirection];
263
264     _data->_inBecomeFirstResponder = true;
265     _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
266     _data->_inBecomeFirstResponder = false;
267
268     if (direction != NSDirectSelection)
269         _data->_page->setInitialFocus(direction == NSSelectingNext);
270
271     return YES;
272 }
273
274 - (BOOL)resignFirstResponder
275 {
276     _data->_inResignFirstResponder = true;
277     _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
278     _data->_inResignFirstResponder = false;
279
280     return YES;
281 }
282
283 - (void)viewWillStartLiveResize
284 {
285     _data->_page->viewWillStartLiveResize();
286 }
287
288 - (void)viewDidEndLiveResize
289 {
290     _data->_page->viewWillEndLiveResize();
291 }
292
293 - (BOOL)isFlipped
294 {
295     return YES;
296 }
297
298 - (void)_setRemoteAccessibilityWindow:(id)window
299 {
300 #if !defined(BUILDING_ON_SNOW_LEOPARD)
301     WKAXInitializeRemoteElementWithWindow(_data->_remoteAccessibilityChild.get(), window);    
302 #endif
303 }
304
305 - (void)setFrameSize:(NSSize)size
306 {
307     [super setFrameSize:size];
308     
309     if (![self frameSizeUpdatesDisabled])
310         [self _setDrawingAreaSize:size];
311 }
312
313 - (void)_updateWindowAndViewFrames
314 {
315     NSWindow *window = [self window];
316     ASSERT(window);
317     
318     NSRect windowFrameInScreenCoordinates = [window frame];
319     NSRect viewFrameInWindowCoordinates = [self convertRect:[self frame] toView:nil];
320     NSPoint accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue];
321     
322     _data->_page->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates), IntPoint(accessibilityPosition));
323 }
324
325 - (void)renewGState
326 {
327     // Hide the find indicator.
328     _data->_findIndicatorWindow = nullptr;
329
330     // Update the view frame.
331     if ([self window])
332         [self _updateWindowAndViewFrames];
333
334     [super renewGState];
335 }
336
337 typedef HashMap<SEL, String> SelectorNameMap;
338
339 // Map selectors into Editor command names.
340 // This is not needed for any selectors that have the same name as the Editor command.
341 static const SelectorNameMap* createSelectorExceptionMap()
342 {
343     SelectorNameMap* map = new HashMap<SEL, String>;
344     
345     map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
346     map->add(@selector(insertParagraphSeparator:), "InsertNewline");
347     map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
348     map->add(@selector(pageDown:), "MovePageDown");
349     map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
350     map->add(@selector(pageUp:), "MovePageUp");
351     map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
352     map->add(@selector(scrollPageDown:), "ScrollPageForward");
353     map->add(@selector(scrollPageUp:), "ScrollPageBackward");
354     
355     return map;
356 }
357
358 static String commandNameForSelector(SEL selector)
359 {
360     // Check the exception map first.
361     static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
362     SelectorNameMap::const_iterator it = exceptionMap->find(selector);
363     if (it != exceptionMap->end())
364         return it->second;
365     
366     // Remove the trailing colon.
367     // No need to capitalize the command name since Editor command names are
368     // not case sensitive.
369     const char* selectorName = sel_getName(selector);
370     size_t selectorNameLength = strlen(selectorName);
371     if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
372         return String();
373     return String(selectorName, selectorNameLength - 1);
374 }
375
376 // Editing commands
377
378 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
379
380 WEBCORE_COMMAND(alignCenter)
381 WEBCORE_COMMAND(alignJustified)
382 WEBCORE_COMMAND(alignLeft)
383 WEBCORE_COMMAND(alignRight)
384 WEBCORE_COMMAND(copy)
385 WEBCORE_COMMAND(cut)
386 WEBCORE_COMMAND(delete)
387 WEBCORE_COMMAND(deleteBackward)
388 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
389 WEBCORE_COMMAND(deleteForward)
390 WEBCORE_COMMAND(deleteToBeginningOfLine)
391 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
392 WEBCORE_COMMAND(deleteToEndOfLine)
393 WEBCORE_COMMAND(deleteToEndOfParagraph)
394 WEBCORE_COMMAND(deleteToMark)
395 WEBCORE_COMMAND(deleteWordBackward)
396 WEBCORE_COMMAND(deleteWordForward)
397 WEBCORE_COMMAND(ignoreSpelling)
398 WEBCORE_COMMAND(indent)
399 WEBCORE_COMMAND(insertBacktab)
400 WEBCORE_COMMAND(insertLineBreak)
401 WEBCORE_COMMAND(insertNewline)
402 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
403 WEBCORE_COMMAND(insertParagraphSeparator)
404 WEBCORE_COMMAND(insertTab)
405 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
406 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
407 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
408 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
409 WEBCORE_COMMAND(moveBackward)
410 WEBCORE_COMMAND(moveBackwardAndModifySelection)
411 WEBCORE_COMMAND(moveDown)
412 WEBCORE_COMMAND(moveDownAndModifySelection)
413 WEBCORE_COMMAND(moveForward)
414 WEBCORE_COMMAND(moveForwardAndModifySelection)
415 WEBCORE_COMMAND(moveLeft)
416 WEBCORE_COMMAND(moveLeftAndModifySelection)
417 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
418 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
419 WEBCORE_COMMAND(moveRight)
420 WEBCORE_COMMAND(moveRightAndModifySelection)
421 WEBCORE_COMMAND(moveToBeginningOfDocument)
422 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
423 WEBCORE_COMMAND(moveToBeginningOfLine)
424 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
425 WEBCORE_COMMAND(moveToBeginningOfParagraph)
426 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
427 WEBCORE_COMMAND(moveToBeginningOfSentence)
428 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
429 WEBCORE_COMMAND(moveToEndOfDocument)
430 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
431 WEBCORE_COMMAND(moveToEndOfLine)
432 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
433 WEBCORE_COMMAND(moveToEndOfParagraph)
434 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
435 WEBCORE_COMMAND(moveToEndOfSentence)
436 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
437 WEBCORE_COMMAND(moveToLeftEndOfLine)
438 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
439 WEBCORE_COMMAND(moveToRightEndOfLine)
440 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
441 WEBCORE_COMMAND(moveUp)
442 WEBCORE_COMMAND(moveUpAndModifySelection)
443 WEBCORE_COMMAND(moveWordBackward)
444 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
445 WEBCORE_COMMAND(moveWordForward)
446 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
447 WEBCORE_COMMAND(moveWordLeft)
448 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
449 WEBCORE_COMMAND(moveWordRight)
450 WEBCORE_COMMAND(moveWordRightAndModifySelection)
451 WEBCORE_COMMAND(outdent)
452 WEBCORE_COMMAND(pageDown)
453 WEBCORE_COMMAND(pageDownAndModifySelection)
454 WEBCORE_COMMAND(pageUp)
455 WEBCORE_COMMAND(pageUpAndModifySelection)
456 WEBCORE_COMMAND(paste)
457 WEBCORE_COMMAND(pasteAsPlainText)
458 WEBCORE_COMMAND(scrollPageDown)
459 WEBCORE_COMMAND(scrollPageUp)
460 WEBCORE_COMMAND(scrollToBeginningOfDocument)
461 WEBCORE_COMMAND(scrollToEndOfDocument)
462 WEBCORE_COMMAND(selectAll)
463 WEBCORE_COMMAND(selectLine)
464 WEBCORE_COMMAND(selectParagraph)
465 WEBCORE_COMMAND(selectSentence)
466 WEBCORE_COMMAND(selectToMark)
467 WEBCORE_COMMAND(selectWord)
468 WEBCORE_COMMAND(setMark)
469 WEBCORE_COMMAND(subscript)
470 WEBCORE_COMMAND(superscript)
471 WEBCORE_COMMAND(swapWithMark)
472 WEBCORE_COMMAND(takeFindStringFromSelection)
473 WEBCORE_COMMAND(transpose)
474 WEBCORE_COMMAND(underline)
475 WEBCORE_COMMAND(unscript)
476 WEBCORE_COMMAND(yank)
477 WEBCORE_COMMAND(yankAndSelect)
478
479 #undef WEBCORE_COMMAND
480
481 /*
482
483 When possible, editing-related methods should be implemented in WebCore with the
484 EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing
485 individual methods here with Mac-specific code.
486
487 Editing-related methods still unimplemented that are implemented in WebKit1:
488
489 - (void)capitalizeWord:(id)sender;
490 - (void)centerSelectionInVisibleArea:(id)sender;
491 - (void)changeFont:(id)sender;
492 - (void)complete:(id)sender;
493 - (void)copyFont:(id)sender;
494 - (void)lowercaseWord:(id)sender;
495 - (void)makeBaseWritingDirectionLeftToRight:(id)sender;
496 - (void)makeBaseWritingDirectionNatural:(id)sender;
497 - (void)makeBaseWritingDirectionRightToLeft:(id)sender;
498 - (void)pasteFont:(id)sender;
499 - (void)scrollLineDown:(id)sender;
500 - (void)scrollLineUp:(id)sender;
501 - (void)showGuessPanel:(id)sender;
502 - (void)uppercaseWord:(id)sender;
503
504 Some other editing-related methods still unimplemented:
505
506 - (void)changeCaseOfLetter:(id)sender;
507 - (void)copyRuler:(id)sender;
508 - (void)insertContainerBreak:(id)sender;
509 - (void)insertDoubleQuoteIgnoringSubstitution:(id)sender;
510 - (void)insertSingleQuoteIgnoringSubstitution:(id)sender;
511 - (void)pasteRuler:(id)sender;
512 - (void)toggleRuler:(id)sender;
513 - (void)transposeWords:(id)sender;
514
515 */
516
517 // Menu items validation
518
519 static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item)
520 {
521     if (![(NSObject *)item isKindOfClass:[NSMenuItem class]])
522         return nil;
523     return (NSMenuItem *)item;
524 }
525
526 static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item)
527 {
528     if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]])
529         return nil;
530     return (NSToolbarItem *)item;
531 }
532
533 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
534 {
535     SEL action = [item action];
536
537     if (action == @selector(showGuessPanel:)) {
538         if (NSMenuItem *menuItem = ::menuItem(item)) {
539             BOOL panelShowing = [[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible];
540             [menuItem setTitle:panelShowing
541                 ? UI_STRING("Hide Spelling and Grammar", "menu item title")
542                 : UI_STRING("Show Spelling and Grammar", "menu item title")];
543         }
544         return _data->_page->selectionState().isContentEditable;
545     }
546
547     if (action == @selector(checkSpelling:) || action == @selector(changeSpelling:))
548         return _data->_page->selectionState().isContentEditable;
549
550     if (action == @selector(toggleContinuousSpellChecking:)) {
551         bool enabled = TextChecker::isContinuousSpellCheckingAllowed();
552         bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled;
553         [menuItem(item) setState:checked ? NSOnState : NSOffState];
554         return enabled;
555     }
556
557     if (action == @selector(toggleGrammarChecking:)) {
558         bool checked = TextChecker::state().isGrammarCheckingEnabled;
559         [menuItem(item) setState:checked ? NSOnState : NSOffState];
560         return YES;
561     }
562
563     if (action == @selector(toggleAutomaticSpellingCorrection:)) {
564         bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled;
565         [menuItem(item) setState:checked ? NSOnState : NSOffState];
566         return _data->_page->selectionState().isContentEditable;
567     }
568
569     if (action == @selector(orderFrontSubstitutionsPanel:)) {
570         if (NSMenuItem *menuItem = ::menuItem(item)) {
571             BOOL panelShowing = [[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible];
572             [menuItem setTitle:panelShowing
573                 ? UI_STRING("Hide Substitutions", "menu item title")
574                 : UI_STRING("Show Substitutions", "menu item title")];
575         }
576         return _data->_page->selectionState().isContentEditable;
577     }
578
579     if (action == @selector(toggleSmartInsertDelete:)) {
580         bool checked = _data->_page->isSmartInsertDeleteEnabled();
581         [menuItem(item) setState:checked ? NSOnState : NSOffState];
582         return _data->_page->selectionState().isContentEditable;
583     }
584
585     if (action == @selector(toggleAutomaticQuoteSubstitution:)) {
586         bool checked = TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
587         [menuItem(item) setState:checked ? NSOnState : NSOffState];
588         return _data->_page->selectionState().isContentEditable;
589     }
590
591     if (action == @selector(toggleAutomaticDashSubstitution:)) {
592         bool checked = TextChecker::state().isAutomaticDashSubstitutionEnabled;
593         [menuItem(item) setState:checked ? NSOnState : NSOffState];
594         return _data->_page->selectionState().isContentEditable;
595     }
596
597     if (action == @selector(toggleAutomaticLinkDetection:)) {
598         bool checked = TextChecker::state().isAutomaticLinkDetectionEnabled;
599         [menuItem(item) setState:checked ? NSOnState : NSOffState];
600         return _data->_page->selectionState().isContentEditable;
601     }
602
603     if (action == @selector(toggleAutomaticTextReplacement:)) {
604         bool checked = TextChecker::state().isAutomaticTextReplacementEnabled;
605         [menuItem(item) setState:checked ? NSOnState : NSOffState];
606         return _data->_page->selectionState().isContentEditable;
607     }
608
609     if (action == @selector(uppercaseWord:) || action == @selector(lowercaseWord:) || action == @selector(capitalizeWord:))
610         return _data->_page->selectionState().selectedRangeLength && _data->_page->selectionState().isContentEditable;
611     
612     if (action == @selector(stopSpeaking:))
613         return [NSApp isSpeaking];
614
615     // Next, handle editor commands. Start by returning YES for anything that is not an editor command.
616     // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized.
617     String commandName = commandNameForSelector([item action]);
618     if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName))
619         return YES;
620
621     // Add this item to the vector of items for a given command that are awaiting validation.
622     pair<ValidationMap::iterator, bool> addResult = _data->_validationMap.add(commandName, ValidationVector());
623     addResult.first->second.append(item);
624     if (addResult.second) {
625         // If we are not already awaiting validation for this command, start the asynchronous validation process.
626         // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
627         // we asked for the same command; there is no guarantee the answer is still valid.
628         // FIXME: The function called here should be renamed validateCommand because it is not specific to menu items.
629         _data->_page->validateMenuItem(commandName);
630     }
631
632     // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called.
633     // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment.
634     // But returning NO here would be worse; that would make keyboard commands such as command-C fail.
635     return YES;
636 }
637
638 static void speakString(WKStringRef string, WKErrorRef error, void*)
639 {
640     if (error)
641         return;
642     if (!string)
643         return;
644
645     NSString *convertedString = toImpl(string)->string();
646     [NSApp speakString:convertedString];
647 }
648
649 - (IBAction)startSpeaking:(id)sender
650 {
651     _data->_page->getSelectionOrContentsAsString(StringCallback::create(0, speakString));
652 }
653
654 - (IBAction)stopSpeaking:(id)sender
655 {
656     [NSApp stopSpeaking:sender];
657 }
658
659 - (IBAction)showGuessPanel:(id)sender
660 {
661     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
662     if (!checker) {
663         LOG_ERROR("No NSSpellChecker");
664         return;
665     }
666     
667     NSPanel *spellingPanel = [checker spellingPanel];
668     if ([spellingPanel isVisible]) {
669         [spellingPanel orderOut:sender];
670         return;
671     }
672     
673     _data->_page->advanceToNextMisspelling(true);
674     [spellingPanel orderFront:sender];
675 }
676
677 - (IBAction)checkSpelling:(id)sender
678 {
679     _data->_page->advanceToNextMisspelling(false);
680 }
681
682 - (void)changeSpelling:(id)sender
683 {
684     NSString *word = [[sender selectedCell] stringValue];
685
686     _data->_page->changeSpellingToWord(word);
687 }
688
689 - (IBAction)toggleContinuousSpellChecking:(id)sender
690 {
691     bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled;
692     TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled);
693
694     _data->_page->process()->updateTextCheckerState();
695
696     if (!spellCheckingEnabled)
697         _data->_page->unmarkAllMisspellings();
698 }
699
700 - (IBAction)toggleGrammarChecking:(id)sender
701 {
702     bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled;
703     TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled);
704
705     _data->_page->process()->updateTextCheckerState();
706
707     if (!grammarCheckingEnabled)
708         _data->_page->unmarkAllBadGrammar();
709 }
710
711 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
712 {
713     TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
714
715     _data->_page->process()->updateTextCheckerState();
716 }
717
718 - (void)orderFrontSubstitutionsPanel:(id)sender
719 {
720     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
721     if (!checker) {
722         LOG_ERROR("No NSSpellChecker");
723         return;
724     }
725     
726     NSPanel *substitutionsPanel = [checker substitutionsPanel];
727     if ([substitutionsPanel isVisible]) {
728         [substitutionsPanel orderOut:sender];
729         return;
730     }
731     [substitutionsPanel orderFront:sender];
732 }
733
734 - (IBAction)toggleSmartInsertDelete:(id)sender
735 {
736     _data->_page->setSmartInsertDeleteEnabled(!_data->_page->isSmartInsertDeleteEnabled());
737 }
738
739 - (BOOL)isAutomaticQuoteSubstitutionEnabled
740 {
741     return TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
742 }
743
744 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
745 {
746     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticQuoteSubstitutionEnabled)
747         return;
748
749     TextChecker::setAutomaticQuoteSubstitutionEnabled(flag);
750     _data->_page->process()->updateTextCheckerState();
751 }
752
753 - (void)toggleAutomaticQuoteSubstitution:(id)sender
754 {
755     TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled);
756     _data->_page->process()->updateTextCheckerState();
757 }
758
759 - (BOOL)isAutomaticDashSubstitutionEnabled
760 {
761     return TextChecker::state().isAutomaticDashSubstitutionEnabled;
762 }
763
764 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
765 {
766     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticDashSubstitutionEnabled)
767         return;
768
769     TextChecker::setAutomaticDashSubstitutionEnabled(flag);
770     _data->_page->process()->updateTextCheckerState();
771 }
772
773 - (void)toggleAutomaticDashSubstitution:(id)sender
774 {
775     TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled);
776     _data->_page->process()->updateTextCheckerState();
777 }
778
779 - (BOOL)isAutomaticLinkDetectionEnabled
780 {
781     return TextChecker::state().isAutomaticLinkDetectionEnabled;
782 }
783
784 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
785 {
786     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticLinkDetectionEnabled)
787         return;
788
789     TextChecker::setAutomaticLinkDetectionEnabled(flag);
790     _data->_page->process()->updateTextCheckerState();
791 }
792
793 - (void)toggleAutomaticLinkDetection:(id)sender
794 {
795     TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled);
796     _data->_page->process()->updateTextCheckerState();
797 }
798
799 - (BOOL)isAutomaticTextReplacementEnabled
800 {
801     return TextChecker::state().isAutomaticTextReplacementEnabled;
802 }
803
804 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
805 {
806     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticTextReplacementEnabled)
807         return;
808
809     TextChecker::setAutomaticTextReplacementEnabled(flag);
810     _data->_page->process()->updateTextCheckerState();
811 }
812
813 - (void)toggleAutomaticTextReplacement:(id)sender
814 {
815     TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled);
816     _data->_page->process()->updateTextCheckerState();
817 }
818
819 - (void)uppercaseWord:(id)sender
820 {
821     _data->_page->uppercaseWord();
822 }
823
824 - (void)lowercaseWord:(id)sender
825 {
826     _data->_page->lowercaseWord();
827 }
828
829 - (void)capitalizeWord:(id)sender
830 {
831     _data->_page->capitalizeWord();
832 }
833
834 // Events
835
836 // Override this so that AppKit will send us arrow keys as key down events so we can
837 // support them via the key bindings mechanism.
838 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
839 {
840     return YES;
841 }
842
843 - (void)_setMouseDownEvent:(NSEvent *)event
844 {
845     ASSERT(!event || [event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
846     
847     if (event == _data->_mouseDownEvent)
848         return;
849     
850     [_data->_mouseDownEvent release];
851     _data->_mouseDownEvent = [event retain];
852 }
853
854 #define EVENT_HANDLER(Selector, Type) \
855     - (void)Selector:(NSEvent *)theEvent \
856     { \
857         Web##Type##Event webEvent = WebEventFactory::createWeb##Type##Event(theEvent, self); \
858         _data->_page->handle##Type##Event(webEvent); \
859     }
860
861 EVENT_HANDLER(mouseEntered, Mouse)
862 EVENT_HANDLER(mouseExited, Mouse)
863 EVENT_HANDLER(mouseMoved, Mouse)
864 EVENT_HANDLER(otherMouseDown, Mouse)
865 EVENT_HANDLER(otherMouseDragged, Mouse)
866 EVENT_HANDLER(otherMouseMoved, Mouse)
867 EVENT_HANDLER(otherMouseUp, Mouse)
868 EVENT_HANDLER(rightMouseDown, Mouse)
869 EVENT_HANDLER(rightMouseDragged, Mouse)
870 EVENT_HANDLER(rightMouseMoved, Mouse)
871 EVENT_HANDLER(rightMouseUp, Mouse)
872 EVENT_HANDLER(scrollWheel, Wheel)
873
874 #undef EVENT_HANDLER
875
876 - (void)_mouseHandler:(NSEvent *)event
877 {
878     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
879     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
880         return;
881     WebMouseEvent webEvent = WebEventFactory::createWebMouseEvent(event, self);
882     _data->_page->handleMouseEvent(webEvent);
883 }
884
885 - (void)mouseDown:(NSEvent *)event
886 {
887     [self _setMouseDownEvent:event];
888     _data->_ignoringMouseDraggedEvents = NO;
889     _data->_dragHasStarted = NO;
890     [self _mouseHandler:event];
891 }
892
893 - (void)mouseUp:(NSEvent *)event
894 {
895     [self _setMouseDownEvent:nil];
896     [self _mouseHandler:event];
897 }
898
899 - (void)mouseDragged:(NSEvent *)event
900 {
901     if (_data->_ignoringMouseDraggedEvents)
902         return;
903     [self _mouseHandler:event];
904 }
905
906 #if ENABLE(GESTURE_EVENTS)
907
908 static const short kIOHIDEventTypeScroll = 6;
909
910 - (void)shortCircuitedEndGestureWithEvent:(NSEvent *)event
911 {
912     if ([event subtype] != kIOHIDEventTypeScroll)
913         return;
914
915     WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
916     _data->_page->handleGestureEvent(webEvent);
917
918     if (_data->_endGestureMonitor) {
919         [NSEvent removeMonitor:_data->_endGestureMonitor];
920         _data->_endGestureMonitor = nil;
921     }
922 }
923
924 - (void)beginGestureWithEvent:(NSEvent *)event
925 {
926     if ([event subtype] != kIOHIDEventTypeScroll)
927         return;
928
929     WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
930     _data->_page->handleGestureEvent(webEvent);
931
932     if (!_data->_endGestureMonitor) {
933         _data->_endGestureMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskEndGesture handler:^(NSEvent *blockEvent) {
934             [self shortCircuitedEndGestureWithEvent:blockEvent];
935             return blockEvent;
936         }];
937     }
938 }
939 #endif
940
941 - (void)doCommandBySelector:(SEL)selector
942 {
943     if (selector != @selector(noop:))
944         _data->_commandsList.append(KeypressCommand(commandNameForSelector(selector)));
945 }
946
947 - (void)insertText:(id)string
948 {
949     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; // Otherwise, NSString
950     
951     LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
952     NSString *text;
953     bool isFromInputMethod = _data->_page->selectionState().hasComposition;
954
955     if (isAttributedString) {
956         text = [string string];
957         // We deal with the NSTextInputReplacementRangeAttributeName attribute from NSAttributedString here
958         // simply because it is used by at least one Input Method -- it corresonds to the kEventParamTextInputSendReplaceRange
959         // event in TSM.  This behaviour matches that of -[WebHTMLView setMarkedText:selectedRange:] when it receives an
960         // NSAttributedString
961         NSString *rangeString = [string attribute:NSTextInputReplacementRangeAttributeName atIndex:0 longestEffectiveRange:NULL inRange:NSMakeRange(0, [text length])];
962         LOG(TextInput, "ReplacementRange: %@", rangeString);
963         if (rangeString)
964             isFromInputMethod = YES;
965     } else
966         text = string;
967     
968     String eventText = text;
969     
970     if (!isFromInputMethod)
971         _data->_commandsList.append(KeypressCommand("insertText", text));
972     else {
973         eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
974         _data->_commandsList.append(KeypressCommand("insertText", eventText));
975     }
976 }
977
978 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
979 {
980     if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) != NSCommandKeyMask)
981         return NO;
982     
983     // Here we special case cmd+b and cmd+i but not cmd+u, for historic reason.
984     // This should not be changed, since it could break some Mac applications that
985     // rely on this inherent behavior.
986     // See https://bugs.webkit.org/show_bug.cgi?id=24943
987     
988     NSString *string = [event characters];
989     if ([string caseInsensitiveCompare:@"b"] == NSOrderedSame) {
990         _data->_page->executeEditCommand("ToggleBold");
991         return YES;
992     }
993     if ([string caseInsensitiveCompare:@"i"] == NSOrderedSame) {
994         _data->_page->executeEditCommand("ToggleItalic");
995         return YES;
996     }
997     
998     return NO;
999 }
1000
1001 - (BOOL)performKeyEquivalent:(NSEvent *)event
1002 {
1003     // There's a chance that responding to this event will run a nested event loop, and
1004     // fetching a new event might release the old one. Retaining and then autoreleasing
1005     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1006     [[event retain] autorelease];
1007     
1008     BOOL eventWasSentToWebCore = (_data->_keyDownEventBeingResent == event);
1009
1010     // Pass key combos through WebCore if there is a key binding available for
1011     // this event. This lets web pages have a crack at intercepting key-modified keypresses.
1012     // But don't do it if we have already handled the event.
1013     // Pressing Esc results in a fake event being sent - don't pass it to WebCore.
1014     if (!eventWasSentToWebCore && event == [NSApp currentEvent] && self == [[self window] firstResponder]) {
1015         [_data->_keyDownEventBeingResent release];
1016         _data->_keyDownEventBeingResent = nil;
1017         
1018         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, self));
1019         return YES;
1020     }
1021     
1022     return [self _handleStyleKeyEquivalent:event] || [super performKeyEquivalent:event];
1023 }
1024
1025 - (void)keyUp:(NSEvent *)theEvent
1026 {
1027     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1028 }
1029
1030 - (void)keyDown:(NSEvent *)theEvent
1031 {
1032     if (_data->_pluginComplexTextInputIdentifier) {
1033         // Try feeding the keyboard event directly to the plug-in.
1034         NSString *string = nil;
1035         if ([[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:theEvent string:&string]) {
1036             if (string)
1037                 _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string);
1038             return;
1039         }
1040     }
1041
1042     _data->_underlines.clear();
1043     _data->_selectionStart = 0;
1044     _data->_selectionEnd = 0;
1045     // We could be receiving a key down from AppKit if we have re-sent an event
1046     // that maps to an action that is currently unavailable (for example a copy when
1047     // there is no range selection).
1048     // If this is the case we should ignore the key down.
1049     if (_data->_keyDownEventBeingResent == theEvent) {
1050         [_data->_keyDownEventBeingResent release];
1051         _data->_keyDownEventBeingResent = nil;
1052         [super keyDown:theEvent];
1053         return;
1054     }
1055     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1056 }
1057
1058 - (NSTextInputContext *)inputContext {
1059     if (_data->_pluginComplexTextInputIdentifier)
1060         return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
1061
1062     return [super inputContext];
1063 }
1064
1065 - (NSRange)selectedRange
1066 {
1067     if (_data->_page->selectionState().isNone || !_data->_page->selectionState().isContentEditable)
1068         return NSMakeRange(NSNotFound, 0);
1069     
1070     LOG(TextInput, "selectedRange -> (%u, %u)", _data->_page->selectionState().selectedRangeStart, _data->_page->selectionState().selectedRangeLength);
1071     return NSMakeRange(_data->_page->selectionState().selectedRangeStart, _data->_page->selectionState().selectedRangeLength);
1072 }
1073
1074 - (BOOL)hasMarkedText
1075 {
1076     LOG(TextInput, "hasMarkedText -> %u", _data->_page->selectionState().hasComposition);
1077     return _data->_page->selectionState().hasComposition;
1078 }
1079
1080 - (void)unmarkText
1081 {
1082     LOG(TextInput, "unmarkText");
1083     
1084     _data->_commandsList.append(KeypressCommand("unmarkText"));
1085 }
1086
1087 - (NSArray *)validAttributesForMarkedText
1088 {
1089     static NSArray *validAttributes;
1090     if (!validAttributes) {
1091         validAttributes = [[NSArray alloc] initWithObjects:
1092                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
1093                            NSMarkedClauseSegmentAttributeName, NSTextInputReplacementRangeAttributeName, nil];
1094         // NSText also supports the following attributes, but it's
1095         // hard to tell which are really required for text input to
1096         // work well; I have not seen any input method make use of them yet.
1097         //     NSFontAttributeName, NSForegroundColorAttributeName,
1098         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
1099         CFRetain(validAttributes);
1100     }
1101     LOG(TextInput, "validAttributesForMarkedText -> (...)");
1102     return validAttributes;
1103 }
1104
1105 static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result)
1106 {
1107     int length = [[string string] length];
1108     
1109     int i = 0;
1110     while (i < length) {
1111         NSRange range;
1112         NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)];
1113         
1114         if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
1115             Color color = Color::black;
1116             if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName])
1117                 color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
1118             result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1));
1119         }
1120         
1121         i = range.location + range.length;
1122     }
1123 }
1124
1125 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
1126 {
1127     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; // Otherwise, NSString
1128     
1129     LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelRange.location, newSelRange.length);
1130     
1131     NSString *text = string;
1132     
1133     if (isAttributedString) {
1134         text = [string string];
1135         extractUnderlines(string, _data->_underlines);
1136     }
1137     
1138     _data->_commandsList.append(KeypressCommand("setMarkedText", text));
1139     _data->_selectionStart = newSelRange.location;
1140     _data->_selectionEnd = NSMaxRange(newSelRange);
1141 }
1142
1143 - (NSRange)markedRange
1144 {
1145     uint64_t location;
1146     uint64_t length;
1147
1148     _data->_page->getMarkedRange(location, length);
1149     LOG(TextInput, "markedRange -> (%u, %u)", location, length);
1150     return NSMakeRange(location, length);
1151 }
1152
1153 - (NSAttributedString *)attributedSubstringFromRange:(NSRange)nsRange
1154 {
1155     // This is not implemented for now. Need to figure out how to serialize the attributed string across processes.
1156     LOG(TextInput, "attributedSubstringFromRange");
1157     return nil;
1158 }
1159
1160 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1161 {
1162     NSWindow *window = [self window];
1163     
1164     if (window)
1165         thePoint = [window convertScreenToBase:thePoint];
1166     thePoint = [self convertPoint:thePoint fromView:nil];  // the point is relative to the main frame 
1167     
1168     uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint));
1169     LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result);
1170     return result;
1171 }
1172
1173 - (NSRect)firstRectForCharacterRange:(NSRange)theRange
1174
1175     // Just to match NSTextView's behavior. Regression tests cannot detect this;
1176     // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
1177     // (type something; try ranges (1, -1) and (2, -1).
1178     if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
1179         theRange.length = 0;
1180     
1181     NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange.location, theRange.length);
1182     resultRect = [self convertRect:resultRect toView:nil];
1183     
1184     NSWindow *window = [self window];
1185     if (window)
1186         resultRect.origin = [window convertBaseToScreen:resultRect.origin];
1187     
1188     LOG(TextInput, "firstRectForCharacterRange:(%u, %u) -> (%f, %f, %f, %f)", theRange.location, theRange.length, resultRect.origin.x, resultRect.origin.y, resultRect.size.width, resultRect.size.height);
1189     return resultRect;
1190 }
1191
1192 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
1193 {
1194     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
1195     NSPoint windowMouseLoc = windowImageLoc;
1196    
1197     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
1198     _data->_ignoringMouseDraggedEvents = YES;
1199     
1200     _data->_page->dragEnded(IntPoint(windowMouseLoc), globalPoint(windowMouseLoc, [self window]), operation);
1201 }
1202
1203 - (DragApplicationFlags)applicationFlags:(id <NSDraggingInfo>)draggingInfo
1204 {
1205     uint32_t flags = 0;
1206     if ([NSApp modalWindow])
1207         flags = DragApplicationIsModal;
1208     if ([[self window] attachedSheet])
1209         flags |= DragApplicationHasAttachedSheet;
1210     if ([draggingInfo draggingSource] == self)
1211         flags |= DragApplicationIsSource;
1212     if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1213         flags |= DragApplicationIsCopyKeyDown;
1214     return static_cast<DragApplicationFlags>(flags);
1215 }
1216
1217 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
1218 {
1219     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1220     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1221     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1222
1223     _data->_page->resetDragOperation();
1224     _data->_page->performDragControllerAction(DragControllerActionEntered, &dragData, [[draggingInfo draggingPasteboard] name]);
1225     return NSDragOperationCopy;
1226 }
1227
1228 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
1229 {
1230     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1231     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1232     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1233     _data->_page->performDragControllerAction(DragControllerActionUpdated, &dragData, [[draggingInfo draggingPasteboard] name]);
1234     return _data->_page->dragOperation();
1235 }
1236
1237 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
1238 {
1239     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1240     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1241     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1242     _data->_page->performDragControllerAction(DragControllerActionExited, &dragData, [[draggingInfo draggingPasteboard] name]);
1243     _data->_page->resetDragOperation();
1244 }
1245
1246 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
1247 {
1248     return YES;
1249 }
1250
1251 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
1252 {
1253     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1254     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1255     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1256     _data->_page->performDragControllerAction(DragControllerActionPerformDrag, &dragData, [[draggingInfo draggingPasteboard] name]);
1257     return YES;
1258 }
1259
1260 - (void)_updateWindowVisibility
1261 {
1262     _data->_page->updateWindowIsVisible(![[self window] isMiniaturized]);
1263 }
1264
1265 - (BOOL)_ownsWindowGrowBox
1266 {
1267     NSWindow* window = [self window];
1268     if (!window)
1269         return NO;
1270
1271     NSView *superview = [self superview];
1272     if (!superview)
1273         return NO;
1274
1275     NSRect growBoxRect = [window _growBoxRect];
1276     if (NSIsEmptyRect(growBoxRect))
1277         return NO;
1278
1279     NSRect visibleRect = [self visibleRect];
1280     if (NSIsEmptyRect(visibleRect))
1281         return NO;
1282
1283     NSRect visibleRectInWindowCoords = [self convertRect:visibleRect toView:nil];
1284     if (!NSIntersectsRect(growBoxRect, visibleRectInWindowCoords))
1285         return NO;
1286
1287     return YES;
1288 }
1289
1290 - (BOOL)_updateGrowBoxForWindowFrameChange
1291 {
1292     // Temporarily enable the resize indicator to make a the _ownsWindowGrowBox calculation work.
1293     BOOL wasShowingIndicator = [[self window] showsResizeIndicator];
1294     [[self window] setShowsResizeIndicator:YES];
1295
1296     BOOL ownsGrowBox = [self _ownsWindowGrowBox];
1297     _data->_page->setWindowResizerSize(ownsGrowBox ? enclosingIntRect([[self window] _growBoxRect]).size() : IntSize());
1298     
1299     // Once WebCore can draw the window resizer, this should read:
1300     // if (wasShowingIndicator)
1301     //     [[self window] setShowsResizeIndicator:!ownsGrowBox];
1302     [[self window] setShowsResizeIndicator:wasShowingIndicator];
1303
1304     return ownsGrowBox;
1305 }
1306
1307 - (void)addWindowObserversForWindow:(NSWindow *)window
1308 {
1309     if (window) {
1310         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
1311                                                      name:NSWindowDidBecomeKeyNotification object:nil];
1312         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
1313                                                      name:NSWindowDidResignKeyNotification object:nil];
1314         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) 
1315                                                      name:NSWindowDidMiniaturizeNotification object:window];
1316         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
1317                                                      name:NSWindowDidDeminiaturizeNotification object:window];
1318         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:)
1319                                                      name:NSWindowDidMoveNotification object:window];
1320         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:) 
1321                                                      name:NSWindowDidResizeNotification object:window];
1322     }
1323 }
1324
1325 - (void)removeWindowObservers
1326 {
1327     NSWindow *window = [self window];
1328     if (!window)
1329         return;
1330
1331     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
1332     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
1333     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
1334     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
1335     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
1336     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
1337 }
1338
1339 - (void)viewWillMoveToWindow:(NSWindow *)window
1340 {
1341     if (window != [self window]) {
1342         [self removeWindowObservers];
1343         [self addWindowObserversForWindow:window];
1344     }
1345 }
1346
1347 - (void)viewDidMoveToWindow
1348 {
1349     // We want to make sure to update the active state while hidden, so if the view is about to become visible, we
1350     // update the active state first and then make it visible. If the view is about to be hidden, we hide it first and then
1351     // update the active state.
1352     if ([self window]) {
1353         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1354         _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible | WebPageProxy::ViewIsInWindow);
1355         [self _updateWindowVisibility];
1356         [self _updateWindowAndViewFrames];
1357     } else {
1358         _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1359         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive | WebPageProxy::ViewIsInWindow);
1360
1361 #if ENABLE(GESTURE_EVENTS)
1362         if (_data->_endGestureMonitor) {
1363             [NSEvent removeMonitor:_data->_endGestureMonitor];
1364             _data->_endGestureMonitor = nil;
1365         }
1366 #endif
1367     }
1368     [self _setRemoteAccessibilityWindow:[self window]];
1369 }
1370
1371 - (void)_windowDidBecomeKey:(NSNotification *)notification
1372 {
1373     NSWindow *keyWindow = [notification object];
1374     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
1375         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1376 }
1377
1378 - (void)_windowDidResignKey:(NSNotification *)notification
1379 {
1380     NSWindow *formerKeyWindow = [notification object];
1381     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet])
1382         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1383 }
1384
1385 - (void)_windowDidMiniaturize:(NSNotification *)notification
1386 {
1387     [self _updateWindowVisibility];
1388 }
1389
1390 - (void)_windowDidDeminiaturize:(NSNotification *)notification
1391 {
1392     [self _updateWindowVisibility];
1393 }
1394
1395 - (void)_windowFrameDidChange:(NSNotification *)notification
1396 {
1397     [self _updateWindowAndViewFrames];
1398 }
1399
1400 static void drawPageBackground(CGContextRef context, WebPageProxy* page, const IntRect& rect)
1401 {
1402     if (!page->drawsBackground())
1403         return;
1404
1405     CGContextSaveGState(context);
1406     CGContextSetBlendMode(context, kCGBlendModeCopy);
1407
1408     CGColorRef backgroundColor;
1409     if (page->drawsTransparentBackground())
1410         backgroundColor = CGColorGetConstantColor(kCGColorClear);
1411     else
1412         backgroundColor = CGColorGetConstantColor(kCGColorWhite);
1413
1414     CGContextSetFillColorWithColor(context, backgroundColor);
1415     CGContextFillRect(context, rect);
1416
1417     CGContextRestoreGState(context);
1418 }
1419
1420 - (void)drawRect:(NSRect)rect
1421 {
1422     LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1423     _data->_page->endPrinting();
1424     if (useNewDrawingArea()) {
1425         CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
1426
1427         if (DrawingAreaProxyImpl* drawingArea = static_cast<DrawingAreaProxyImpl*>(_data->_page->drawingArea())) {
1428             const NSRect *rectsBeingDrawn;
1429             NSInteger numRectsBeingDrawn;
1430             [self getRectsBeingDrawn:&rectsBeingDrawn count:&numRectsBeingDrawn];
1431             for (NSInteger i = 0; i < numRectsBeingDrawn; ++i) {
1432                 Region unpaintedRegion;
1433                 IntRect rect = enclosingIntRect(rectsBeingDrawn[i]);
1434                 drawingArea->paint(context, rect, unpaintedRegion);
1435
1436                 Vector<IntRect> unpaintedRects = unpaintedRegion.rects();
1437                 for (size_t i = 0; i < unpaintedRects.size(); ++i)
1438                     drawPageBackground(context, _data->_page.get(), unpaintedRects[i]);
1439             }
1440         } else 
1441             drawPageBackground(context, _data->_page.get(), enclosingIntRect(rect));
1442
1443         _data->_page->didDraw();
1444         return;
1445     }
1446
1447     if (_data->_page->isValid() && _data->_page->drawingArea()) {
1448         CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
1449         _data->_page->drawingArea()->paint(IntRect(rect), context);
1450         _data->_page->didDraw();
1451     } else if (_data->_page->drawsBackground()) {
1452         [_data->_page->drawsTransparentBackground() ? [NSColor clearColor] : [NSColor whiteColor] set];
1453         NSRectFill(rect);
1454     }
1455 }
1456
1457 - (BOOL)isOpaque
1458 {
1459     return _data->_page->drawsBackground();
1460 }
1461
1462 - (void)viewDidHide
1463 {
1464     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1465 }
1466
1467 - (void)viewDidUnhide
1468 {
1469     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1470 }
1471
1472 - (BOOL)accessibilityIsIgnored
1473 {
1474     return NO;
1475 }
1476
1477 - (id)accessibilityHitTest:(NSPoint)point
1478 {
1479     return _data->_remoteAccessibilityChild.get();
1480 }
1481
1482 - (id)accessibilityAttributeValue:(NSString*)attribute
1483 {
1484     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
1485         if (!_data->_remoteAccessibilityChild)
1486             return nil;
1487         return [NSArray arrayWithObject:_data->_remoteAccessibilityChild.get()];
1488     }
1489     if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
1490         return NSAccessibilityGroupRole;
1491     if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
1492         return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil);
1493     if ([attribute isEqualToString:NSAccessibilityParentAttribute])
1494         return NSAccessibilityUnignoredAncestor([self superview]);
1495     if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
1496         return [NSNumber numberWithBool:YES];
1497     
1498     return [super accessibilityAttributeValue:attribute];
1499 }
1500
1501 - (NSView *)hitTest:(NSPoint)point
1502 {
1503     NSView *hitView = [super hitTest:point];
1504 #if USE(ACCELERATED_COMPOSITING)
1505     if (hitView && _data && hitView == _data->_layerHostingView)
1506         hitView = self;
1507 #endif
1508     return hitView;
1509 }
1510
1511 - (NSInteger)conversationIdentifier
1512 {
1513     return (NSInteger)self;
1514 }
1515
1516
1517 - (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef
1518 {
1519     // PDF documents are already paginated, so we can't change them to add headers and footers.
1520     return !toImpl(frameRef)->isMainFrame() || !_data->_pdfViewController;
1521 }
1522
1523 - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef
1524 {
1525     LOG(View, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data());
1526
1527     // Only the top frame can currently contain a PDF view.
1528     if (_data->_pdfViewController) {
1529         if (!toImpl(frameRef)->isMainFrame())
1530             return 0;
1531         return _data->_pdfViewController->makePrintOperation(printInfo);
1532     } else {
1533         RetainPtr<WKPrintingView> printingView(AdoptNS, [[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef)]);
1534         // NSPrintOperation takes ownership of the view.
1535         NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get()];
1536         [printOperation setCanSpawnSeparateThread:YES];
1537         printingView->_printOperation = printOperation;
1538         return printOperation;
1539     }
1540 }
1541
1542 @end
1543
1544 @implementation WKView (Internal)
1545
1546 - (PassOwnPtr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy
1547 {
1548     if (useNewDrawingArea())
1549         return DrawingAreaProxyImpl::create(_data->_page.get());
1550
1551     return ChunkedUpdateDrawingAreaProxy::create(self, _data->_page.get());
1552 }
1553
1554 - (BOOL)_isFocused
1555 {
1556     if (_data->_inBecomeFirstResponder)
1557         return YES;
1558     if (_data->_inResignFirstResponder)
1559         return NO;
1560     return [[self window] firstResponder] == self;
1561 }
1562
1563 - (void)_processDidCrash
1564 {
1565     [self setNeedsDisplay:YES];
1566     [self _setRemoteAccessibilityWindow:nil];
1567 }
1568
1569 - (void)_pageClosed
1570 {
1571     // When the page closes, the references the accessibility child has to the window 
1572     // need to be removed, otherwise it can leak.
1573     [self _setRemoteAccessibilityWindow:nil];
1574 }
1575
1576 - (void)_didRelaunchProcess
1577 {
1578     [self setNeedsDisplay:YES];
1579 }
1580
1581 - (void)_takeFocus:(BOOL)forward
1582 {
1583     if (forward)
1584         [[self window] selectKeyViewFollowingView:self];
1585     else
1586         [[self window] selectKeyViewPrecedingView:self];
1587 }
1588
1589 - (void)_setCursor:(NSCursor *)cursor
1590 {
1591     if ([NSCursor currentCursor] == cursor)
1592         return;
1593     [cursor set];
1594 }
1595
1596 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
1597 {
1598     ValidationVector items = _data->_validationMap.take(commandName);
1599     size_t size = items.size();
1600     for (size_t i = 0; i < size; ++i) {
1601         ValidationItem item = items[i].get();
1602         [menuItem(item) setState:newState];
1603         [menuItem(item) setEnabled:isEnabled];
1604         [toolbarItem(item) setEnabled:isEnabled];
1605         // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
1606     }
1607 }
1608
1609 - (void)_setEventBeingResent:(NSEvent *)event
1610 {
1611     _data->_keyDownEventBeingResent = [event retain];
1612 }
1613
1614 - (Vector<KeypressCommand>&)_interceptKeyEvent:(NSEvent *)theEvent 
1615 {
1616     _data->_commandsList.clear();
1617     // interpretKeyEvents will trigger one or more calls to doCommandBySelector or setText
1618     // that will populate the commandsList vector.
1619     [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
1620     return _data->_commandsList;
1621 }
1622
1623 - (void)_getTextInputState:(unsigned)start selectionEnd:(unsigned)end underlines:(Vector<WebCore::CompositionUnderline>&)lines
1624 {
1625     start = _data->_selectionStart;
1626     end = _data->_selectionEnd;
1627     lines = _data->_underlines;
1628 }
1629
1630 - (NSRect)_convertToDeviceSpace:(NSRect)rect
1631 {
1632     return toDeviceSpace(rect, [self window]);
1633 }
1634
1635 - (NSRect)_convertToUserSpace:(NSRect)rect
1636 {
1637     return toUserSpace(rect, [self window]);
1638 }
1639
1640 // Any non-zero value will do, but using something recognizable might help us debug some day.
1641 #define TRACKING_RECT_TAG 0xBADFACE
1642
1643 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
1644 {
1645     ASSERT(_data->_trackingRectOwner == nil);
1646     _data->_trackingRectOwner = owner;
1647     _data->_trackingRectUserData = data;
1648     return TRACKING_RECT_TAG;
1649 }
1650
1651 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
1652 {
1653     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
1654     ASSERT(_data->_trackingRectOwner == nil);
1655     _data->_trackingRectOwner = owner;
1656     _data->_trackingRectUserData = data;
1657     return TRACKING_RECT_TAG;
1658 }
1659
1660 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
1661 {
1662     ASSERT(count == 1);
1663     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
1664     ASSERT(_data->_trackingRectOwner == nil);
1665     _data->_trackingRectOwner = owner;
1666     _data->_trackingRectUserData = userDataList[0];
1667     trackingNums[0] = TRACKING_RECT_TAG;
1668 }
1669
1670 - (void)removeTrackingRect:(NSTrackingRectTag)tag
1671 {
1672     if (tag == 0)
1673         return;
1674     
1675     if (_data && (tag == TRACKING_RECT_TAG)) {
1676         _data->_trackingRectOwner = nil;
1677         return;
1678     }
1679     
1680     if (_data && (tag == _data->_lastToolTipTag)) {
1681         [super removeTrackingRect:tag];
1682         _data->_lastToolTipTag = 0;
1683         return;
1684     }
1685     
1686     // If any other tracking rect is being removed, we don't know how it was created
1687     // and it's possible there's a leak involved (see 3500217)
1688     ASSERT_NOT_REACHED();
1689 }
1690
1691 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
1692 {
1693     int i;
1694     for (i = 0; i < count; ++i) {
1695         int tag = tags[i];
1696         if (tag == 0)
1697             continue;
1698         ASSERT(tag == TRACKING_RECT_TAG);
1699         if (_data != nil) {
1700             _data->_trackingRectOwner = nil;
1701         }
1702     }
1703 }
1704
1705 - (void)_sendToolTipMouseExited
1706 {
1707     // Nothing matters except window, trackingNumber, and userData.
1708     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
1709         location:NSMakePoint(0, 0)
1710         modifierFlags:0
1711         timestamp:0
1712         windowNumber:[[self window] windowNumber]
1713         context:NULL
1714         eventNumber:0
1715         trackingNumber:TRACKING_RECT_TAG
1716         userData:_data->_trackingRectUserData];
1717     [_data->_trackingRectOwner mouseExited:fakeEvent];
1718 }
1719
1720 - (void)_sendToolTipMouseEntered
1721 {
1722     // Nothing matters except window, trackingNumber, and userData.
1723     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
1724         location:NSMakePoint(0, 0)
1725         modifierFlags:0
1726         timestamp:0
1727         windowNumber:[[self window] windowNumber]
1728         context:NULL
1729         eventNumber:0
1730         trackingNumber:TRACKING_RECT_TAG
1731         userData:_data->_trackingRectUserData];
1732     [_data->_trackingRectOwner mouseEntered:fakeEvent];
1733 }
1734
1735 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
1736 {
1737     return nsStringFromWebCoreString(_data->_page->toolTip());
1738 }
1739
1740 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
1741 {
1742     if (oldToolTip)
1743         [self _sendToolTipMouseExited];
1744
1745     if (newToolTip && [newToolTip length] > 0) {
1746         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
1747         [self removeAllToolTips];
1748         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
1749         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
1750         [self _sendToolTipMouseEntered];
1751     }
1752 }
1753
1754 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut
1755 {
1756     if (!findIndicator) {
1757         _data->_findIndicatorWindow = 0;
1758         return;
1759     }
1760
1761     if (!_data->_findIndicatorWindow)
1762         _data->_findIndicatorWindow = FindIndicatorWindow::create(self);
1763
1764     _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut);
1765 }
1766
1767 #if USE(ACCELERATED_COMPOSITING)
1768 - (void)_startAcceleratedCompositing:(CALayer *)rootLayer
1769 {
1770     if (!_data->_layerHostingView) {
1771         NSView *hostingView = [[NSView alloc] initWithFrame:[self bounds]];
1772 #if !defined(BUILDING_ON_LEOPARD)
1773         [hostingView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
1774 #endif
1775         
1776         [self addSubview:hostingView];
1777         [hostingView release];
1778         _data->_layerHostingView = hostingView;
1779     }
1780
1781     // Make a container layer, which will get sized/positioned by AppKit and CA.
1782     CALayer *viewLayer = [CALayer layer];
1783
1784 #ifndef NDEBUG
1785     [viewLayer setName:@"hosting layer"];
1786 #endif
1787
1788 #if defined(BUILDING_ON_LEOPARD)
1789     // Turn off default animations.
1790     NSNull *nullValue = [NSNull null];
1791     NSDictionary *actions = [NSDictionary dictionaryWithObjectsAndKeys:
1792                              nullValue, @"anchorPoint",
1793                              nullValue, @"bounds",
1794                              nullValue, @"contents",
1795                              nullValue, @"contentsRect",
1796                              nullValue, @"opacity",
1797                              nullValue, @"position",
1798                              nullValue, @"sublayerTransform",
1799                              nullValue, @"sublayers",
1800                              nullValue, @"transform",
1801                              nil];
1802     [viewLayer setStyle:[NSDictionary dictionaryWithObject:actions forKey:@"actions"]];
1803 #endif
1804
1805 #if !defined(BUILDING_ON_LEOPARD)
1806     // If we aren't in the window yet, we'll use the screen's scale factor now, and reset the scale 
1807     // via -viewDidMoveToWindow.
1808     CGFloat scaleFactor = [self window] ? [[self window] userSpaceScaleFactor] : [[NSScreen mainScreen] userSpaceScaleFactor];
1809     [viewLayer setTransform:CATransform3DMakeScale(scaleFactor, scaleFactor, 1)];
1810 #endif
1811
1812     [_data->_layerHostingView setLayer:viewLayer];
1813     [_data->_layerHostingView setWantsLayer:YES];
1814     
1815     // Parent our root layer in the container layer
1816     [viewLayer addSublayer:rootLayer];
1817 }
1818
1819 - (void)_stopAcceleratedCompositing
1820 {
1821     if (_data->_layerHostingView) {
1822         [_data->_layerHostingView setLayer:nil];
1823         [_data->_layerHostingView setWantsLayer:NO];
1824         [_data->_layerHostingView removeFromSuperview];
1825         _data->_layerHostingView = nil;
1826     }
1827 }
1828
1829 - (void)_switchToDrawingAreaTypeIfNecessary:(DrawingAreaInfo::Type)type
1830 {
1831     DrawingAreaInfo::Type existingDrawingAreaType = _data->_page->drawingArea() ? _data->_page->drawingArea()->info().type : DrawingAreaInfo::None;
1832     if (existingDrawingAreaType == type)
1833         return;
1834
1835     OwnPtr<DrawingAreaProxy> newDrawingArea;
1836     switch (type) {
1837         case DrawingAreaInfo::Impl:
1838         case DrawingAreaInfo::None:
1839             break;
1840         case DrawingAreaInfo::ChunkedUpdate: {
1841             newDrawingArea = ChunkedUpdateDrawingAreaProxy::create(self, _data->_page.get());
1842             break;
1843         }
1844         case DrawingAreaInfo::LayerBacked: {
1845             newDrawingArea = LayerBackedDrawingAreaProxy::create(self, _data->_page.get());
1846             break;
1847         }
1848     }
1849
1850     newDrawingArea->setSize(IntSize([self frame].size));
1851
1852     _data->_page->drawingArea()->detachCompositingContext();
1853     _data->_page->setDrawingArea(newDrawingArea.release());
1854 }
1855
1856 - (void)_enterAcceleratedCompositingMode:(const LayerTreeContext&)layerTreeContext
1857 {
1858     // FIXME: Implement.
1859 }
1860
1861 - (void)_exitAcceleratedCompositingMode
1862 {
1863     // FIXME: Implement.
1864 }
1865
1866 - (void)_pageDidEnterAcceleratedCompositing
1867 {
1868     [self _switchToDrawingAreaTypeIfNecessary:DrawingAreaInfo::LayerBacked];
1869 }
1870
1871 - (void)_pageDidLeaveAcceleratedCompositing
1872 {
1873     // FIXME: we may want to avoid flipping back to the non-layer-backed drawing area until the next page load, to avoid thrashing.
1874     [self _switchToDrawingAreaTypeIfNecessary:DrawingAreaInfo::ChunkedUpdate];
1875 }
1876 #endif // USE(ACCELERATED_COMPOSITING)
1877
1878 - (void)_setAccessibilityChildToken:(NSData *)data
1879 {
1880 #if !defined(BUILDING_ON_SNOW_LEOPARD)
1881     _data->_remoteAccessibilityChild = WKAXRemoteElementForToken((CFDataRef)data);
1882     [self _setRemoteAccessibilityWindow:[self window]];
1883 #endif
1884 }
1885
1886 - (void)_setComplexTextInputEnabled:(BOOL)complexTextInputEnabled pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
1887 {
1888     BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
1889
1890     if (complexTextInputEnabled) {
1891         // Check if we're already allowing text input for this plug-in.
1892         if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
1893             return;
1894
1895         _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
1896
1897     } else {
1898         // Check if we got a request to disable complex text input for a plug-in that is not the current plug-in.
1899         if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
1900             return;
1901
1902         _data->_pluginComplexTextInputIdentifier = 0;
1903     }
1904
1905     if (inputSourceChanged) {
1906         // Inform the out of line window that the input source changed.
1907         [[WKTextInputWindowController sharedTextInputWindowController] keyboardInputSourceChanged];
1908     }
1909 }
1910
1911 - (void)_setPageHasCustomRepresentation:(BOOL)pageHasCustomRepresentation
1912 {
1913     _data->_pdfViewController = nullptr;
1914
1915     if (pageHasCustomRepresentation)
1916         _data->_pdfViewController = PDFViewController::create(self);
1917 }
1918
1919 - (void)_didFinishLoadingDataForCustomRepresentation:(const CoreIPC::DataReference&)dataReference
1920 {
1921     ASSERT(_data->_pdfViewController);
1922
1923     _data->_pdfViewController->setPDFDocumentData(_data->_page->mainFrame()->mimeType(), dataReference);
1924 }
1925
1926 - (double)_customRepresentationZoomFactor
1927 {
1928     if (!_data->_pdfViewController)
1929         return 1;
1930
1931     return _data->_pdfViewController->zoomFactor();
1932 }
1933
1934 - (void)_setCustomRepresentationZoomFactor:(double)zoomFactor
1935 {
1936     if (!_data->_pdfViewController)
1937         return;
1938
1939     _data->_pdfViewController->setZoomFactor(zoomFactor);
1940 }
1941
1942 - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag
1943 {
1944     // We need to prevent re-entering this call to avoid crashing in AppKit.
1945     // Given the asynchronous nature of WebKit2 this can now happen.
1946     if (_data->_dragHasStarted)
1947         return;
1948     
1949     _data->_dragHasStarted = YES;
1950     [super dragImage:image
1951                   at:clientPoint
1952               offset:NSZeroSize
1953                event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent
1954           pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
1955               source:self
1956            slideBack:YES];
1957     _data->_dragHasStarted = NO;
1958 }
1959
1960 - (void)_setDrawingAreaSize:(NSSize)size
1961 {
1962     if (!_data->_page->drawingArea())
1963         return;
1964     
1965     _data->_page->drawingArea()->setSize(IntSize(size));
1966 }
1967
1968 @end
1969
1970 @implementation WKView (Private)
1971
1972 - (void)disableFrameSizeUpdates
1973 {
1974     _frameSizeUpdatesDisabledCount++;
1975 }
1976
1977 - (void)enableFrameSizeUpdates
1978 {
1979     if (!_frameSizeUpdatesDisabledCount)
1980         return;
1981     
1982     if (!(--_frameSizeUpdatesDisabledCount))
1983         [self _setDrawingAreaSize:[self frame].size];
1984 }
1985
1986 - (BOOL)frameSizeUpdatesDisabled
1987 {
1988     return _frameSizeUpdatesDisabledCount > 0;
1989 }
1990
1991 @end
1992