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