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