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