REGRESSION (r104727): Strange graphics corruption opening a new tab in Safari
[WebKit-https.git] / Source / WebKit2 / UIProcess / API / mac / WKView.mm
1 /*
2  * Copyright (C) 2010, 2011 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 "AttributedString.h"
30 #import "DataReference.h"
31 #import "DrawingAreaProxyImpl.h"
32 #import "EditorState.h"
33 #import "FindIndicator.h"
34 #import "FindIndicatorWindow.h"
35 #import "LayerTreeContext.h"
36 #import "Logging.h"
37 #import "NativeWebKeyboardEvent.h"
38 #import "NativeWebMouseEvent.h"
39 #import "NativeWebWheelEvent.h"
40 #import "PDFViewController.h"
41 #import "PageClientImpl.h"
42 #import "PasteboardTypes.h"
43 #import "TextChecker.h"
44 #import "TextCheckerState.h"
45 #import "TiledCoreAnimationDrawingAreaProxy.h"
46 #import "WKAPICast.h"
47 #import "WKFullScreenWindowController.h"
48 #import "WKPrintingView.h"
49 #import "WKStringCF.h"
50 #import "WKTextInputWindowController.h"
51 #import "WKViewInternal.h"
52 #import "WKViewPrivate.h"
53 #import "WebContext.h"
54 #import "WebEventFactory.h"
55 #import "WebFullScreenManagerProxy.h"
56 #import "WebPage.h"
57 #import "WebPageProxy.h"
58 #import "WebProcessProxy.h"
59 #import "WebSystemInterface.h"
60 #import <QuartzCore/QuartzCore.h>
61 #import <WebCore/ColorMac.h>
62 #import <WebCore/DragController.h>
63 #import <WebCore/DragData.h>
64 #import <WebCore/DragSession.h>
65 #import <WebCore/FloatRect.h>
66 #import <WebCore/IntRect.h>
67 #import <WebCore/KeyboardEvent.h>
68 #import <WebCore/LocalizedStrings.h>
69 #import <WebCore/PlatformEventFactoryMac.h>
70 #import <WebCore/PlatformScreen.h>
71 #import <WebCore/Region.h>
72 #import <WebCore/RunLoop.h>
73 #import <WebKitSystemInterface.h>
74 #import <wtf/RefPtr.h>
75 #import <wtf/RetainPtr.h>
76
77 /* API internals. */
78 #import "WKBrowsingContextControllerInternal.h"
79 #import "WKBrowsingContextGroupInternal.h"
80 #import "WKProcessGroupInternal.h"
81
82
83 @interface NSApplication (WKNSApplicationDetails)
84 - (void)speakString:(NSString *)string;
85 - (void)_setCurrentEvent:(NSEvent *)event;
86 @end
87
88 @interface NSObject (WKNSTextInputContextDetails)
89 - (BOOL)wantsToHandleMouseEvents;
90 - (BOOL)handleMouseEvent:(NSEvent *)event;
91 @end
92
93 @interface NSWindow (WKNSWindowDetails)
94 - (NSRect)_growBoxRect;
95 - (id)_growBoxOwner;
96 - (void)_setShowOpaqueGrowBoxForOwner:(id)owner;
97 - (BOOL)_updateGrowBoxForWindowFrameChange;
98 - (NSRect)_intersectBottomCornersWithRect:(NSRect)viewRect;
99 - (void)_maskRoundedBottomCorners:(NSRect)clipRect;
100 @end
101
102 using namespace WebKit;
103 using namespace WebCore;
104
105 namespace WebKit {
106
107 typedef id <NSValidatedUserInterfaceItem> ValidationItem;
108 typedef Vector<RetainPtr<ValidationItem> > ValidationVector;
109 typedef HashMap<String, ValidationVector> ValidationMap;
110
111 }
112
113 struct WKViewInterpretKeyEventsParameters {
114     bool eventInterpretationHadSideEffects;
115     bool consumedByIM;
116     bool executingSavedKeypressCommands;
117     Vector<KeypressCommand>* commands;
118 };
119
120 @interface WKView ()
121 - (void)_accessibilityRegisterUIProcessTokens;
122 - (void)_disableComplexTextInputIfNecessary;
123 - (float)_intrinsicDeviceScaleFactor;
124 - (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent;
125 - (void)_setDrawingAreaSize:(NSSize)size;
126 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState;
127 - (BOOL)_shouldUseTiledDrawingArea;
128 @end
129
130 @interface WKViewData : NSObject {
131 @public
132     OwnPtr<PageClientImpl> _pageClient;
133     RefPtr<WebPageProxy> _page;
134     
135     // Cache of the associated WKBrowsingContextController.
136     RetainPtr<WKBrowsingContextController> _browsingContextController;
137
138     // For ToolTips.
139     NSToolTipTag _lastToolTipTag;
140     id _trackingRectOwner;
141     void* _trackingRectUserData;
142
143     RetainPtr<NSView> _layerHostingView;
144
145     RetainPtr<id> _remoteAccessibilityChild;
146     
147     // For asynchronous validation.
148     ValidationMap _validationMap;
149
150     OwnPtr<PDFViewController> _pdfViewController;
151
152     OwnPtr<FindIndicatorWindow> _findIndicatorWindow;
153     // We keep here the event when resending it to
154     // the application to distinguish the case of a new event from one 
155     // that has been already sent to WebCore.
156     RetainPtr<NSEvent> _keyDownEventBeingResent;
157     WKViewInterpretKeyEventsParameters* _interpretKeyEventsParameters;
158
159     NSSize _resizeScrollOffset;
160
161     // The identifier of the plug-in we want to send complex text input to, or 0 if there is none.
162     uint64_t _pluginComplexTextInputIdentifier;
163
164     // The state of complex text input for the plug-in.
165     PluginComplexTextInputState _pluginComplexTextInputState;
166
167     bool _inBecomeFirstResponder;
168     bool _inResignFirstResponder;
169     NSEvent *_mouseDownEvent;
170     BOOL _ignoringMouseDraggedEvents;
171     BOOL _dragHasStarted;
172
173     id _flagsChangedEventMonitor;
174 #if ENABLE(GESTURE_EVENTS)
175     id _endGestureMonitor;
176 #endif
177     
178 #if ENABLE(FULLSCREEN_API)
179     RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
180 #endif
181
182     BOOL _hasSpellCheckerDocumentTag;
183     NSInteger _spellCheckerDocumentTag;
184
185     BOOL _inSecureInputState;
186
187     NSRect _windowBottomCornerIntersectionRect;
188     
189     unsigned _frameSizeUpdatesDisabledCount;
190
191     // Whether the containing window of the WKView has a valid backing store.
192     // The window server invalidates the backing store whenever the window is resized or minimized.
193     // We use this flag to determine when we need to paint the background (white or clear)
194     // when the web process is unresponsive or takes too long to paint.
195     BOOL _windowHasValidBackingStore;
196 }
197
198 @end
199
200 @implementation WKViewData
201 @end
202
203
204 @interface WKResponderChainSink : NSResponder {
205     NSResponder *_lastResponderInChain;
206     bool _didReceiveUnhandledCommand;
207 }
208 - (id)initWithResponderChain:(NSResponder *)chain;
209 - (void)detach;
210 - (bool)didReceiveUnhandledCommand;
211 @end
212
213 @interface WKFlippedView : NSView
214 @end
215
216 @implementation WKFlippedView
217
218 - (BOOL)isFlipped
219 {
220     return YES;
221 }
222
223 @end
224
225 @implementation WKView
226
227 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup
228 {
229     return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef];
230 }
231
232 - (void)dealloc
233 {
234     _data->_page->close();
235
236     ASSERT(!_data->_inSecureInputState);
237
238     [_data release];
239     _data = nil;
240
241     WebContext::statistics().wkViewCount--;
242
243     [super dealloc];
244 }
245
246 - (WKBrowsingContextController *)browsingContextController
247 {
248     if (!_data->_browsingContextController)
249         _data->_browsingContextController.adoptNS([[WKBrowsingContextController alloc] _initWithPageRef:[self pageRef]]);
250     return _data->_browsingContextController.get();
251 }
252
253 - (void)setDrawsBackground:(BOOL)drawsBackground
254 {
255     _data->_page->setDrawsBackground(drawsBackground);
256 }
257
258 - (BOOL)drawsBackground
259 {
260     return _data->_page->drawsBackground();
261 }
262
263 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
264 {
265     _data->_page->setDrawsTransparentBackground(drawsTransparentBackground);
266 }
267
268 - (BOOL)drawsTransparentBackground
269 {
270     return _data->_page->drawsTransparentBackground();
271 }
272
273 - (BOOL)acceptsFirstResponder
274 {
275     return YES;
276 }
277
278 - (BOOL)becomeFirstResponder
279 {
280     NSSelectionDirection direction = [[self window] keyViewSelectionDirection];
281
282     _data->_inBecomeFirstResponder = true;
283     
284     [self _updateSecureInputState];
285     _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
286
287     _data->_inBecomeFirstResponder = false;
288     
289     if (direction != NSDirectSelection) {
290         NSEvent *event = [NSApp currentEvent];
291         NSEvent *keyboardEvent = nil;
292         if ([event type] == NSKeyDown || [event type] == NSKeyUp)
293             keyboardEvent = event;
294         _data->_page->setInitialFocus(direction == NSSelectingNext, keyboardEvent != nil, NativeWebKeyboardEvent(keyboardEvent, self));
295     }
296     return YES;
297 }
298
299 - (BOOL)resignFirstResponder
300 {
301     _data->_inResignFirstResponder = true;
302
303     if (_data->_page->editorState().hasComposition && !_data->_page->editorState().shouldIgnoreCompositionSelectionChange)
304         _data->_page->cancelComposition();
305     [self _resetTextInputState];
306     
307     if (!_data->_page->maintainsInactiveSelection())
308         _data->_page->clearSelection();
309     
310     _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
311
312     _data->_inResignFirstResponder = false;
313
314     return YES;
315 }
316
317 - (void)viewWillStartLiveResize
318 {
319     _data->_page->viewWillStartLiveResize();
320 }
321
322 - (void)viewDidEndLiveResize
323 {
324     _data->_page->viewWillEndLiveResize();
325 }
326
327 - (BOOL)isFlipped
328 {
329     return YES;
330 }
331
332 - (void)setFrameSize:(NSSize)size
333 {
334     if (!NSEqualSizes(size, [self frame].size))
335         _data->_windowHasValidBackingStore = NO;
336
337     [super setFrameSize:size];
338     
339     if (![self frameSizeUpdatesDisabled])
340         [self _setDrawingAreaSize:size];
341 }
342
343 - (void)_updateWindowAndViewFrames
344 {
345     NSWindow *window = [self window];
346     ASSERT(window);
347     
348     NSRect windowFrameInScreenCoordinates = [window frame];
349     NSRect viewFrameInWindowCoordinates = [self convertRect:[self frame] toView:nil];
350     NSPoint accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue];
351     
352     _data->_page->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates), IntPoint(accessibilityPosition));
353 }
354
355 - (void)renewGState
356 {
357     // Hide the find indicator.
358     _data->_findIndicatorWindow = nullptr;
359
360     // Update the view frame.
361     if ([self window])
362         [self _updateWindowAndViewFrames];
363
364     [super renewGState];
365 }
366
367 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState
368 {
369     _data->_pluginComplexTextInputState = pluginComplexTextInputState;
370     
371     if (_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled)
372         return;
373
374     // Send back an empty string to the plug-in. This will disable text input.
375     _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, String());
376 }
377
378 typedef HashMap<SEL, String> SelectorNameMap;
379
380 // Map selectors into Editor command names.
381 // This is not needed for any selectors that have the same name as the Editor command.
382 static const SelectorNameMap* createSelectorExceptionMap()
383 {
384     SelectorNameMap* map = new HashMap<SEL, String>;
385     
386     map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
387     map->add(@selector(insertParagraphSeparator:), "InsertNewline");
388     map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
389     map->add(@selector(pageDown:), "MovePageDown");
390     map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
391     map->add(@selector(pageUp:), "MovePageUp");
392     map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
393     map->add(@selector(scrollPageDown:), "ScrollPageForward");
394     map->add(@selector(scrollPageUp:), "ScrollPageBackward");
395     
396     return map;
397 }
398
399 static String commandNameForSelector(SEL selector)
400 {
401     // Check the exception map first.
402     static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
403     SelectorNameMap::const_iterator it = exceptionMap->find(selector);
404     if (it != exceptionMap->end())
405         return it->second;
406     
407     // Remove the trailing colon.
408     // No need to capitalize the command name since Editor command names are
409     // not case sensitive.
410     const char* selectorName = sel_getName(selector);
411     size_t selectorNameLength = strlen(selectorName);
412     if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
413         return String();
414     return String(selectorName, selectorNameLength - 1);
415 }
416
417 // Editing commands
418
419 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
420
421 WEBCORE_COMMAND(alignCenter)
422 WEBCORE_COMMAND(alignJustified)
423 WEBCORE_COMMAND(alignLeft)
424 WEBCORE_COMMAND(alignRight)
425 WEBCORE_COMMAND(copy)
426 WEBCORE_COMMAND(cut)
427 WEBCORE_COMMAND(delete)
428 WEBCORE_COMMAND(deleteBackward)
429 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
430 WEBCORE_COMMAND(deleteForward)
431 WEBCORE_COMMAND(deleteToBeginningOfLine)
432 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
433 WEBCORE_COMMAND(deleteToEndOfLine)
434 WEBCORE_COMMAND(deleteToEndOfParagraph)
435 WEBCORE_COMMAND(deleteToMark)
436 WEBCORE_COMMAND(deleteWordBackward)
437 WEBCORE_COMMAND(deleteWordForward)
438 WEBCORE_COMMAND(ignoreSpelling)
439 WEBCORE_COMMAND(indent)
440 WEBCORE_COMMAND(insertBacktab)
441 WEBCORE_COMMAND(insertLineBreak)
442 WEBCORE_COMMAND(insertNewline)
443 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
444 WEBCORE_COMMAND(insertParagraphSeparator)
445 WEBCORE_COMMAND(insertTab)
446 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
447 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
448 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
449 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
450 WEBCORE_COMMAND(moveBackward)
451 WEBCORE_COMMAND(moveBackwardAndModifySelection)
452 WEBCORE_COMMAND(moveDown)
453 WEBCORE_COMMAND(moveDownAndModifySelection)
454 WEBCORE_COMMAND(moveForward)
455 WEBCORE_COMMAND(moveForwardAndModifySelection)
456 WEBCORE_COMMAND(moveLeft)
457 WEBCORE_COMMAND(moveLeftAndModifySelection)
458 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
459 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
460 WEBCORE_COMMAND(moveRight)
461 WEBCORE_COMMAND(moveRightAndModifySelection)
462 WEBCORE_COMMAND(moveToBeginningOfDocument)
463 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
464 WEBCORE_COMMAND(moveToBeginningOfLine)
465 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
466 WEBCORE_COMMAND(moveToBeginningOfParagraph)
467 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
468 WEBCORE_COMMAND(moveToBeginningOfSentence)
469 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
470 WEBCORE_COMMAND(moveToEndOfDocument)
471 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
472 WEBCORE_COMMAND(moveToEndOfLine)
473 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
474 WEBCORE_COMMAND(moveToEndOfParagraph)
475 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
476 WEBCORE_COMMAND(moveToEndOfSentence)
477 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
478 WEBCORE_COMMAND(moveToLeftEndOfLine)
479 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
480 WEBCORE_COMMAND(moveToRightEndOfLine)
481 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
482 WEBCORE_COMMAND(moveUp)
483 WEBCORE_COMMAND(moveUpAndModifySelection)
484 WEBCORE_COMMAND(moveWordBackward)
485 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
486 WEBCORE_COMMAND(moveWordForward)
487 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
488 WEBCORE_COMMAND(moveWordLeft)
489 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
490 WEBCORE_COMMAND(moveWordRight)
491 WEBCORE_COMMAND(moveWordRightAndModifySelection)
492 WEBCORE_COMMAND(outdent)
493 WEBCORE_COMMAND(pageDown)
494 WEBCORE_COMMAND(pageDownAndModifySelection)
495 WEBCORE_COMMAND(pageUp)
496 WEBCORE_COMMAND(pageUpAndModifySelection)
497 WEBCORE_COMMAND(paste)
498 WEBCORE_COMMAND(pasteAsPlainText)
499 WEBCORE_COMMAND(scrollPageDown)
500 WEBCORE_COMMAND(scrollPageUp)
501 WEBCORE_COMMAND(scrollLineDown)
502 WEBCORE_COMMAND(scrollLineUp)
503 WEBCORE_COMMAND(scrollToBeginningOfDocument)
504 WEBCORE_COMMAND(scrollToEndOfDocument)
505 WEBCORE_COMMAND(selectAll)
506 WEBCORE_COMMAND(selectLine)
507 WEBCORE_COMMAND(selectParagraph)
508 WEBCORE_COMMAND(selectSentence)
509 WEBCORE_COMMAND(selectToMark)
510 WEBCORE_COMMAND(selectWord)
511 WEBCORE_COMMAND(setMark)
512 WEBCORE_COMMAND(subscript)
513 WEBCORE_COMMAND(superscript)
514 WEBCORE_COMMAND(swapWithMark)
515 WEBCORE_COMMAND(takeFindStringFromSelection)
516 WEBCORE_COMMAND(transpose)
517 WEBCORE_COMMAND(underline)
518 WEBCORE_COMMAND(unscript)
519 WEBCORE_COMMAND(yank)
520 WEBCORE_COMMAND(yankAndSelect)
521
522 #undef WEBCORE_COMMAND
523
524 // This method is needed to support Mac OS X services.
525
526 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
527 {
528     Vector<String> pasteboardTypes;
529     size_t numTypes = [types count];
530     for (size_t i = 0; i < numTypes; ++i)
531         pasteboardTypes.append([types objectAtIndex:i]);
532     return _data->_page->writeSelectionToPasteboard([pasteboard name], pasteboardTypes);
533 }
534
535 - (void)centerSelectionInVisibleArea:(id)sender 
536
537     _data->_page->centerSelectionInVisibleArea();
538 }
539
540 // This method is needed to support Mac OS X services.
541
542 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
543 {
544     BOOL isValidSendType = !sendType || ([PasteboardTypes::forSelection() containsObject:sendType] && !_data->_page->editorState().selectionIsNone);
545     BOOL isValidReturnType = NO;
546     if (!returnType)
547         isValidReturnType = YES;
548     else if ([PasteboardTypes::forEditing() containsObject:returnType] && _data->_page->editorState().isContentEditable) {
549         // We can insert strings in any editable context.  We can insert other types, like images, only in rich edit contexts.
550         isValidReturnType = _data->_page->editorState().isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType];
551     }
552     if (isValidSendType && isValidReturnType)
553         return self;
554     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
555 }
556
557 // This method is needed to support Mac OS X services.
558
559 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard 
560 {
561     return _data->_page->readSelectionFromPasteboard([pasteboard name]);
562 }
563
564 /*
565
566 When possible, editing-related methods should be implemented in WebCore with the
567 EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing
568 individual methods here with Mac-specific code.
569
570 Editing-related methods still unimplemented that are implemented in WebKit1:
571
572 - (void)capitalizeWord:(id)sender;
573 - (void)changeFont:(id)sender;
574 - (void)complete:(id)sender;
575 - (void)copyFont:(id)sender;
576 - (void)lowercaseWord:(id)sender;
577 - (void)makeBaseWritingDirectionLeftToRight:(id)sender;
578 - (void)makeBaseWritingDirectionNatural:(id)sender;
579 - (void)makeBaseWritingDirectionRightToLeft:(id)sender;
580 - (void)pasteFont:(id)sender;
581 - (void)scrollLineDown:(id)sender;
582 - (void)scrollLineUp:(id)sender;
583 - (void)showGuessPanel:(id)sender;
584 - (void)uppercaseWord:(id)sender;
585
586 Some other editing-related methods still unimplemented:
587
588 - (void)changeCaseOfLetter:(id)sender;
589 - (void)copyRuler:(id)sender;
590 - (void)insertContainerBreak:(id)sender;
591 - (void)insertDoubleQuoteIgnoringSubstitution:(id)sender;
592 - (void)insertSingleQuoteIgnoringSubstitution:(id)sender;
593 - (void)pasteRuler:(id)sender;
594 - (void)toggleRuler:(id)sender;
595 - (void)transposeWords:(id)sender;
596
597 */
598
599 // Menu items validation
600
601 static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item)
602 {
603     if (![(NSObject *)item isKindOfClass:[NSMenuItem class]])
604         return nil;
605     return (NSMenuItem *)item;
606 }
607
608 static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item)
609 {
610     if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]])
611         return nil;
612     return (NSToolbarItem *)item;
613 }
614
615 static void validateCommandCallback(WKStringRef commandName, bool isEnabled, int32_t state, WKErrorRef error, void* context)
616 {
617     // If the process exits before the command can be validated, we'll be called back with an error.
618     if (error)
619         return;
620     
621     WKView* wkView = static_cast<WKView*>(context);
622     ASSERT(wkView);
623     
624     [wkView _setUserInterfaceItemState:nsStringFromWebCoreString(toImpl(commandName)->string()) enabled:isEnabled state:state];
625 }
626
627 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
628 {
629     SEL action = [item action];
630
631     if (action == @selector(showGuessPanel:)) {
632         if (NSMenuItem *menuItem = ::menuItem(item))
633             [menuItem setTitle:contextMenuItemTagShowSpellingPanel(![[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible])];
634         return _data->_page->editorState().isContentEditable;
635     }
636
637     if (action == @selector(checkSpelling:) || action == @selector(changeSpelling:))
638         return _data->_page->editorState().isContentEditable;
639
640     if (action == @selector(toggleContinuousSpellChecking:)) {
641         bool enabled = TextChecker::isContinuousSpellCheckingAllowed();
642         bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled;
643         [menuItem(item) setState:checked ? NSOnState : NSOffState];
644         return enabled;
645     }
646
647     if (action == @selector(toggleGrammarChecking:)) {
648         bool checked = TextChecker::state().isGrammarCheckingEnabled;
649         [menuItem(item) setState:checked ? NSOnState : NSOffState];
650         return YES;
651     }
652
653     if (action == @selector(toggleAutomaticSpellingCorrection:)) {
654         bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled;
655         [menuItem(item) setState:checked ? NSOnState : NSOffState];
656         return _data->_page->editorState().isContentEditable;
657     }
658
659     if (action == @selector(orderFrontSubstitutionsPanel:)) {
660         if (NSMenuItem *menuItem = ::menuItem(item))
661             [menuItem setTitle:contextMenuItemTagShowSubstitutions(![[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible])];
662         return _data->_page->editorState().isContentEditable;
663     }
664
665     if (action == @selector(toggleSmartInsertDelete:)) {
666         bool checked = _data->_page->isSmartInsertDeleteEnabled();
667         [menuItem(item) setState:checked ? NSOnState : NSOffState];
668         return _data->_page->editorState().isContentEditable;
669     }
670
671     if (action == @selector(toggleAutomaticQuoteSubstitution:)) {
672         bool checked = TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
673         [menuItem(item) setState:checked ? NSOnState : NSOffState];
674         return _data->_page->editorState().isContentEditable;
675     }
676
677     if (action == @selector(toggleAutomaticDashSubstitution:)) {
678         bool checked = TextChecker::state().isAutomaticDashSubstitutionEnabled;
679         [menuItem(item) setState:checked ? NSOnState : NSOffState];
680         return _data->_page->editorState().isContentEditable;
681     }
682
683     if (action == @selector(toggleAutomaticLinkDetection:)) {
684         bool checked = TextChecker::state().isAutomaticLinkDetectionEnabled;
685         [menuItem(item) setState:checked ? NSOnState : NSOffState];
686         return _data->_page->editorState().isContentEditable;
687     }
688
689     if (action == @selector(toggleAutomaticTextReplacement:)) {
690         bool checked = TextChecker::state().isAutomaticTextReplacementEnabled;
691         [menuItem(item) setState:checked ? NSOnState : NSOffState];
692         return _data->_page->editorState().isContentEditable;
693     }
694
695     if (action == @selector(uppercaseWord:) || action == @selector(lowercaseWord:) || action == @selector(capitalizeWord:))
696         return _data->_page->editorState().selectionIsRange && _data->_page->editorState().isContentEditable;
697     
698     if (action == @selector(stopSpeaking:))
699         return [NSApp isSpeaking];
700     
701     // The centerSelectionInVisibleArea: selector is enabled if there's a selection range or if there's an insertion point in an editable area.
702     if (action == @selector(centerSelectionInVisibleArea:))
703         return _data->_page->editorState().selectionIsRange || (_data->_page->editorState().isContentEditable && !_data->_page->editorState().selectionIsNone);
704
705     // Next, handle editor commands. Start by returning YES for anything that is not an editor command.
706     // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized.
707     String commandName = commandNameForSelector([item action]);
708     if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName))
709         return YES;
710
711     // Add this item to the vector of items for a given command that are awaiting validation.
712     pair<ValidationMap::iterator, bool> addResult = _data->_validationMap.add(commandName, ValidationVector());
713     addResult.first->second.append(item);
714     if (addResult.second) {
715         // If we are not already awaiting validation for this command, start the asynchronous validation process.
716         // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
717         // we asked for the same command; there is no guarantee the answer is still valid.
718         _data->_page->validateCommand(commandName, ValidateCommandCallback::create(self, validateCommandCallback));
719     }
720
721     // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called.
722     // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment.
723     // But returning NO here would be worse; that would make keyboard commands such as command-C fail.
724     return YES;
725 }
726
727 static void speakString(WKStringRef string, WKErrorRef error, void*)
728 {
729     if (error)
730         return;
731     if (!string)
732         return;
733
734     NSString *convertedString = toImpl(string)->string();
735     [NSApp speakString:convertedString];
736 }
737
738 - (IBAction)startSpeaking:(id)sender
739 {
740     _data->_page->getSelectionOrContentsAsString(StringCallback::create(0, speakString));
741 }
742
743 - (IBAction)stopSpeaking:(id)sender
744 {
745     [NSApp stopSpeaking:sender];
746 }
747
748 - (IBAction)showGuessPanel:(id)sender
749 {
750     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
751     if (!checker) {
752         LOG_ERROR("No NSSpellChecker");
753         return;
754     }
755     
756     NSPanel *spellingPanel = [checker spellingPanel];
757     if ([spellingPanel isVisible]) {
758         [spellingPanel orderOut:sender];
759         return;
760     }
761     
762     _data->_page->advanceToNextMisspelling(true);
763     [spellingPanel orderFront:sender];
764 }
765
766 - (IBAction)checkSpelling:(id)sender
767 {
768     _data->_page->advanceToNextMisspelling(false);
769 }
770
771 - (void)changeSpelling:(id)sender
772 {
773     NSString *word = [[sender selectedCell] stringValue];
774
775     _data->_page->changeSpellingToWord(word);
776 }
777
778 - (IBAction)toggleContinuousSpellChecking:(id)sender
779 {
780     bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled;
781     TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled);
782
783     _data->_page->process()->updateTextCheckerState();
784 }
785
786 - (BOOL)isGrammarCheckingEnabled
787 {
788     return TextChecker::state().isGrammarCheckingEnabled;
789 }
790
791 - (void)setGrammarCheckingEnabled:(BOOL)flag
792 {
793     if (static_cast<bool>(flag) == TextChecker::state().isGrammarCheckingEnabled)
794         return;
795     
796     TextChecker::setGrammarCheckingEnabled(flag);
797     _data->_page->process()->updateTextCheckerState();
798 }
799
800 - (IBAction)toggleGrammarChecking:(id)sender
801 {
802     bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled;
803     TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled);
804
805     _data->_page->process()->updateTextCheckerState();
806 }
807
808 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
809 {
810     TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
811
812     _data->_page->process()->updateTextCheckerState();
813 }
814
815 - (void)orderFrontSubstitutionsPanel:(id)sender
816 {
817     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
818     if (!checker) {
819         LOG_ERROR("No NSSpellChecker");
820         return;
821     }
822     
823     NSPanel *substitutionsPanel = [checker substitutionsPanel];
824     if ([substitutionsPanel isVisible]) {
825         [substitutionsPanel orderOut:sender];
826         return;
827     }
828     [substitutionsPanel orderFront:sender];
829 }
830
831 - (IBAction)toggleSmartInsertDelete:(id)sender
832 {
833     _data->_page->setSmartInsertDeleteEnabled(!_data->_page->isSmartInsertDeleteEnabled());
834 }
835
836 - (BOOL)isAutomaticQuoteSubstitutionEnabled
837 {
838     return TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
839 }
840
841 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
842 {
843     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticQuoteSubstitutionEnabled)
844         return;
845
846     TextChecker::setAutomaticQuoteSubstitutionEnabled(flag);
847     _data->_page->process()->updateTextCheckerState();
848 }
849
850 - (void)toggleAutomaticQuoteSubstitution:(id)sender
851 {
852     TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled);
853     _data->_page->process()->updateTextCheckerState();
854 }
855
856 - (BOOL)isAutomaticDashSubstitutionEnabled
857 {
858     return TextChecker::state().isAutomaticDashSubstitutionEnabled;
859 }
860
861 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
862 {
863     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticDashSubstitutionEnabled)
864         return;
865
866     TextChecker::setAutomaticDashSubstitutionEnabled(flag);
867     _data->_page->process()->updateTextCheckerState();
868 }
869
870 - (void)toggleAutomaticDashSubstitution:(id)sender
871 {
872     TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled);
873     _data->_page->process()->updateTextCheckerState();
874 }
875
876 - (BOOL)isAutomaticLinkDetectionEnabled
877 {
878     return TextChecker::state().isAutomaticLinkDetectionEnabled;
879 }
880
881 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
882 {
883     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticLinkDetectionEnabled)
884         return;
885
886     TextChecker::setAutomaticLinkDetectionEnabled(flag);
887     _data->_page->process()->updateTextCheckerState();
888 }
889
890 - (void)toggleAutomaticLinkDetection:(id)sender
891 {
892     TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled);
893     _data->_page->process()->updateTextCheckerState();
894 }
895
896 - (BOOL)isAutomaticTextReplacementEnabled
897 {
898     return TextChecker::state().isAutomaticTextReplacementEnabled;
899 }
900
901 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
902 {
903     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticTextReplacementEnabled)
904         return;
905
906     TextChecker::setAutomaticTextReplacementEnabled(flag);
907     _data->_page->process()->updateTextCheckerState();
908 }
909
910 - (void)toggleAutomaticTextReplacement:(id)sender
911 {
912     TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled);
913     _data->_page->process()->updateTextCheckerState();
914 }
915
916 - (void)uppercaseWord:(id)sender
917 {
918     _data->_page->uppercaseWord();
919 }
920
921 - (void)lowercaseWord:(id)sender
922 {
923     _data->_page->lowercaseWord();
924 }
925
926 - (void)capitalizeWord:(id)sender
927 {
928     _data->_page->capitalizeWord();
929 }
930
931 - (void)displayIfNeeded
932 {
933 #if !defined(BUILDING_ON_SNOW_LEOPARD)
934     // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. In the meantime,
935     // it is necessary to disable scren updates so we get a chance to redraw the corners before this 
936     // display is visible.
937     NSWindow *window = [self window];
938     BOOL shouldMaskWindow = window && !NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect);
939     if (shouldMaskWindow)
940         NSDisableScreenUpdates();
941 #endif
942
943     [super displayIfNeeded];
944
945 #if !defined(BUILDING_ON_SNOW_LEOPARD)
946     if (shouldMaskWindow) {
947         [window _maskRoundedBottomCorners:_data->_windowBottomCornerIntersectionRect];
948         NSEnableScreenUpdates();
949         _data->_windowBottomCornerIntersectionRect = NSZeroRect;
950     }
951 #endif
952 }
953
954 // Events
955
956 // Override this so that AppKit will send us arrow keys as key down events so we can
957 // support them via the key bindings mechanism.
958 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
959 {
960     return YES;
961 }
962
963 - (void)_setMouseDownEvent:(NSEvent *)event
964 {
965     ASSERT(!event || [event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
966     
967     if (event == _data->_mouseDownEvent)
968         return;
969     
970     [_data->_mouseDownEvent release];
971     _data->_mouseDownEvent = [event retain];
972 }
973
974 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
975     - (void)Selector:(NSEvent *)theEvent \
976     { \
977         if ([[self inputContext] handleEvent:theEvent]) { \
978             LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
979             return; \
980         } \
981         NativeWebMouseEvent webEvent(theEvent, self); \
982         _data->_page->handleMouseEvent(webEvent); \
983     }
984
985 NATIVE_MOUSE_EVENT_HANDLER(mouseEntered)
986 NATIVE_MOUSE_EVENT_HANDLER(mouseExited)
987 NATIVE_MOUSE_EVENT_HANDLER(mouseMovedInternal)
988 NATIVE_MOUSE_EVENT_HANDLER(mouseDownInternal)
989 NATIVE_MOUSE_EVENT_HANDLER(mouseUpInternal)
990 NATIVE_MOUSE_EVENT_HANDLER(mouseDraggedInternal)
991 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDown)
992 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDragged)
993 NATIVE_MOUSE_EVENT_HANDLER(otherMouseMoved)
994 NATIVE_MOUSE_EVENT_HANDLER(otherMouseUp)
995 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDown)
996 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDragged)
997 NATIVE_MOUSE_EVENT_HANDLER(rightMouseUp)
998
999 #undef NATIVE_MOUSE_EVENT_HANDLER
1000
1001 #define NATIVE_EVENT_HANDLER(Selector, Type) \
1002     - (void)Selector:(NSEvent *)theEvent \
1003     { \
1004         NativeWeb##Type##Event webEvent = NativeWeb##Type##Event(theEvent, self); \
1005         _data->_page->handle##Type##Event(webEvent); \
1006     }
1007
1008 NATIVE_EVENT_HANDLER(scrollWheel, Wheel)
1009
1010 #undef NATIVE_EVENT_HANDLER
1011
1012 - (void)mouseMoved:(NSEvent *)event
1013 {
1014     // When a view is first responder, it gets mouse moved events even when the mouse is outside its visible rect.
1015     if (self == [[self window] firstResponder] && !NSPointInRect([self convertPoint:[event locationInWindow] fromView:nil], [self visibleRect]))
1016         return;
1017
1018     [self mouseMovedInternal:event];
1019 }
1020
1021 - (void)mouseDown:(NSEvent *)event
1022 {
1023     [self _setMouseDownEvent:event];
1024     _data->_ignoringMouseDraggedEvents = NO;
1025     _data->_dragHasStarted = NO;
1026     [self mouseDownInternal:event];
1027 }
1028
1029 - (void)mouseUp:(NSEvent *)event
1030 {
1031     [self _setMouseDownEvent:nil];
1032     [self mouseUpInternal:event];
1033 }
1034
1035 - (void)mouseDragged:(NSEvent *)event
1036 {
1037     if (_data->_ignoringMouseDraggedEvents)
1038         return;
1039     [self mouseDraggedInternal:event];
1040 }
1041
1042 - (BOOL)acceptsFirstMouse:(NSEvent *)event
1043 {
1044     // There's a chance that responding to this event will run a nested event loop, and
1045     // fetching a new event might release the old one. Retaining and then autoreleasing
1046     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1047     [[event retain] autorelease];
1048     
1049     if (![self hitTest:[event locationInWindow]])
1050         return NO;
1051     
1052     [self _setMouseDownEvent:event];
1053     bool result = _data->_page->acceptsFirstMouse([event eventNumber], WebEventFactory::createWebMouseEvent(event, self));
1054     [self _setMouseDownEvent:nil];
1055     return result;
1056 }
1057
1058 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
1059 {
1060     // If this is the active window or we don't have a range selection, there is no need to perform additional checks
1061     // and we can avoid making a synchronous call to the WebProcess.
1062     if ([[self window] isKeyWindow] || _data->_page->editorState().selectionIsNone || !_data->_page->editorState().selectionIsRange)
1063         return NO;
1064
1065     // There's a chance that responding to this event will run a nested event loop, and
1066     // fetching a new event might release the old one. Retaining and then autoreleasing
1067     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1068     [[event retain] autorelease];
1069     
1070     if (![self hitTest:[event locationInWindow]])
1071         return NO;
1072     
1073     [self _setMouseDownEvent:event];
1074     bool result = _data->_page->shouldDelayWindowOrderingForEvent(WebEventFactory::createWebMouseEvent(event, self));
1075     [self _setMouseDownEvent:nil];
1076     return result;
1077 }
1078
1079 #if ENABLE(GESTURE_EVENTS)
1080
1081 static const short kIOHIDEventTypeScroll = 6;
1082
1083 - (void)shortCircuitedEndGestureWithEvent:(NSEvent *)event
1084 {
1085     if ([event subtype] != kIOHIDEventTypeScroll)
1086         return;
1087
1088     WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
1089     _data->_page->handleGestureEvent(webEvent);
1090
1091     if (_data->_endGestureMonitor) {
1092         [NSEvent removeMonitor:_data->_endGestureMonitor];
1093         _data->_endGestureMonitor = nil;
1094     }
1095 }
1096
1097 - (void)beginGestureWithEvent:(NSEvent *)event
1098 {
1099     if ([event subtype] != kIOHIDEventTypeScroll)
1100         return;
1101
1102     WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
1103     _data->_page->handleGestureEvent(webEvent);
1104
1105     if (!_data->_endGestureMonitor) {
1106         _data->_endGestureMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskEndGesture handler:^(NSEvent *blockEvent) {
1107             [self shortCircuitedEndGestureWithEvent:blockEvent];
1108             return blockEvent;
1109         }];
1110     }
1111 }
1112 #endif
1113
1114 - (void)doCommandBySelector:(SEL)selector
1115 {
1116     LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector));
1117
1118     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1119     if (parameters)
1120         parameters->consumedByIM = false;
1121
1122     // As in insertText:replacementRange:, we assume that the call comes from an input method if there is marked text.
1123     bool isFromInputMethod = _data->_page->editorState().hasComposition;
1124
1125     if (parameters && !isFromInputMethod)
1126         parameters->commands->append(KeypressCommand(NSStringFromSelector(selector)));
1127     else {
1128         // FIXME: Send the command to Editor synchronously and only send it along the
1129         // responder chain if it's a selector that does not correspond to an editing command.
1130         [super doCommandBySelector:selector];
1131     }
1132 }
1133
1134 - (void)insertText:(id)string
1135 {
1136     // Unlike and NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context,
1137     // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText
1138     // command ensures that a keypress event is dispatched as appropriate.
1139     [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
1140 }
1141
1142 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
1143 {
1144     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1145     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1146
1147     if (replacementRange.location != NSNotFound)
1148         LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length);
1149     else
1150         LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
1151     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1152     if (parameters)
1153         parameters->consumedByIM = false;
1154
1155     NSString *text;
1156     bool isFromInputMethod = _data->_page->editorState().hasComposition;
1157
1158     if (isAttributedString) {
1159         // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data.
1160         text = [string string];
1161     } else
1162         text = string;
1163
1164     // insertText can be called for several reasons:
1165     // - If it's from normal key event processing (including key bindings), we may need to save the action to perform it later.
1166     // - If it's from an input method, then we should go ahead and insert the text now. We assume it's from the input method if we have marked text.
1167     // FIXME: In theory, this could be wrong for some input methods, so we should try to find another way to determine if the call is from the input method.
1168     // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse),
1169     // then we also execute it immediately, as there will be no other chance.
1170     if (parameters && !isFromInputMethod) {
1171         ASSERT(replacementRange.location == NSNotFound);
1172         parameters->commands->append(KeypressCommand("insertText:", text));
1173         return;
1174     }
1175
1176     String eventText = text;
1177     eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
1178     bool eventHandled = _data->_page->insertText(eventText, replacementRange.location, NSMaxRange(replacementRange));
1179
1180     if (parameters)
1181         parameters->eventInterpretationHadSideEffects |= eventHandled;
1182 }
1183
1184 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
1185 {
1186     if (!_data->_page->editorState().isContentEditable)
1187         return NO;
1188
1189     if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) != NSCommandKeyMask)
1190         return NO;
1191     
1192     // Here we special case cmd+b and cmd+i but not cmd+u, for historic reason.
1193     // This should not be changed, since it could break some Mac applications that
1194     // rely on this inherent behavior.
1195     // See https://bugs.webkit.org/show_bug.cgi?id=24943
1196     
1197     NSString *string = [event characters];
1198     if ([string caseInsensitiveCompare:@"b"] == NSOrderedSame) {
1199         _data->_page->executeEditCommand("ToggleBold");
1200         return YES;
1201     }
1202     if ([string caseInsensitiveCompare:@"i"] == NSOrderedSame) {
1203         _data->_page->executeEditCommand("ToggleItalic");
1204         return YES;
1205     }
1206     
1207     return NO;
1208 }
1209
1210 - (BOOL)performKeyEquivalent:(NSEvent *)event
1211 {
1212     // There's a chance that responding to this event will run a nested event loop, and
1213     // fetching a new event might release the old one. Retaining and then autoreleasing
1214     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1215     [[event retain] autorelease];
1216     
1217     BOOL eventWasSentToWebCore = (_data->_keyDownEventBeingResent == event);
1218
1219     if (!eventWasSentToWebCore)
1220         [self _disableComplexTextInputIfNecessary];
1221
1222     // Pass key combos through WebCore if there is a key binding available for
1223     // this event. This lets web pages have a crack at intercepting key-modified keypresses.
1224     // But don't do it if we have already handled the event.
1225     // Pressing Esc results in a fake event being sent - don't pass it to WebCore.
1226     if (!eventWasSentToWebCore && event == [NSApp currentEvent] && self == [[self window] firstResponder]) {
1227         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, self));
1228         return YES;
1229     }
1230     
1231     return [self _handleStyleKeyEquivalent:event] || [super performKeyEquivalent:event];
1232 }
1233
1234 - (void)keyUp:(NSEvent *)theEvent
1235 {
1236     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1237 }
1238
1239 - (void)_disableComplexTextInputIfNecessary
1240 {
1241     if (!_data->_pluginComplexTextInputIdentifier)
1242         return;
1243
1244     if (_data->_pluginComplexTextInputState != PluginComplexTextInputEnabled)
1245         return;
1246
1247     // Check if the text input window has been dismissed.
1248     if (![[WKTextInputWindowController sharedTextInputWindowController] hasMarkedText])
1249         [self _setPluginComplexTextInputState:PluginComplexTextInputDisabled];
1250 }
1251
1252 - (BOOL)_handlePluginComplexTextInputKeyDown:(NSEvent *)event
1253 {
1254     ASSERT(_data->_pluginComplexTextInputIdentifier);
1255     ASSERT(_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled);
1256
1257     BOOL usingLegacyCocoaTextInput = _data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy;
1258
1259     NSString *string = nil;
1260     BOOL didHandleEvent = [[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:event usingLegacyCocoaTextInput:usingLegacyCocoaTextInput string:&string];
1261
1262     if (string) {
1263         _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string);
1264
1265         if (!usingLegacyCocoaTextInput)
1266             _data->_pluginComplexTextInputState = PluginComplexTextInputDisabled;
1267     }
1268
1269     return didHandleEvent;
1270 }
1271
1272 - (BOOL)_tryHandlePluginComplexTextInputKeyDown:(NSEvent *)event
1273 {
1274     if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
1275         return NO;
1276
1277     // Check if the text input window has been dismissed and let the plug-in process know.
1278     // This is only valid with the updated Cocoa text input spec.
1279     [self _disableComplexTextInputIfNecessary];
1280
1281     // Try feeding the keyboard event directly to the plug-in.
1282     if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
1283         return [self _handlePluginComplexTextInputKeyDown:event];
1284
1285     return NO;
1286 }
1287
1288 - (void)keyDown:(NSEvent *)theEvent
1289 {
1290     // There's a chance that responding to this event will run a nested event loop, and
1291     // fetching a new event might release the old one. Retaining and then autoreleasing
1292     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1293     [[theEvent retain] autorelease];
1294
1295     if ([self _tryHandlePluginComplexTextInputKeyDown:theEvent])
1296         return;
1297
1298     // We could be receiving a key down from AppKit if we have re-sent an event
1299     // that maps to an action that is currently unavailable (for example a copy when
1300     // there is no range selection).
1301     // If this is the case we should ignore the key down.
1302     if (_data->_keyDownEventBeingResent == theEvent) {
1303         [super keyDown:theEvent];
1304         return;
1305     }
1306     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1307 }
1308
1309 - (void)flagsChanged:(NSEvent *)theEvent
1310 {
1311     // There's a chance that responding to this event will run a nested event loop, and
1312     // fetching a new event might release the old one. Retaining and then autoreleasing
1313     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1314     [[theEvent retain] autorelease];
1315
1316     unsigned short keyCode = [theEvent keyCode];
1317
1318     // Don't make an event from the num lock and function keys
1319     if (!keyCode || keyCode == 10 || keyCode == 63)
1320         return;
1321
1322     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1323 }
1324
1325 - (void)_executeSavedKeypressCommands
1326 {
1327     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1328     if (!parameters || parameters->commands->isEmpty())
1329         return;
1330
1331     // We could be called again if the execution of one command triggers a call to selectedRange.
1332     // In this case, the state is up to date, and we don't need to execute any more saved commands to return a result.
1333     if (parameters->executingSavedKeypressCommands)
1334         return;
1335
1336     parameters->executingSavedKeypressCommands = true;
1337     parameters->eventInterpretationHadSideEffects |= _data->_page->executeKeypressCommands(*parameters->commands);
1338     parameters->commands->clear();
1339     parameters->executingSavedKeypressCommands = false;
1340 }
1341
1342 - (void)_notifyInputContextAboutDiscardedComposition
1343 {
1344     // <rdar://problem/9359055>: -discardMarkedText can only be called for active contexts.
1345     // FIXME: We fail to ever notify the input context if something (e.g. a navigation) happens while the window is not key.
1346     // This is not a problem when the window is key, because we discard marked text on resigning first responder.
1347     if (![[self window] isKeyWindow] || self != [[self window] firstResponder])
1348         return;
1349
1350     [[super inputContext] discardMarkedText]; // Inform the input method that we won't have an inline input area despite having been asked to.
1351 }
1352
1353 - (NSTextInputContext *)inputContext
1354 {
1355     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1356
1357     if (_data->_pluginComplexTextInputIdentifier && !parameters)
1358         return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
1359
1360     // Disable text input machinery when in non-editable content. An invisible inline input area affects performance, and can prevent Expose from working.
1361     if (!_data->_page->editorState().isContentEditable)
1362         return nil;
1363
1364     return [super inputContext];
1365 }
1366
1367 - (NSRange)selectedRange
1368 {
1369     [self _executeSavedKeypressCommands];
1370
1371     uint64_t selectionStart;
1372     uint64_t selectionLength;
1373     _data->_page->getSelectedRange(selectionStart, selectionLength);
1374
1375     NSRange result = NSMakeRange(selectionStart, selectionLength);
1376     if (result.location == NSNotFound)
1377         LOG(TextInput, "selectedRange -> (NSNotFound, %u)", result.length);
1378     else
1379         LOG(TextInput, "selectedRange -> (%u, %u)", result.location, result.length);
1380
1381     return result;
1382 }
1383
1384 - (BOOL)hasMarkedText
1385 {
1386     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1387
1388     BOOL result;
1389     if (parameters) {
1390         result = _data->_page->editorState().hasComposition;
1391         if (result) {
1392             // A saved command can confirm a composition, but it cannot start a new one.
1393             [self _executeSavedKeypressCommands];
1394             result = _data->_page->editorState().hasComposition;
1395         }
1396     } else {
1397         uint64_t location;
1398         uint64_t length;
1399         _data->_page->getMarkedRange(location, length);
1400         result = location != NSNotFound;
1401     }
1402
1403     LOG(TextInput, "hasMarkedText -> %u", result);
1404     return result;
1405 }
1406
1407 - (void)unmarkText
1408 {
1409     [self _executeSavedKeypressCommands];
1410
1411     LOG(TextInput, "unmarkText");
1412
1413     // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
1414     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1415
1416     if (parameters) {
1417         parameters->eventInterpretationHadSideEffects = true;
1418         parameters->consumedByIM = false;
1419     }
1420
1421     _data->_page->confirmComposition();
1422 }
1423
1424 - (NSArray *)validAttributesForMarkedText
1425 {
1426     static NSArray *validAttributes;
1427     if (!validAttributes) {
1428         validAttributes = [[NSArray alloc] initWithObjects:
1429                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
1430                            NSMarkedClauseSegmentAttributeName, nil];
1431         // NSText also supports the following attributes, but it's
1432         // hard to tell which are really required for text input to
1433         // work well; I have not seen any input method make use of them yet.
1434         //     NSFontAttributeName, NSForegroundColorAttributeName,
1435         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
1436         CFRetain(validAttributes);
1437     }
1438     LOG(TextInput, "validAttributesForMarkedText -> (...)");
1439     return validAttributes;
1440 }
1441
1442 static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result)
1443 {
1444     int length = [[string string] length];
1445     
1446     int i = 0;
1447     while (i < length) {
1448         NSRange range;
1449         NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)];
1450         
1451         if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
1452             Color color = Color::black;
1453             if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName])
1454                 color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
1455             result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1));
1456         }
1457         
1458         i = range.location + range.length;
1459     }
1460 }
1461
1462 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange replacementRange:(NSRange)replacementRange
1463 {
1464     [self _executeSavedKeypressCommands];
1465
1466     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1467     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1468
1469     LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelRange.location, newSelRange.length);
1470
1471     // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
1472     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1473
1474     if (parameters) {
1475         parameters->eventInterpretationHadSideEffects = true;
1476         parameters->consumedByIM = false;
1477     }
1478     
1479     Vector<CompositionUnderline> underlines;
1480     NSString *text;
1481
1482     if (isAttributedString) {
1483         // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation.
1484         text = [string string];
1485         extractUnderlines(string, underlines);
1486     } else
1487         text = string;
1488
1489     if (_data->_page->editorState().isInPasswordField) {
1490         // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField.
1491         // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard.
1492         ASSERT(!_data->_page->editorState().hasComposition);
1493         [self _notifyInputContextAboutDiscardedComposition];
1494         if ([text length] == 1 && [[text decomposedStringWithCanonicalMapping] characterAtIndex:0] < 0x80) {
1495             _data->_page->insertText(text, replacementRange.location, NSMaxRange(replacementRange));
1496         } else
1497             NSBeep();
1498         return;
1499     }
1500
1501     _data->_page->setComposition(text, underlines, newSelRange.location, NSMaxRange(newSelRange), replacementRange.location, NSMaxRange(replacementRange));
1502 }
1503
1504 - (NSRange)markedRange
1505 {
1506     [self _executeSavedKeypressCommands];
1507
1508     uint64_t location;
1509     uint64_t length;
1510     _data->_page->getMarkedRange(location, length);
1511
1512     LOG(TextInput, "markedRange -> (%u, %u)", location, length);
1513     return NSMakeRange(location, length);
1514 }
1515
1516 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
1517 {
1518     [self _executeSavedKeypressCommands];
1519
1520     if (!_data->_page->editorState().isContentEditable) {
1521         LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> nil", nsRange.location, nsRange.length);
1522         return nil;
1523     }
1524
1525     if (_data->_page->editorState().isInPasswordField)
1526         return nil;
1527
1528     AttributedString result;
1529     _data->_page->getAttributedSubstringFromRange(nsRange.location, NSMaxRange(nsRange), result);
1530
1531     if (actualRange) {
1532         *actualRange = nsRange;
1533         actualRange->length = [result.string.get() length];
1534     }
1535
1536     LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> \"%@\"", nsRange.location, nsRange.length, [result.string.get() string]);
1537     return [[result.string.get() retain] autorelease];
1538 }
1539
1540 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1541 {
1542     [self _executeSavedKeypressCommands];
1543
1544     NSWindow *window = [self window];
1545     
1546     if (window)
1547         thePoint = [window convertScreenToBase:thePoint];
1548     thePoint = [self convertPoint:thePoint fromView:nil];  // the point is relative to the main frame 
1549     
1550     uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint));
1551     LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result);
1552     return result;
1553 }
1554
1555 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
1556
1557     [self _executeSavedKeypressCommands];
1558
1559     // Just to match NSTextView's behavior. Regression tests cannot detect this;
1560     // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
1561     // (type something; try ranges (1, -1) and (2, -1).
1562     if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
1563         theRange.length = 0;
1564     
1565     NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange.location, theRange.length);
1566     resultRect = [self convertRect:resultRect toView:nil];
1567     
1568     NSWindow *window = [self window];
1569     if (window)
1570         resultRect.origin = [window convertBaseToScreen:resultRect.origin];
1571
1572     if (actualRange) {
1573         // FIXME: Update actualRange to match the range of first rect.
1574         *actualRange = theRange;
1575     }
1576
1577     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);
1578     return resultRect;
1579 }
1580
1581 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
1582 {
1583     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
1584     NSPoint windowMouseLoc = windowImageLoc;
1585    
1586     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
1587     _data->_ignoringMouseDraggedEvents = YES;
1588     
1589     _data->_page->dragEnded(IntPoint(windowMouseLoc), globalPoint(windowMouseLoc, [self window]), operation);
1590 }
1591
1592 - (DragApplicationFlags)applicationFlags:(id <NSDraggingInfo>)draggingInfo
1593 {
1594     uint32_t flags = 0;
1595     if ([NSApp modalWindow])
1596         flags = DragApplicationIsModal;
1597     if ([[self window] attachedSheet])
1598         flags |= DragApplicationHasAttachedSheet;
1599     if ([draggingInfo draggingSource] == self)
1600         flags |= DragApplicationIsSource;
1601     if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1602         flags |= DragApplicationIsCopyKeyDown;
1603     return static_cast<DragApplicationFlags>(flags);
1604 }
1605
1606 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
1607 {
1608     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1609     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1610     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1611
1612     _data->_page->resetDragOperation();
1613     _data->_page->dragEntered(&dragData, [[draggingInfo draggingPasteboard] name]);
1614     return NSDragOperationCopy;
1615 }
1616
1617 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
1618 {
1619     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1620     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1621     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1622     _data->_page->dragUpdated(&dragData, [[draggingInfo draggingPasteboard] name]);
1623     
1624     WebCore::DragSession dragSession = _data->_page->dragSession();
1625 #if !defined(BUILDING_ON_SNOW_LEOPARD)
1626     NSInteger numberOfValidItemsForDrop = dragSession.numberOfItemsToBeAccepted;
1627     NSDraggingFormation draggingFormation = NSDraggingFormationNone;
1628     if (dragSession.mouseIsOverFileInput && numberOfValidItemsForDrop > 0)
1629         draggingFormation = NSDraggingFormationList;
1630
1631     if ([draggingInfo numberOfValidItemsForDrop] != numberOfValidItemsForDrop)
1632         [draggingInfo setNumberOfValidItemsForDrop:numberOfValidItemsForDrop];
1633     if ([draggingInfo draggingFormation] != draggingFormation)
1634         [draggingInfo setDraggingFormation:draggingFormation];
1635 #endif
1636     return dragSession.operation;
1637 }
1638
1639 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
1640 {
1641     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1642     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1643     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1644     _data->_page->dragExited(&dragData, [[draggingInfo draggingPasteboard] name]);
1645     _data->_page->resetDragOperation();
1646 }
1647
1648 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
1649 {
1650     return YES;
1651 }
1652
1653 // FIXME: This code is more or less copied from Pasteboard::getBestURL.
1654 // It would be nice to be able to share the code somehow.
1655 static bool maybeCreateSandboxExtensionFromPasteboard(NSPasteboard *pasteboard, SandboxExtension::Handle& sandboxExtensionHandle)
1656 {
1657     NSArray *types = [pasteboard types];
1658     if (![types containsObject:NSFilenamesPboardType])
1659         return false;
1660
1661     NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
1662     if ([files count] != 1)
1663         return false;
1664
1665     NSString *file = [files objectAtIndex:0];
1666     BOOL isDirectory;
1667     if (![[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory])
1668         return false;
1669
1670     if (isDirectory)
1671         return false;
1672
1673     SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle);
1674     return true;
1675 }
1676
1677 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
1678 {
1679     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1680     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1681     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1682
1683     SandboxExtension::Handle sandboxExtensionHandle;
1684     bool createdExtension = maybeCreateSandboxExtensionFromPasteboard([draggingInfo draggingPasteboard], sandboxExtensionHandle);
1685     if (createdExtension)
1686         _data->_page->process()->willAcquireUniversalFileReadSandboxExtension();
1687
1688     _data->_page->performDrag(&dragData, [[draggingInfo draggingPasteboard] name], sandboxExtensionHandle);
1689
1690     return YES;
1691 }
1692
1693 // This code is needed to support drag and drop when the drag types cannot be matched.
1694 // This is the case for elements that do not place content
1695 // in the drag pasteboard automatically when the drag start (i.e. dragging a DIV element).
1696 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
1697 {
1698     if ([[self superview] mouse:*point inRect:[self frame]])
1699         return self;
1700     return nil;
1701 }
1702
1703 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)loc
1704 {
1705     NSPoint localPoint = [self convertPoint:loc fromView:nil];
1706     NSRect visibleThumbRect = NSRect(_data->_page->visibleScrollerThumbRect());
1707     return NSMouseInRect(localPoint, visibleThumbRect, [self isFlipped]);
1708 }
1709
1710 - (void)_updateWindowVisibility
1711 {
1712     _data->_page->updateWindowIsVisible(![[self window] isMiniaturized]);
1713 }
1714
1715 - (BOOL)_ownsWindowGrowBox
1716 {
1717     NSWindow* window = [self window];
1718     if (!window)
1719         return NO;
1720
1721     NSView *superview = [self superview];
1722     if (!superview)
1723         return NO;
1724
1725     NSRect growBoxRect = [window _growBoxRect];
1726     if (NSIsEmptyRect(growBoxRect))
1727         return NO;
1728
1729     NSRect visibleRect = [self visibleRect];
1730     if (NSIsEmptyRect(visibleRect))
1731         return NO;
1732
1733     NSRect visibleRectInWindowCoords = [self convertRect:visibleRect toView:nil];
1734     if (!NSIntersectsRect(growBoxRect, visibleRectInWindowCoords))
1735         return NO;
1736
1737     return YES;
1738 }
1739
1740 - (BOOL)_updateGrowBoxForWindowFrameChange
1741 {
1742     // Temporarily enable the resize indicator to make a the _ownsWindowGrowBox calculation work.
1743     BOOL wasShowingIndicator = [[self window] showsResizeIndicator];
1744     if (!wasShowingIndicator)
1745         [[self window] setShowsResizeIndicator:YES];
1746
1747     BOOL ownsGrowBox = [self _ownsWindowGrowBox];
1748     _data->_page->setWindowResizerSize(ownsGrowBox ? enclosingIntRect([[self window] _growBoxRect]).size() : IntSize());
1749
1750     if (ownsGrowBox)
1751         [[self window] _setShowOpaqueGrowBoxForOwner:(_data->_page->hasHorizontalScrollbar() || _data->_page->hasVerticalScrollbar() ? self : nil)];
1752     else
1753         [[self window] _setShowOpaqueGrowBoxForOwner:nil];
1754
1755     // Once WebCore can draw the window resizer, this should read:
1756     // if (wasShowingIndicator)
1757     //     [[self window] setShowsResizeIndicator:!ownsGrowBox];
1758     if (!wasShowingIndicator)
1759         [[self window] setShowsResizeIndicator:NO];
1760
1761     return ownsGrowBox;
1762 }
1763
1764 // FIXME: Use AppKit constants for these when they are available.
1765 static NSString * const windowDidChangeBackingPropertiesNotification = @"NSWindowDidChangeBackingPropertiesNotification";
1766 static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOldScaleFactorKey";
1767
1768 - (void)addWindowObserversForWindow:(NSWindow *)window
1769 {
1770     if (window) {
1771         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
1772                                                      name:NSWindowDidBecomeKeyNotification object:nil];
1773         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
1774                                                      name:NSWindowDidResignKeyNotification object:nil];
1775         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) 
1776                                                      name:NSWindowDidMiniaturizeNotification object:window];
1777         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
1778                                                      name:NSWindowDidDeminiaturizeNotification object:window];
1779         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMove:)
1780                                                      name:NSWindowDidMoveNotification object:window];
1781         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResize:) 
1782                                                      name:NSWindowDidResizeNotification object:window];
1783         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOffScreen:) 
1784                                                      name:@"NSWindowDidOrderOffScreenNotification" object:window];
1785         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOnScreen:) 
1786                                                      name:@"_NSWindowDidBecomeVisible" object:window];
1787         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeBackingProperties:)
1788                                                      name:windowDidChangeBackingPropertiesNotification object:window];
1789         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeScreen:)
1790                                                      name:NSWindowDidChangeScreenNotification object:window];
1791     }
1792 }
1793
1794 - (void)removeWindowObservers
1795 {
1796     NSWindow *window = [self window];
1797     if (!window)
1798         return;
1799
1800     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
1801     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
1802     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
1803     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
1804     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
1805     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
1806     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowDidOrderOffScreenNotification" object:window];
1807     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"_NSWindowDidBecomeVisible" object:window];
1808     [[NSNotificationCenter defaultCenter] removeObserver:self name:windowDidChangeBackingPropertiesNotification object:window];
1809     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeScreenNotification object:window];
1810 }
1811
1812 - (void)viewWillMoveToWindow:(NSWindow *)window
1813 {
1814     NSWindow *currentWindow = [self window];
1815     if (window == currentWindow)
1816         return;
1817     
1818     [self removeWindowObservers];
1819     [self addWindowObserversForWindow:window];
1820     
1821     if ([currentWindow _growBoxOwner] == self)
1822         [currentWindow _setShowOpaqueGrowBoxForOwner:nil];
1823 }
1824
1825 - (void)viewDidMoveToWindow
1826 {
1827     // We want to make sure to update the active state while hidden, so if the view is about to become visible, we
1828     // update the active state first and then make it visible. If the view is about to be hidden, we hide it first and then
1829     // update the active state.
1830     if ([self window]) {
1831         _data->_windowHasValidBackingStore = NO;
1832         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1833         _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible | WebPageProxy::ViewIsInWindow);
1834         [self _updateWindowVisibility];
1835         [self _updateWindowAndViewFrames];
1836
1837         if (!_data->_flagsChangedEventMonitor) {
1838             _data->_flagsChangedEventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSFlagsChangedMask handler:^(NSEvent *flagsChangedEvent) {
1839                 [self _postFakeMouseMovedEventForFlagsChangedEvent:flagsChangedEvent];
1840                 return flagsChangedEvent;
1841             }];
1842         }
1843
1844         [self _accessibilityRegisterUIProcessTokens];
1845     } else {
1846         _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1847         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive | WebPageProxy::ViewIsInWindow);
1848
1849         [NSEvent removeMonitor:_data->_flagsChangedEventMonitor];
1850         _data->_flagsChangedEventMonitor = nil;
1851
1852 #if ENABLE(GESTURE_EVENTS)
1853         if (_data->_endGestureMonitor) {
1854             [NSEvent removeMonitor:_data->_endGestureMonitor];
1855             _data->_endGestureMonitor = nil;
1856         }
1857 #endif
1858 #if !defined(BUILDING_ON_SNOW_LEOPARD)
1859         WKHideWordDefinitionWindow();
1860 #endif
1861     }
1862
1863     _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]);
1864 }
1865
1866 - (void)doWindowDidChangeScreen
1867 {
1868     _data->_page->windowScreenDidChange((PlatformDisplayID)[[[[[self window] screen] deviceDescription] objectForKey:@"NSScreenNumber"] intValue]);
1869 }
1870
1871 - (void)_windowDidBecomeKey:(NSNotification *)notification
1872 {
1873     NSWindow *keyWindow = [notification object];
1874     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet]) {
1875         [self _updateSecureInputState];
1876         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1877     }
1878
1879     // Send a change screen to make sure the initial displayID is set
1880     [self doWindowDidChangeScreen];
1881 }
1882
1883 - (void)_windowDidChangeScreen:(NSNotification *)notification
1884 {
1885     [self doWindowDidChangeScreen];
1886 }
1887
1888 - (void)_windowDidResignKey:(NSNotification *)notification
1889 {
1890     NSWindow *formerKeyWindow = [notification object];
1891     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) {
1892         [self _updateSecureInputState];
1893         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1894     }
1895 }
1896
1897 - (void)_windowDidMiniaturize:(NSNotification *)notification
1898 {
1899     _data->_windowHasValidBackingStore = NO;
1900
1901     [self _updateWindowVisibility];
1902 }
1903
1904 - (void)_windowDidDeminiaturize:(NSNotification *)notification
1905 {
1906     [self _updateWindowVisibility];
1907 }
1908
1909 - (void)_windowDidMove:(NSNotification *)notification
1910 {
1911     [self _updateWindowAndViewFrames];    
1912 }
1913
1914 - (void)_windowDidResize:(NSNotification *)notification
1915 {
1916     _data->_windowHasValidBackingStore = NO;
1917
1918     [self _updateWindowAndViewFrames];
1919 }
1920
1921 - (void)_windowDidOrderOffScreen:(NSNotification *)notification
1922 {
1923     // We want to make sure to update the active state while hidden, so since the view is about to be hidden,
1924     // we hide it first and then update the active state.
1925     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1926     _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1927 }
1928
1929 - (void)_windowDidOrderOnScreen:(NSNotification *)notification
1930 {
1931     // We want to make sure to update the active state while hidden, so since the view is about to become visible,
1932     // we update the active state first and then make it visible.
1933     _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1934     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1935 }
1936
1937 - (void)_windowDidChangeBackingProperties:(NSNotification *)notification
1938 {
1939     CGFloat oldBackingScaleFactor = [[notification.userInfo objectForKey:backingPropertyOldScaleFactorKey] doubleValue]; 
1940     CGFloat newBackingScaleFactor = [self _intrinsicDeviceScaleFactor]; 
1941     if (oldBackingScaleFactor == newBackingScaleFactor) 
1942         return; 
1943
1944     _data->_windowHasValidBackingStore = NO;
1945     _data->_page->setIntrinsicDeviceScaleFactor(newBackingScaleFactor);
1946 }
1947
1948 static void drawPageBackground(CGContextRef context, WebPageProxy* page, const IntRect& rect)
1949 {
1950     if (!page->drawsBackground())
1951         return;
1952
1953     CGContextSaveGState(context);
1954     CGContextSetBlendMode(context, kCGBlendModeCopy);
1955
1956     CGColorRef backgroundColor;
1957     if (page->drawsTransparentBackground())
1958         backgroundColor = CGColorGetConstantColor(kCGColorClear);
1959     else
1960         backgroundColor = CGColorGetConstantColor(kCGColorWhite);
1961
1962     CGContextSetFillColorWithColor(context, backgroundColor);
1963     CGContextFillRect(context, rect);
1964
1965     CGContextRestoreGState(context);
1966 }
1967
1968 - (void)drawRect:(NSRect)rect
1969 {
1970     LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1971     _data->_page->endPrinting();
1972
1973     if ([self _shouldUseTiledDrawingArea]) {
1974         // Nothing to do here.
1975         return;
1976     }
1977
1978     CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
1979
1980     if (DrawingAreaProxyImpl* drawingArea = static_cast<DrawingAreaProxyImpl*>(_data->_page->drawingArea())) {
1981         const NSRect *rectsBeingDrawn;
1982         NSInteger numRectsBeingDrawn;
1983         [self getRectsBeingDrawn:&rectsBeingDrawn count:&numRectsBeingDrawn];
1984         for (NSInteger i = 0; i < numRectsBeingDrawn; ++i) {
1985             Region unpaintedRegion;
1986             IntRect rect = enclosingIntRect(rectsBeingDrawn[i]);
1987             drawingArea->paint(context, rect, unpaintedRegion);
1988
1989             // If the window doesn't have a valid backing store, we need to fill the parts of the page that we
1990             // didn't paint with the background color (white or clear), to avoid garbage in those areas.
1991             if (!_data->_windowHasValidBackingStore) {
1992                 Vector<IntRect> unpaintedRects = unpaintedRegion.rects();
1993                 for (size_t i = 0; i < unpaintedRects.size(); ++i)
1994                     drawPageBackground(context, _data->_page.get(), unpaintedRects[i]);
1995
1996                 _data->_windowHasValidBackingStore = YES;
1997             }
1998         }
1999     } else 
2000         drawPageBackground(context, _data->_page.get(), enclosingIntRect(rect));
2001
2002     _data->_page->didDraw();
2003 }
2004
2005 - (BOOL)isOpaque
2006 {
2007     return _data->_page->drawsBackground();
2008 }
2009
2010 - (BOOL)mouseDownCanMoveWindow
2011 {
2012     // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent,
2013     // but we don't want a drag in the NSView to move the window, even if it's transparent.
2014     return NO;
2015 }
2016
2017 - (void)viewDidHide
2018 {
2019     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
2020 }
2021
2022 - (void)viewDidUnhide
2023 {
2024     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
2025 }
2026
2027 - (void)_accessibilityRegisterUIProcessTokens
2028 {
2029     // Initialize remote accessibility when the window connection has been established.
2030     NSData *remoteElementToken = WKAXRemoteTokenForElement(self);
2031     NSData *remoteWindowToken = WKAXRemoteTokenForElement([self accessibilityAttributeValue:NSAccessibilityWindowAttribute]);
2032     CoreIPC::DataReference elementToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteElementToken bytes]), [remoteElementToken length]);
2033     CoreIPC::DataReference windowToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteWindowToken bytes]), [remoteWindowToken length]);
2034     _data->_page->registerUIProcessAccessibilityTokens(elementToken, windowToken);
2035 }
2036
2037 - (void)_updateRemoteAccessibilityRegistration:(BOOL)registerProcess
2038 {
2039     // When the tree is connected/disconnected, the remote accessibility registration
2040     // needs to be updated with the pid of the remote process. If the process is going
2041     // away, that information is not present in WebProcess
2042     pid_t pid = 0;
2043     if (registerProcess && _data->_page->process())
2044         pid = _data->_page->process()->processIdentifier();
2045     else if (!registerProcess) {
2046         pid = WKAXRemoteProcessIdentifier(_data->_remoteAccessibilityChild.get());
2047         _data->_remoteAccessibilityChild = nil;
2048     }
2049     if (pid)
2050         WKAXRegisterRemoteProcess(registerProcess, pid); 
2051 }
2052
2053 - (id)accessibilityFocusedUIElement
2054 {
2055     if (_data->_pdfViewController)
2056         return NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView());
2057
2058     return _data->_remoteAccessibilityChild.get();
2059 }
2060
2061 - (BOOL)accessibilityIsIgnored
2062 {
2063     return NO;
2064 }
2065
2066 - (id)accessibilityHitTest:(NSPoint)point
2067 {
2068     if (_data->_pdfViewController)
2069         return [_data->_pdfViewController->pdfView() accessibilityHitTest:point];
2070     
2071     return _data->_remoteAccessibilityChild.get();
2072 }
2073
2074 - (id)accessibilityAttributeValue:(NSString*)attribute
2075 {
2076     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
2077
2078         id child = nil;
2079         if (_data->_pdfViewController)
2080             child = NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView());
2081         else if (_data->_remoteAccessibilityChild)
2082             child = _data->_remoteAccessibilityChild.get();
2083         
2084         if (!child)
2085             return nil;
2086         return [NSArray arrayWithObject:child];
2087     }
2088     if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
2089         return NSAccessibilityGroupRole;
2090     if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
2091         return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil);
2092     if ([attribute isEqualToString:NSAccessibilityParentAttribute])
2093         return NSAccessibilityUnignoredAncestor([self superview]);
2094     if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
2095         return [NSNumber numberWithBool:YES];
2096     
2097     return [super accessibilityAttributeValue:attribute];
2098 }
2099
2100 - (NSView *)hitTest:(NSPoint)point
2101 {
2102     NSView *hitView = [super hitTest:point];
2103     if (hitView && _data && hitView == _data->_layerHostingView)
2104         hitView = self;
2105
2106     return hitView;
2107 }
2108
2109 - (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent
2110 {
2111     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
2112         modifierFlags:[flagsChangedEvent modifierFlags] timestamp:[flagsChangedEvent timestamp] windowNumber:[flagsChangedEvent windowNumber]
2113         context:[flagsChangedEvent context] eventNumber:0 clickCount:0 pressure:0];
2114     [self mouseMoved:fakeEvent];
2115 }
2116
2117 - (NSInteger)conversationIdentifier
2118 {
2119     return (NSInteger)self;
2120 }
2121
2122 - (float)_intrinsicDeviceScaleFactor
2123 {
2124     NSWindow *window = [self window];
2125 #if !defined(BUILDING_ON_SNOW_LEOPARD)
2126     if (window)
2127         return [window backingScaleFactor];
2128     return [[NSScreen mainScreen] backingScaleFactor];
2129 #else
2130     if (window)
2131         return [window userSpaceScaleFactor];
2132     return [[NSScreen mainScreen] userSpaceScaleFactor];
2133 #endif
2134 }
2135
2136 - (void)_setDrawingAreaSize:(NSSize)size
2137 {
2138     if (!_data->_page->drawingArea())
2139         return;
2140     
2141     _data->_page->drawingArea()->setSize(IntSize(size), IntSize(_data->_resizeScrollOffset));
2142     _data->_resizeScrollOffset = NSZeroSize;
2143 }
2144
2145 - (BOOL)_shouldUseTiledDrawingArea
2146 {
2147     return NO;
2148 }
2149
2150 #if !defined(BUILDING_ON_SNOW_LEOPARD) && !defined(BUILDING_ON_LION)
2151 - (void)quickLookWithEvent:(NSEvent *)event
2152 {
2153     NSPoint locationInViewCoordinates = [self convertPoint:[event locationInWindow] fromView:nil];
2154     _data->_page->performDictionaryLookupAtLocation(FloatPoint(locationInViewCoordinates.x, locationInViewCoordinates.y));
2155 }
2156 #endif
2157
2158 @end
2159
2160 @implementation WKView (Internal)
2161
2162 - (PassOwnPtr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy
2163 {
2164     if ([self _shouldUseTiledDrawingArea])
2165         return TiledCoreAnimationDrawingAreaProxy::create(_data->_page.get());
2166
2167     return DrawingAreaProxyImpl::create(_data->_page.get());
2168 }
2169
2170 - (BOOL)_isFocused
2171 {
2172     if (_data->_inBecomeFirstResponder)
2173         return YES;
2174     if (_data->_inResignFirstResponder)
2175         return NO;
2176     return [[self window] firstResponder] == self;
2177 }
2178
2179 - (void)_processDidCrash
2180 {
2181     [self _updateRemoteAccessibilityRegistration:NO];
2182 }
2183
2184 - (void)_pageClosed
2185 {
2186     [self _updateRemoteAccessibilityRegistration:NO];
2187 }
2188
2189 - (void)_didRelaunchProcess
2190 {
2191     [self _accessibilityRegisterUIProcessTokens];
2192 }
2193
2194 - (void)_setCursor:(NSCursor *)cursor
2195 {
2196     if ([NSCursor currentCursor] == cursor)
2197         return;
2198     [cursor set];
2199 }
2200
2201 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
2202 {
2203     ValidationVector items = _data->_validationMap.take(commandName);
2204     size_t size = items.size();
2205     for (size_t i = 0; i < size; ++i) {
2206         ValidationItem item = items[i].get();
2207         [menuItem(item) setState:newState];
2208         [menuItem(item) setEnabled:isEnabled];
2209         [toolbarItem(item) setEnabled:isEnabled];
2210         // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
2211     }
2212 }
2213
2214 - (BOOL)_tryPostProcessPluginComplexTextInputKeyDown:(NSEvent *)event
2215 {
2216     if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
2217         return NO;
2218
2219     // In the legacy text input model, the event has already been sent to the input method.
2220     if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
2221         return NO;
2222
2223     return [self _handlePluginComplexTextInputKeyDown:event];
2224 }
2225
2226 - (void)_doneWithKeyEvent:(NSEvent *)event eventWasHandled:(BOOL)eventWasHandled
2227 {
2228     if ([event type] != NSKeyDown)
2229         return;
2230
2231     if ([self _tryPostProcessPluginComplexTextInputKeyDown:event])
2232         return;
2233     
2234     if (eventWasHandled) {
2235         [NSCursor setHiddenUntilMouseMoves:YES];
2236         return;
2237     }
2238
2239     // resending the event may destroy this WKView
2240     RetainPtr<WKView> protector(self);
2241
2242     ASSERT(!_data->_keyDownEventBeingResent);
2243     _data->_keyDownEventBeingResent = event;
2244     [NSApp _setCurrentEvent:event];
2245     [NSApp sendEvent:event];
2246
2247     _data->_keyDownEventBeingResent = nullptr;
2248 }
2249
2250 - (BOOL)_interpretKeyEvent:(NSEvent *)event savingCommandsTo:(Vector<WebCore::KeypressCommand>&)commands
2251 {
2252     ASSERT(!_data->_interpretKeyEventsParameters);
2253     ASSERT(commands.isEmpty());
2254
2255     if ([event type] == NSFlagsChanged)
2256         return NO;
2257
2258     WKViewInterpretKeyEventsParameters parameters;
2259     parameters.eventInterpretationHadSideEffects = false;
2260     parameters.executingSavedKeypressCommands = false;
2261     // We assume that an input method has consumed the event, and only change this assumption if one of the NSTextInput methods is called.
2262     // We assume the IM will *not* consume hotkey sequences.
2263     parameters.consumedByIM = !([event modifierFlags] & NSCommandKeyMask);
2264     parameters.commands = &commands;
2265     _data->_interpretKeyEventsParameters = &parameters;
2266
2267     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2268
2269     _data->_interpretKeyEventsParameters = 0;
2270
2271     // An input method may consume an event and not tell us (e.g. when displaying a candidate window),
2272     // in which case we should not bubble the event up the DOM.
2273     if (parameters.consumedByIM)
2274         return YES;
2275
2276     // If we have already executed all or some of the commands, the event is "handled". Note that there are additional checks on web process side.
2277     return parameters.eventInterpretationHadSideEffects;
2278 }
2279
2280 - (NSRect)_convertToDeviceSpace:(NSRect)rect
2281 {
2282     return toDeviceSpace(rect, [self window], _data->_page->deviceScaleFactor());
2283 }
2284
2285 - (NSRect)_convertToUserSpace:(NSRect)rect
2286 {
2287     return toUserSpace(rect, [self window], _data->_page->deviceScaleFactor());
2288 }
2289
2290 // Any non-zero value will do, but using something recognizable might help us debug some day.
2291 #define TRACKING_RECT_TAG 0xBADFACE
2292
2293 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2294 {
2295     ASSERT(_data->_trackingRectOwner == nil);
2296     _data->_trackingRectOwner = owner;
2297     _data->_trackingRectUserData = data;
2298     return TRACKING_RECT_TAG;
2299 }
2300
2301 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2302 {
2303     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
2304     ASSERT(_data->_trackingRectOwner == nil);
2305     _data->_trackingRectOwner = owner;
2306     _data->_trackingRectUserData = data;
2307     return TRACKING_RECT_TAG;
2308 }
2309
2310 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
2311 {
2312     ASSERT(count == 1);
2313     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
2314     ASSERT(_data->_trackingRectOwner == nil);
2315     _data->_trackingRectOwner = owner;
2316     _data->_trackingRectUserData = userDataList[0];
2317     trackingNums[0] = TRACKING_RECT_TAG;
2318 }
2319
2320 - (void)removeTrackingRect:(NSTrackingRectTag)tag
2321 {
2322     if (!_data)
2323         return;
2324
2325     if (tag == 0)
2326         return;
2327     
2328     if (tag == TRACKING_RECT_TAG) {
2329         _data->_trackingRectOwner = nil;
2330         return;
2331     }
2332     
2333     if (tag == _data->_lastToolTipTag) {
2334         [super removeTrackingRect:tag];
2335         _data->_lastToolTipTag = 0;
2336         return;
2337     }
2338
2339     // If any other tracking rect is being removed, we don't know how it was created
2340     // and it's possible there's a leak involved (see 3500217)
2341     ASSERT_NOT_REACHED();
2342 }
2343
2344 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
2345 {
2346     int i;
2347     for (i = 0; i < count; ++i) {
2348         int tag = tags[i];
2349         if (tag == 0)
2350             continue;
2351         ASSERT(tag == TRACKING_RECT_TAG);
2352         if (_data != nil) {
2353             _data->_trackingRectOwner = nil;
2354         }
2355     }
2356 }
2357
2358 - (void)_sendToolTipMouseExited
2359 {
2360     // Nothing matters except window, trackingNumber, and userData.
2361     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
2362         location:NSMakePoint(0, 0)
2363         modifierFlags:0
2364         timestamp:0
2365         windowNumber:[[self window] windowNumber]
2366         context:NULL
2367         eventNumber:0
2368         trackingNumber:TRACKING_RECT_TAG
2369         userData:_data->_trackingRectUserData];
2370     [_data->_trackingRectOwner mouseExited:fakeEvent];
2371 }
2372
2373 - (void)_sendToolTipMouseEntered
2374 {
2375     // Nothing matters except window, trackingNumber, and userData.
2376     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
2377         location:NSMakePoint(0, 0)
2378         modifierFlags:0
2379         timestamp:0
2380         windowNumber:[[self window] windowNumber]
2381         context:NULL
2382         eventNumber:0
2383         trackingNumber:TRACKING_RECT_TAG
2384         userData:_data->_trackingRectUserData];
2385     [_data->_trackingRectOwner mouseEntered:fakeEvent];
2386 }
2387
2388 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
2389 {
2390     return nsStringFromWebCoreString(_data->_page->toolTip());
2391 }
2392
2393 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
2394 {
2395     if (oldToolTip)
2396         [self _sendToolTipMouseExited];
2397
2398     if (newToolTip && [newToolTip length] > 0) {
2399         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
2400         [self removeAllToolTips];
2401         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
2402         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
2403         [self _sendToolTipMouseEntered];
2404     }
2405 }
2406
2407 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut animate:(BOOL)animate
2408 {
2409     if (!findIndicator) {
2410         _data->_findIndicatorWindow = nullptr;
2411         return;
2412     }
2413
2414     if (!_data->_findIndicatorWindow)
2415         _data->_findIndicatorWindow = FindIndicatorWindow::create(self);
2416
2417     _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut, animate);
2418 }
2419
2420 - (void)_enterAcceleratedCompositingMode:(const LayerTreeContext&)layerTreeContext
2421 {
2422     ASSERT(!_data->_layerHostingView);
2423     ASSERT(!layerTreeContext.isEmpty());
2424
2425     // Create an NSView that will host our layer tree.
2426     _data->_layerHostingView.adoptNS([[WKFlippedView alloc] initWithFrame:[self bounds]]);
2427     [_data->_layerHostingView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
2428
2429     [CATransaction begin];
2430     [CATransaction setDisableActions:YES];
2431     [self addSubview:_data->_layerHostingView.get()];
2432
2433     // Create a root layer that will back the NSView.
2434     RetainPtr<CALayer> rootLayer(AdoptNS, [[CALayer alloc] init]);
2435 #ifndef NDEBUG
2436     [rootLayer.get() setName:@"Hosting root layer"];
2437 #endif
2438
2439     CALayer *renderLayer = WKMakeRenderLayer(layerTreeContext.contextID);
2440     [rootLayer.get() addSublayer:renderLayer];
2441
2442     [_data->_layerHostingView.get() setLayer:rootLayer.get()];
2443     [_data->_layerHostingView.get() setWantsLayer:YES];
2444
2445     [CATransaction commit];
2446 }
2447
2448 - (void)_exitAcceleratedCompositingMode
2449 {
2450     ASSERT(_data->_layerHostingView);
2451
2452     [_data->_layerHostingView.get() removeFromSuperview];
2453     [_data->_layerHostingView.get() setLayer:nil];
2454     [_data->_layerHostingView.get() setWantsLayer:NO];
2455     
2456     _data->_layerHostingView = nullptr;
2457 }
2458
2459 - (void)_setAccessibilityWebProcessToken:(NSData *)data
2460 {
2461     _data->_remoteAccessibilityChild = WKAXRemoteElementForToken(data);
2462     [self _updateRemoteAccessibilityRegistration:YES];
2463 }
2464
2465 - (void)_pluginFocusOrWindowFocusChanged:(BOOL)pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
2466 {
2467     BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
2468
2469     if (pluginHasFocusAndWindowHasFocus) {
2470         // Check if we're already allowing text input for this plug-in.
2471         if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
2472             return;
2473
2474         _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
2475
2476     } else {
2477         // Check if we got a request to unfocus a plug-in that isn't focused.
2478         if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
2479             return;
2480
2481         _data->_pluginComplexTextInputIdentifier = 0;
2482     }
2483
2484     if (inputSourceChanged) {
2485         // The input source changed, go ahead and discard any entered text.
2486         [[WKTextInputWindowController sharedTextInputWindowController] unmarkText];
2487     }
2488
2489     // This will force the current input context to be updated to its correct value.
2490     [NSApp updateWindows];
2491 }
2492
2493 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
2494 {
2495     if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier) {
2496         // We're asked to update the state for a plug-in that doesn't have focus.
2497         return;
2498     }
2499
2500     [self _setPluginComplexTextInputState:pluginComplexTextInputState];
2501 }
2502
2503 - (void)_setPageHasCustomRepresentation:(BOOL)pageHasCustomRepresentation
2504 {
2505     bool hadPDFView = _data->_pdfViewController;
2506     _data->_pdfViewController = nullptr;
2507
2508     if (pageHasCustomRepresentation)
2509         _data->_pdfViewController = PDFViewController::create(self);
2510     
2511     if (pageHasCustomRepresentation != hadPDFView)
2512         _data->_page->drawingArea()->pageCustomRepresentationChanged();
2513 }
2514
2515 - (void)_didFinishLoadingDataForCustomRepresentationWithSuggestedFilename:(const String&)suggestedFilename dataReference:(const CoreIPC::DataReference&)dataReference
2516 {
2517     ASSERT(_data->_pdfViewController);
2518
2519     _data->_pdfViewController->setPDFDocumentData(_data->_page->mainFrame()->mimeType(), suggestedFilename, dataReference);
2520 }
2521
2522 - (double)_customRepresentationZoomFactor
2523 {
2524     if (!_data->_pdfViewController)
2525         return 1;
2526
2527     return _data->_pdfViewController->zoomFactor();
2528 }
2529
2530 - (void)_setCustomRepresentationZoomFactor:(double)zoomFactor
2531 {
2532     if (!_data->_pdfViewController)
2533         return;
2534
2535     _data->_pdfViewController->setZoomFactor(zoomFactor);
2536 }
2537
2538 - (void)_findStringInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count
2539 {
2540     if (!_data->_pdfViewController)
2541         return;
2542
2543     _data->_pdfViewController->findString(string, options, count);
2544 }
2545
2546 - (void)_countStringMatchesInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count
2547 {
2548     if (!_data->_pdfViewController)
2549         return;
2550
2551     _data->_pdfViewController->countStringMatches(string, options, count);
2552 }
2553
2554 - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag
2555 {
2556     // We need to prevent re-entering this call to avoid crashing in AppKit.
2557     // Given the asynchronous nature of WebKit2 this can now happen.
2558     if (_data->_dragHasStarted)
2559         return;
2560     
2561     _data->_dragHasStarted = YES;
2562     
2563     // The call to super could release this WKView.
2564     RetainPtr<WKView> protector(self);
2565     
2566     [super dragImage:image
2567                   at:clientPoint
2568               offset:NSZeroSize
2569                event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent
2570           pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
2571               source:self
2572            slideBack:YES];
2573     _data->_dragHasStarted = NO;
2574 }
2575
2576 - (void)_updateSecureInputState
2577 {
2578     if (![[self window] isKeyWindow] || ![self _isFocused]) {
2579         if (_data->_inSecureInputState) {
2580             DisableSecureEventInput();
2581             _data->_inSecureInputState = NO;
2582         }
2583         return;
2584     }
2585     // WKView has a single input context for all editable areas (except for plug-ins).
2586     NSTextInputContext *context = [super inputContext];
2587     bool isInPasswordField = _data->_page->editorState().isInPasswordField;
2588
2589     if (isInPasswordField) {
2590         if (!_data->_inSecureInputState)
2591             EnableSecureEventInput();
2592         static NSArray *romanInputSources = [[NSArray alloc] initWithObjects:&NSAllRomanInputSourcesLocaleIdentifier count:1];
2593         [context setAllowedInputSourceLocales:romanInputSources];
2594     } else {
2595         if (_data->_inSecureInputState)
2596             DisableSecureEventInput();
2597         [context setAllowedInputSourceLocales:nil];
2598     }
2599     _data->_inSecureInputState = isInPasswordField;
2600 }
2601
2602 - (void)_updateTextInputStateIncludingSecureInputState:(BOOL)updateSecureInputState
2603 {
2604     const EditorState& editorState = _data->_page->editorState();
2605     if (updateSecureInputState) {
2606         // This is a temporary state when editing. Flipping secure input state too quickly can expose race conditions.
2607         if (!editorState.selectionIsNone)
2608             [self _updateSecureInputState];
2609     }
2610
2611     if (!editorState.hasComposition || editorState.shouldIgnoreCompositionSelectionChange)
2612         return;
2613
2614     _data->_page->cancelComposition();
2615
2616     [self _notifyInputContextAboutDiscardedComposition];
2617 }
2618
2619 - (void)_resetTextInputState
2620 {
2621     [self _notifyInputContextAboutDiscardedComposition];
2622
2623     if (_data->_inSecureInputState) {
2624         DisableSecureEventInput();
2625         _data->_inSecureInputState = NO;
2626     }
2627 }
2628
2629 - (void)_didChangeScrollbarsForMainFrame
2630 {
2631     [self _updateGrowBoxForWindowFrameChange];
2632 }
2633
2634 #if ENABLE(FULLSCREEN_API)
2635 - (WKFullScreenWindowController*)fullScreenWindowController
2636 {
2637     if (!_data->_fullScreenWindowController) {
2638         _data->_fullScreenWindowController.adoptNS([[WKFullScreenWindowController alloc] init]);
2639         [_data->_fullScreenWindowController.get() setWebView:self];
2640     }
2641     return _data->_fullScreenWindowController.get();
2642 }
2643
2644 - (void)closeFullScreenWindowController
2645 {
2646     if (!_data->_fullScreenWindowController)
2647         return;
2648     [_data->_fullScreenWindowController.get() close];
2649     _data->_fullScreenWindowController = nullptr;
2650 }
2651 #endif
2652
2653 - (bool)_executeSavedCommandBySelector:(SEL)selector
2654 {
2655     // The sink does two things: 1) Tells us if the responder went unhandled, and
2656     // 2) prevents any NSBeep; we don't ever want to beep here.
2657     RetainPtr<WKResponderChainSink> sink(AdoptNS, [[WKResponderChainSink alloc] initWithResponderChain:self]);
2658     [super doCommandBySelector:selector];
2659     [sink.get() detach];
2660     return ![sink.get() didReceiveUnhandledCommand];
2661 }
2662
2663 - (void)_cacheWindowBottomCornerRect
2664 {
2665 #if !defined(BUILDING_ON_SNOW_LEOPARD)
2666     // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. 
2667     NSWindow *window = [self window];
2668     if (!window)
2669         return;
2670
2671     _data->_windowBottomCornerIntersectionRect = [window _intersectBottomCornersWithRect:[self convertRect:[self visibleRect] toView:nil]];
2672     if (!NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect))
2673         [self setNeedsDisplayInRect:[self convertRect:_data->_windowBottomCornerIntersectionRect fromView:nil]];
2674 #endif
2675 }
2676
2677 - (NSInteger)spellCheckerDocumentTag
2678 {
2679     if (!_data->_hasSpellCheckerDocumentTag) {
2680         _data->_spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
2681         _data->_hasSpellCheckerDocumentTag = YES;
2682     }
2683     return _data->_spellCheckerDocumentTag;
2684 }
2685
2686 - (void)handleCorrectionPanelResult:(NSString*)result
2687 {
2688     _data->_page->handleCorrectionPanelResult(result);
2689 }
2690
2691 @end
2692
2693 @implementation WKView (Private)
2694
2695 - (void)_registerDraggedTypes
2696 {
2697     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:PasteboardTypes::forEditing()];
2698     [types addObjectsFromArray:PasteboardTypes::forURL()];
2699     [self registerForDraggedTypes:[types allObjects]];
2700     [types release];
2701 }
2702
2703 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef
2704 {
2705     self = [super initWithFrame:frame];
2706     if (!self)
2707         return nil;
2708
2709     [NSApp registerServicesMenuSendTypes:PasteboardTypes::forSelection() returnTypes:PasteboardTypes::forEditing()];
2710
2711     InitWebCoreSystemInterface();
2712     RunLoop::initializeMainRunLoop();
2713
2714     // Legacy style scrollbars have design details that rely on tracking the mouse all the time.
2715     NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect;
2716 #if !defined(BUILDING_ON_SNOW_LEOPARD)
2717     if (WKRecommendedScrollerStyle() == NSScrollerStyleLegacy)
2718         options |= NSTrackingActiveAlways;
2719     else
2720         options |= NSTrackingActiveInKeyWindow;
2721 #else
2722     options |= NSTrackingActiveInKeyWindow;
2723 #endif
2724
2725     NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame
2726                                                                 options:options
2727                                                                   owner:self
2728                                                                userInfo:nil];
2729     [self addTrackingArea:trackingArea];
2730     [trackingArea release];
2731
2732     _data = [[WKViewData alloc] init];
2733
2734     _data->_pageClient = PageClientImpl::create(self);
2735     _data->_page = toImpl(contextRef)->createWebPage(_data->_pageClient.get(), toImpl(pageGroupRef));
2736     _data->_page->initializeWebPage();
2737 #if ENABLE(FULLSCREEN_API)
2738     _data->_page->fullScreenManager()->setWebView(self);
2739 #endif
2740     _data->_mouseDownEvent = nil;
2741     _data->_ignoringMouseDraggedEvents = NO;
2742
2743     [self _registerDraggedTypes];
2744
2745     if ([self _shouldUseTiledDrawingArea]) {
2746         CALayer *layer = [CALayer layer];
2747         layer.backgroundColor = CGColorGetConstantColor(kCGColorWhite);
2748         self.layer = layer;
2749
2750         self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawNever;
2751         self.wantsLayer = YES;
2752     }
2753
2754     WebContext::statistics().wkViewCount++;
2755
2756     return self;
2757 }
2758
2759 - (WKPageRef)pageRef
2760 {
2761     return toAPI(_data->_page.get());
2762 }
2763
2764 - (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef
2765 {
2766     // PDF documents are already paginated, so we can't change them to add headers and footers.
2767     return !toImpl(frameRef)->isDisplayingPDFDocument();
2768 }
2769
2770 - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef
2771 {
2772     LOG(View, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data());
2773
2774     // Only the top frame can currently contain a PDF view.
2775     if (_data->_pdfViewController) {
2776         if (!toImpl(frameRef)->isMainFrame())
2777             return 0;
2778         return _data->_pdfViewController->makePrintOperation(printInfo);
2779     } else {
2780         // FIXME: If the frame cannot be printed (e.g. if it contains an encrypted PDF that disallows
2781         // printing), this function should return nil.
2782         RetainPtr<WKPrintingView> printingView(AdoptNS, [[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef) view:self]);
2783         // NSPrintOperation takes ownership of the view.
2784         NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get()];
2785         [printOperation setCanSpawnSeparateThread:YES];
2786         [printOperation setJobTitle:toImpl(frameRef)->title()];
2787         printingView->_printOperation = printOperation;
2788         return printOperation;
2789     }
2790 }
2791
2792 - (void)setFrame:(NSRect)rect andScrollBy:(NSSize)offset
2793 {
2794     ASSERT(NSEqualSizes(_data->_resizeScrollOffset, NSZeroSize));
2795
2796     _data->_resizeScrollOffset = offset;
2797     [self setFrame:rect];
2798 }
2799
2800 - (void)disableFrameSizeUpdates
2801 {
2802     _data->_frameSizeUpdatesDisabledCount++;
2803 }
2804
2805 - (void)enableFrameSizeUpdates
2806 {
2807     if (!_data->_frameSizeUpdatesDisabledCount)
2808         return;
2809     
2810     if (!(--_data->_frameSizeUpdatesDisabledCount))
2811         [self _setDrawingAreaSize:[self frame].size];
2812 }
2813
2814 - (BOOL)frameSizeUpdatesDisabled
2815 {
2816     return _data->_frameSizeUpdatesDisabledCount > 0;
2817 }
2818
2819 - (void)performDictionaryLookupAtCurrentMouseLocation
2820 {
2821     NSPoint thePoint = [NSEvent mouseLocation];
2822     thePoint = [[self window] convertScreenToBase:thePoint];
2823     thePoint = [self convertPoint:thePoint fromView:nil];
2824
2825     _data->_page->performDictionaryLookupAtLocation(FloatPoint(thePoint.x, thePoint.y));
2826 }
2827
2828 + (void)hideWordDefinitionWindow
2829 {
2830 #if !defined(BUILDING_ON_SNOW_LEOPARD)
2831     WKHideWordDefinitionWindow();
2832 #endif
2833 }
2834
2835 @end
2836
2837 @implementation WKResponderChainSink
2838
2839 - (id)initWithResponderChain:(NSResponder *)chain
2840 {
2841     self = [super init];
2842     if (!self)
2843         return nil;
2844     _lastResponderInChain = chain;
2845     while (NSResponder *next = [_lastResponderInChain nextResponder])
2846         _lastResponderInChain = next;
2847     [_lastResponderInChain setNextResponder:self];
2848     return self;
2849 }
2850
2851 - (void)detach
2852 {
2853     // This assumes that the responder chain was either unmodified since
2854     // -initWithResponderChain: was called, or was modified in such a way
2855     // that _lastResponderInChain is still in the chain, and self was not
2856     // moved earlier in the chain than _lastResponderInChain.
2857     NSResponder *responderBeforeSelf = _lastResponderInChain;    
2858     NSResponder *next = [responderBeforeSelf nextResponder];
2859     for (; next && next != self; next = [next nextResponder])
2860         responderBeforeSelf = next;
2861     
2862     // Nothing to be done if we are no longer in the responder chain.
2863     if (next != self)
2864         return;
2865     
2866     [responderBeforeSelf setNextResponder:[self nextResponder]];
2867     _lastResponderInChain = nil;
2868 }
2869
2870 - (bool)didReceiveUnhandledCommand
2871 {
2872     return _didReceiveUnhandledCommand;
2873 }
2874
2875 - (void)noResponderFor:(SEL)selector
2876 {
2877     _didReceiveUnhandledCommand = true;
2878 }
2879
2880 - (void)doCommandBySelector:(SEL)selector
2881 {
2882     _didReceiveUnhandledCommand = true;
2883 }
2884
2885 - (BOOL)tryToPerform:(SEL)action with:(id)object
2886 {
2887     _didReceiveUnhandledCommand = true;
2888     return YES;
2889 }
2890
2891 @end