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