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