Use a layer delegate instead of web_disableAllActions wherever possible
[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 #if PLATFORM(MAC)
30
31 #if USE(DICTATION_ALTERNATIVES)
32 #import <AppKit/NSTextAlternatives.h>
33 #import <AppKit/NSAttributedString.h>
34 #endif
35
36 #import "APIHistoryClient.h"
37 #import "AttributedString.h"
38 #import "ColorSpaceData.h"
39 #import "DataReference.h"
40 #import "EditingRange.h"
41 #import "EditorState.h"
42 #import "FindIndicator.h"
43 #import "FindIndicatorWindow.h"
44 #import "LayerTreeContext.h"
45 #import "Logging.h"
46 #import "NativeWebKeyboardEvent.h"
47 #import "NativeWebMouseEvent.h"
48 #import "NativeWebWheelEvent.h"
49 #import "PageClientImpl.h"
50 #import "PasteboardTypes.h"
51 #import "RemoteLayerTreeDrawingAreaProxy.h"
52 #import "StringUtilities.h"
53 #import "TextChecker.h"
54 #import "TextCheckerState.h"
55 #import "TiledCoreAnimationDrawingAreaProxy.h"
56 #import "ViewGestureController.h"
57 #import "ViewSnapshotStore.h"
58 #import "WKAPICast.h"
59 #import "WKFullScreenWindowController.h"
60 #import "WKPrintingView.h"
61 #import "WKProcessPoolInternal.h"
62 #import "WKStringCF.h"
63 #import "WKTextInputWindowController.h"
64 #import "WKViewInternal.h"
65 #import "WKViewPrivate.h"
66 #import "WebBackForwardList.h"
67 #import "WebContext.h"
68 #import "WebEventFactory.h"
69 #import "WebKit2Initialize.h"
70 #import "WebPage.h"
71 #import "WebPageGroup.h"
72 #import "WebPageProxy.h"
73 #import "WebPreferences.h"
74 #import "WebProcessProxy.h"
75 #import "WebSystemInterface.h"
76 #import "_WKThumbnailViewInternal.h"
77 #import <QuartzCore/QuartzCore.h>
78 #import <WebCore/AXObjectCache.h>
79 #import <WebCore/ColorMac.h>
80 #import <WebCore/DragController.h>
81 #import <WebCore/DragData.h>
82 #import <WebCore/FloatRect.h>
83 #import <WebCore/Image.h>
84 #import <WebCore/IntRect.h>
85 #import <WebCore/FileSystem.h>
86 #import <WebCore/KeyboardEvent.h>
87 #import <WebCore/LocalizedStrings.h>
88 #import <WebCore/PlatformEventFactoryMac.h>
89 #import <WebCore/PlatformScreen.h>
90 #import <WebCore/Region.h>
91 #import <WebCore/SharedBuffer.h>
92 #import <WebCore/TextAlternativeWithRange.h>
93 #import <WebCore/WebActionDisablingCALayerDelegate.h>
94 #import <WebCore/WebCoreCALayerExtras.h>
95 #import <WebCore/WebCoreFullScreenPlaceholderView.h>
96 #import <WebCore/WebCoreFullScreenWindow.h>
97 #import <WebCore/WebCoreNSStringExtras.h>
98 #import <WebKitSystemInterface.h>
99 #import <sys/stat.h>
100 #import <wtf/RefPtr.h>
101 #import <wtf/RetainPtr.h>
102 #import <wtf/RunLoop.h>
103
104 /* API internals. */
105 #import "WKBrowsingContextControllerInternal.h"
106 #import "WKBrowsingContextGroupPrivate.h"
107 #import "WKProcessGroupPrivate.h"
108
109 @interface NSApplication (WKNSApplicationDetails)
110 - (void)speakString:(NSString *)string;
111 - (void)_setCurrentEvent:(NSEvent *)event;
112 @end
113
114 @interface NSWindow (WKNSWindowDetails)
115 - (NSRect)_intersectBottomCornersWithRect:(NSRect)viewRect;
116 - (void)_maskRoundedBottomCorners:(NSRect)clipRect;
117 @end
118
119 #if USE(ASYNC_NSTEXTINPUTCLIENT)
120 @interface NSTextInputContext (WKNSTextInputContextDetails)
121 - (void)handleEvent:(NSEvent *)theEvent completionHandler:(void(^)(BOOL handled))completionHandler;
122 - (void)handleEventByInputMethod:(NSEvent *)theEvent completionHandler:(void(^)(BOOL handled))completionHandler;
123 - (BOOL)handleEventByKeyboardLayout:(NSEvent *)theEvent;
124 @end
125 #endif
126
127 #if defined(__has_include) && __has_include(<CoreGraphics/CoreGraphicsPrivate.h>)
128 #import <CoreGraphics/CoreGraphicsPrivate.h>
129 #import <CoreGraphics/CGSCapture.h>
130 #endif
131
132 extern "C" {
133 typedef uint32_t CGSConnectionID;
134 typedef uint32_t CGSWindowID;
135 CGSConnectionID CGSMainConnectionID(void);
136 CGError CGSGetScreenRectForWindow(CGSConnectionID cid, CGSWindowID wid, CGRect *rect);
137 CGError CGSCaptureWindowsContentsToRect(CGSConnectionID cid, const CGSWindowID windows[], uint32_t windowCount, CGRect rect, CGImageRef *outImage);
138 };
139
140 using namespace WebKit;
141 using namespace WebCore;
142
143 namespace WebKit {
144
145 typedef id <NSValidatedUserInterfaceItem> ValidationItem;
146 typedef Vector<RetainPtr<ValidationItem>> ValidationVector;
147 typedef HashMap<String, ValidationVector> ValidationMap;
148
149 }
150
151 #if !USE(ASYNC_NSTEXTINPUTCLIENT)
152 struct WKViewInterpretKeyEventsParameters {
153     bool eventInterpretationHadSideEffects;
154     bool consumedByIM;
155     bool executingSavedKeypressCommands;
156     Vector<KeypressCommand>* commands;
157 };
158 #endif
159
160 @interface WKViewData : NSObject {
161 @public
162     std::unique_ptr<PageClientImpl> _pageClient;
163     RefPtr<WebPageProxy> _page;
164
165 #if WK_API_ENABLED
166     RetainPtr<WKBrowsingContextController> _browsingContextController;
167 #endif
168
169     // For ToolTips.
170     NSToolTipTag _lastToolTipTag;
171     id _trackingRectOwner;
172     void* _trackingRectUserData;
173
174     RetainPtr<NSView> _layerHostingView;
175
176     RetainPtr<id> _remoteAccessibilityChild;
177     
178     // For asynchronous validation.
179     ValidationMap _validationMap;
180
181     std::unique_ptr<FindIndicatorWindow> _findIndicatorWindow;
182
183     // We keep here the event when resending it to
184     // the application to distinguish the case of a new event from one 
185     // that has been already sent to WebCore.
186     RetainPtr<NSEvent> _keyDownEventBeingResent;
187 #if USE(ASYNC_NSTEXTINPUTCLIENT)
188     Vector<KeypressCommand>* _collectedKeypressCommands;
189 #else
190     WKViewInterpretKeyEventsParameters* _interpretKeyEventsParameters;
191 #endif
192
193     NSSize _resizeScrollOffset;
194
195     // The identifier of the plug-in we want to send complex text input to, or 0 if there is none.
196     uint64_t _pluginComplexTextInputIdentifier;
197
198     // The state of complex text input for the plug-in.
199     PluginComplexTextInputState _pluginComplexTextInputState;
200
201     bool _inBecomeFirstResponder;
202     bool _inResignFirstResponder;
203     NSEvent *_mouseDownEvent;
204     BOOL _ignoringMouseDraggedEvents;
205
206     id _flagsChangedEventMonitor;
207
208 #if ENABLE(FULLSCREEN_API)
209     RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
210 #endif
211
212     BOOL _hasSpellCheckerDocumentTag;
213     NSInteger _spellCheckerDocumentTag;
214
215     BOOL _inSecureInputState;
216
217     NSRect _windowBottomCornerIntersectionRect;
218     
219     unsigned _frameSizeUpdatesDisabledCount;
220     BOOL _shouldDeferViewInWindowChanges;
221
222     BOOL _viewInWindowChangeWasDeferred;
223
224     BOOL _needsViewFrameInWindowCoordinates;
225     BOOL _didScheduleWindowAndViewFrameUpdate;
226
227     RetainPtr<NSColorSpace> _colorSpace;
228
229     RefPtr<WebCore::Image> _promisedImage;
230     String _promisedFilename;
231     String _promisedURL;
232     
233     NSSize _intrinsicContentSize;
234     BOOL _clipsToVisibleRect;
235     NSRect _contentPreparationRect;
236     BOOL _useContentPreparationRectForVisibleRect;
237     BOOL _windowOcclusionDetectionEnabled;
238
239     std::unique_ptr<ViewGestureController> _gestureController;
240     BOOL _allowsMagnification;
241     BOOL _allowsBackForwardNavigationGestures;
242
243     RetainPtr<CALayer> _rootLayer;
244
245 #if WK_API_ENABLED
246     _WKThumbnailView *_thumbnailView;
247 #endif
248 }
249
250 @end
251
252 @implementation WKViewData
253 @end
254
255 @interface WKResponderChainSink : NSResponder {
256     NSResponder *_lastResponderInChain;
257     bool _didReceiveUnhandledCommand;
258 }
259 - (id)initWithResponderChain:(NSResponder *)chain;
260 - (void)detach;
261 - (bool)didReceiveUnhandledCommand;
262 @end
263
264 @interface WKFlippedView : NSView
265 @end
266
267 @implementation WKFlippedView
268
269 - (BOOL)isFlipped
270 {
271     return YES;
272 }
273
274 @end
275
276 @implementation WKView
277
278 #if WK_API_ENABLED
279
280 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup
281 {
282     return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:nil];
283 }
284
285 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup relatedToView:(WKView *)relatedView
286 {
287     return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:relatedView ? toAPI(relatedView->_data->_page.get()) : nil];
288 }
289
290 #endif // WK_API_ENABLED
291
292 - (void)dealloc
293 {
294     _data->_page->close();
295
296 #if WK_API_ENABLED
297     ASSERT(!_data->_thumbnailView);
298 #endif
299     ASSERT(!_data->_inSecureInputState);
300
301     [_data release];
302     _data = nil;
303
304     NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
305     [workspaceNotificationCenter removeObserver:self name:NSWorkspaceActiveSpaceDidChangeNotification object:nil];
306
307     WebContext::statistics().wkViewCount--;
308
309     [super dealloc];
310 }
311
312 #if WK_API_ENABLED
313
314 - (WKBrowsingContextController *)browsingContextController
315 {
316     if (!_data->_browsingContextController)
317         _data->_browsingContextController = [[WKBrowsingContextController alloc] _initWithPageRef:toAPI(_data->_page.get())];
318
319     return _data->_browsingContextController.get();
320 }
321
322 #endif // WK_API_ENABLED
323
324 - (void)setDrawsBackground:(BOOL)drawsBackground
325 {
326     _data->_page->setDrawsBackground(drawsBackground);
327 }
328
329 - (BOOL)drawsBackground
330 {
331     return _data->_page->drawsBackground();
332 }
333
334 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
335 {
336     _data->_page->setDrawsTransparentBackground(drawsTransparentBackground);
337 }
338
339 - (BOOL)drawsTransparentBackground
340 {
341     return _data->_page->drawsTransparentBackground();
342 }
343
344 - (BOOL)acceptsFirstResponder
345 {
346     return YES;
347 }
348
349 - (BOOL)becomeFirstResponder
350 {
351     NSSelectionDirection direction = [[self window] keyViewSelectionDirection];
352
353     _data->_inBecomeFirstResponder = true;
354     
355     [self _updateSecureInputState];
356     _data->_page->viewStateDidChange(ViewState::IsFocused);
357
358     _data->_inBecomeFirstResponder = false;
359     
360     if (direction != NSDirectSelection) {
361         NSEvent *event = [NSApp currentEvent];
362         NSEvent *keyboardEvent = nil;
363         if ([event type] == NSKeyDown || [event type] == NSKeyUp)
364             keyboardEvent = event;
365         _data->_page->setInitialFocus(direction == NSSelectingNext, keyboardEvent != nil, NativeWebKeyboardEvent(keyboardEvent, false, Vector<KeypressCommand>()));
366     }
367     return YES;
368 }
369
370 - (BOOL)resignFirstResponder
371 {
372     _data->_inResignFirstResponder = true;
373
374 #if USE(ASYNC_NSTEXTINPUTCLIENT)
375     _data->_page->confirmCompositionAsync();
376 #else
377     if (_data->_page->editorState().hasComposition && !_data->_page->editorState().shouldIgnoreCompositionSelectionChange)
378         _data->_page->cancelComposition();
379 #endif
380
381     [self _notifyInputContextAboutDiscardedComposition];
382
383     [self _resetSecureInputState];
384
385     if (!_data->_page->maintainsInactiveSelection())
386         _data->_page->clearSelection();
387     
388     _data->_page->viewStateDidChange(ViewState::IsFocused);
389
390     _data->_inResignFirstResponder = false;
391
392     return YES;
393 }
394
395 - (void)viewWillStartLiveResize
396 {
397     _data->_page->viewWillStartLiveResize();
398 }
399
400 - (void)viewDidEndLiveResize
401 {
402     _data->_page->viewWillEndLiveResize();
403 }
404
405 - (BOOL)isFlipped
406 {
407     return YES;
408 }
409
410 - (NSSize)intrinsicContentSize
411 {
412     return _data->_intrinsicContentSize;
413 }
414
415 - (void)prepareContentInRect:(NSRect)rect
416 {
417     _data->_contentPreparationRect = rect;
418     _data->_useContentPreparationRectForVisibleRect = YES;
419
420     [self _updateViewExposedRect];
421 }
422
423 - (void)_updateViewExposedRect
424 {
425     NSRect exposedRect = [self visibleRect];
426
427     if (_data->_useContentPreparationRectForVisibleRect)
428         exposedRect = NSUnionRect(_data->_contentPreparationRect, exposedRect);
429
430     if (auto drawingArea = _data->_page->drawingArea())
431         drawingArea->setExposedRect(_data->_clipsToVisibleRect ? FloatRect(exposedRect) : FloatRect::infiniteRect());
432 }
433
434 - (void)setFrameSize:(NSSize)size
435 {
436     [super setFrameSize:size];
437
438     if (![self frameSizeUpdatesDisabled]) {
439         if (_data->_clipsToVisibleRect)
440             [self _updateViewExposedRect];
441         [self _setDrawingAreaSize:size];
442     }
443 }
444
445 - (void)_updateWindowAndViewFrames
446 {
447     if (_data->_clipsToVisibleRect)
448         [self _updateViewExposedRect];
449
450     if (_data->_didScheduleWindowAndViewFrameUpdate)
451         return;
452
453     _data->_didScheduleWindowAndViewFrameUpdate = YES;
454
455     dispatch_async(dispatch_get_main_queue(), ^{
456         _data->_didScheduleWindowAndViewFrameUpdate = NO;
457
458         NSRect viewFrameInWindowCoordinates = NSZeroRect;
459         NSPoint accessibilityPosition = NSZeroPoint;
460
461         if (_data->_needsViewFrameInWindowCoordinates)
462             viewFrameInWindowCoordinates = [self convertRect:self.frame toView:nil];
463
464 #pragma clang diagnostic push
465 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
466         if (WebCore::AXObjectCache::accessibilityEnabled())
467             accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue];
468 #pragma clang diagnostic pop
469
470         _data->_page->windowAndViewFramesChanged(viewFrameInWindowCoordinates, accessibilityPosition);
471     });
472 }
473
474 - (void)renewGState
475 {
476     // Hide the find indicator.
477     _data->_findIndicatorWindow = nullptr;
478
479     // Update the view frame.
480     if ([self window])
481         [self _updateWindowAndViewFrames];
482
483     [super renewGState];
484 }
485
486 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState
487 {
488     _data->_pluginComplexTextInputState = pluginComplexTextInputState;
489     
490     if (_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled)
491         return;
492
493     // Send back an empty string to the plug-in. This will disable text input.
494     _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, String());
495 }
496
497 typedef HashMap<SEL, String> SelectorNameMap;
498
499 // Map selectors into Editor command names.
500 // This is not needed for any selectors that have the same name as the Editor command.
501 static const SelectorNameMap* createSelectorExceptionMap()
502 {
503     SelectorNameMap* map = new HashMap<SEL, String>;
504     
505     map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
506     map->add(@selector(insertParagraphSeparator:), "InsertNewline");
507     map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
508     map->add(@selector(pageDown:), "MovePageDown");
509     map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
510     map->add(@selector(pageUp:), "MovePageUp");
511     map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
512     map->add(@selector(scrollPageDown:), "ScrollPageForward");
513     map->add(@selector(scrollPageUp:), "ScrollPageBackward");
514     
515     return map;
516 }
517
518 static String commandNameForSelector(SEL selector)
519 {
520     // Check the exception map first.
521     static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
522     SelectorNameMap::const_iterator it = exceptionMap->find(selector);
523     if (it != exceptionMap->end())
524         return it->value;
525     
526     // Remove the trailing colon.
527     // No need to capitalize the command name since Editor command names are
528     // not case sensitive.
529     const char* selectorName = sel_getName(selector);
530     size_t selectorNameLength = strlen(selectorName);
531     if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
532         return String();
533     return String(selectorName, selectorNameLength - 1);
534 }
535
536 // Editing commands
537
538 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
539
540 WEBCORE_COMMAND(alignCenter)
541 WEBCORE_COMMAND(alignJustified)
542 WEBCORE_COMMAND(alignLeft)
543 WEBCORE_COMMAND(alignRight)
544 WEBCORE_COMMAND(copy)
545 WEBCORE_COMMAND(cut)
546 WEBCORE_COMMAND(delete)
547 WEBCORE_COMMAND(deleteBackward)
548 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
549 WEBCORE_COMMAND(deleteForward)
550 WEBCORE_COMMAND(deleteToBeginningOfLine)
551 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
552 WEBCORE_COMMAND(deleteToEndOfLine)
553 WEBCORE_COMMAND(deleteToEndOfParagraph)
554 WEBCORE_COMMAND(deleteToMark)
555 WEBCORE_COMMAND(deleteWordBackward)
556 WEBCORE_COMMAND(deleteWordForward)
557 WEBCORE_COMMAND(ignoreSpelling)
558 WEBCORE_COMMAND(indent)
559 WEBCORE_COMMAND(insertBacktab)
560 WEBCORE_COMMAND(insertLineBreak)
561 WEBCORE_COMMAND(insertNewline)
562 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
563 WEBCORE_COMMAND(insertParagraphSeparator)
564 WEBCORE_COMMAND(insertTab)
565 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
566 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
567 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
568 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
569 WEBCORE_COMMAND(moveBackward)
570 WEBCORE_COMMAND(moveBackwardAndModifySelection)
571 WEBCORE_COMMAND(moveDown)
572 WEBCORE_COMMAND(moveDownAndModifySelection)
573 WEBCORE_COMMAND(moveForward)
574 WEBCORE_COMMAND(moveForwardAndModifySelection)
575 WEBCORE_COMMAND(moveLeft)
576 WEBCORE_COMMAND(moveLeftAndModifySelection)
577 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
578 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
579 WEBCORE_COMMAND(moveRight)
580 WEBCORE_COMMAND(moveRightAndModifySelection)
581 WEBCORE_COMMAND(moveToBeginningOfDocument)
582 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
583 WEBCORE_COMMAND(moveToBeginningOfLine)
584 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
585 WEBCORE_COMMAND(moveToBeginningOfParagraph)
586 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
587 WEBCORE_COMMAND(moveToBeginningOfSentence)
588 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
589 WEBCORE_COMMAND(moveToEndOfDocument)
590 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
591 WEBCORE_COMMAND(moveToEndOfLine)
592 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
593 WEBCORE_COMMAND(moveToEndOfParagraph)
594 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
595 WEBCORE_COMMAND(moveToEndOfSentence)
596 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
597 WEBCORE_COMMAND(moveToLeftEndOfLine)
598 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
599 WEBCORE_COMMAND(moveToRightEndOfLine)
600 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
601 WEBCORE_COMMAND(moveUp)
602 WEBCORE_COMMAND(moveUpAndModifySelection)
603 WEBCORE_COMMAND(moveWordBackward)
604 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
605 WEBCORE_COMMAND(moveWordForward)
606 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
607 WEBCORE_COMMAND(moveWordLeft)
608 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
609 WEBCORE_COMMAND(moveWordRight)
610 WEBCORE_COMMAND(moveWordRightAndModifySelection)
611 WEBCORE_COMMAND(outdent)
612 WEBCORE_COMMAND(pageDown)
613 WEBCORE_COMMAND(pageDownAndModifySelection)
614 WEBCORE_COMMAND(pageUp)
615 WEBCORE_COMMAND(pageUpAndModifySelection)
616 WEBCORE_COMMAND(paste)
617 WEBCORE_COMMAND(pasteAsPlainText)
618 WEBCORE_COMMAND(scrollPageDown)
619 WEBCORE_COMMAND(scrollPageUp)
620 WEBCORE_COMMAND(scrollLineDown)
621 WEBCORE_COMMAND(scrollLineUp)
622 WEBCORE_COMMAND(scrollToBeginningOfDocument)
623 WEBCORE_COMMAND(scrollToEndOfDocument)
624 WEBCORE_COMMAND(selectAll)
625 WEBCORE_COMMAND(selectLine)
626 WEBCORE_COMMAND(selectParagraph)
627 WEBCORE_COMMAND(selectSentence)
628 WEBCORE_COMMAND(selectToMark)
629 WEBCORE_COMMAND(selectWord)
630 WEBCORE_COMMAND(setMark)
631 WEBCORE_COMMAND(subscript)
632 WEBCORE_COMMAND(superscript)
633 WEBCORE_COMMAND(swapWithMark)
634 WEBCORE_COMMAND(takeFindStringFromSelection)
635 WEBCORE_COMMAND(transpose)
636 WEBCORE_COMMAND(underline)
637 WEBCORE_COMMAND(unscript)
638 WEBCORE_COMMAND(yank)
639 WEBCORE_COMMAND(yankAndSelect)
640
641 #undef WEBCORE_COMMAND
642
643 // This method is needed to support Mac OS X services.
644
645 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
646 {
647     size_t numTypes = [types count];
648     [pasteboard declareTypes:types owner:nil];
649     for (size_t i = 0; i < numTypes; ++i) {
650         if ([[types objectAtIndex:i] isEqualTo:NSStringPboardType])
651             [pasteboard setString:_data->_page->stringSelectionForPasteboard() forType:NSStringPboardType];
652         else {
653             RefPtr<SharedBuffer> buffer = _data->_page->dataSelectionForPasteboard([types objectAtIndex:i]);
654             [pasteboard setData:buffer ? buffer->createNSData().get() : nil forType:[types objectAtIndex:i]];
655        }
656     }
657     return YES;
658 }
659
660 - (void)centerSelectionInVisibleArea:(id)sender 
661
662     _data->_page->centerSelectionInVisibleArea();
663 }
664
665 // This method is needed to support Mac OS X services.
666
667 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
668 {
669     EditorState editorState = _data->_page->editorState();
670     BOOL isValidSendType = NO;
671
672     if (sendType && !editorState.selectionIsNone) {
673         if (editorState.isInPlugin)
674             isValidSendType = [sendType isEqualToString:NSStringPboardType];
675         else
676             isValidSendType = [PasteboardTypes::forSelection() containsObject:sendType];
677     }
678
679     BOOL isValidReturnType = NO;
680     if (!returnType)
681         isValidReturnType = YES;
682     else if ([PasteboardTypes::forEditing() containsObject:returnType] && editorState.isContentEditable) {
683         // We can insert strings in any editable context.  We can insert other types, like images, only in rich edit contexts.
684         isValidReturnType = editorState.isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType];
685     }
686     if (isValidSendType && isValidReturnType)
687         return self;
688     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
689 }
690
691 // This method is needed to support Mac OS X services.
692
693 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard 
694 {
695     return _data->_page->readSelectionFromPasteboard([pasteboard name]);
696 }
697
698 /*
699
700 When possible, editing-related methods should be implemented in WebCore with the
701 EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing
702 individual methods here with Mac-specific code.
703
704 Editing-related methods still unimplemented that are implemented in WebKit1:
705
706 - (void)capitalizeWord:(id)sender;
707 - (void)changeFont:(id)sender;
708 - (void)complete:(id)sender;
709 - (void)copyFont:(id)sender;
710 - (void)lowercaseWord:(id)sender;
711 - (void)makeBaseWritingDirectionLeftToRight:(id)sender;
712 - (void)makeBaseWritingDirectionNatural:(id)sender;
713 - (void)makeBaseWritingDirectionRightToLeft:(id)sender;
714 - (void)pasteFont:(id)sender;
715 - (void)scrollLineDown:(id)sender;
716 - (void)scrollLineUp:(id)sender;
717 - (void)showGuessPanel:(id)sender;
718 - (void)uppercaseWord:(id)sender;
719
720 Some other editing-related methods still unimplemented:
721
722 - (void)changeCaseOfLetter:(id)sender;
723 - (void)copyRuler:(id)sender;
724 - (void)insertContainerBreak:(id)sender;
725 - (void)insertDoubleQuoteIgnoringSubstitution:(id)sender;
726 - (void)insertSingleQuoteIgnoringSubstitution:(id)sender;
727 - (void)pasteRuler:(id)sender;
728 - (void)toggleRuler:(id)sender;
729 - (void)transposeWords:(id)sender;
730
731 */
732
733 // Menu items validation
734
735 static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item)
736 {
737     if (![(NSObject *)item isKindOfClass:[NSMenuItem class]])
738         return nil;
739     return (NSMenuItem *)item;
740 }
741
742 static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item)
743 {
744     if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]])
745         return nil;
746     return (NSToolbarItem *)item;
747 }
748
749 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
750 {
751     SEL action = [item action];
752
753     if (action == @selector(showGuessPanel:)) {
754         if (NSMenuItem *menuItem = ::menuItem(item))
755             [menuItem setTitle:contextMenuItemTagShowSpellingPanel(![[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible])];
756         return _data->_page->editorState().isContentEditable;
757     }
758
759     if (action == @selector(checkSpelling:) || action == @selector(changeSpelling:))
760         return _data->_page->editorState().isContentEditable;
761
762     if (action == @selector(toggleContinuousSpellChecking:)) {
763         bool enabled = TextChecker::isContinuousSpellCheckingAllowed();
764         bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled;
765         [menuItem(item) setState:checked ? NSOnState : NSOffState];
766         return enabled;
767     }
768
769     if (action == @selector(toggleGrammarChecking:)) {
770         bool checked = TextChecker::state().isGrammarCheckingEnabled;
771         [menuItem(item) setState:checked ? NSOnState : NSOffState];
772         return YES;
773     }
774
775     if (action == @selector(toggleAutomaticSpellingCorrection:)) {
776         bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled;
777         [menuItem(item) setState:checked ? NSOnState : NSOffState];
778         return _data->_page->editorState().isContentEditable;
779     }
780
781     if (action == @selector(orderFrontSubstitutionsPanel:)) {
782         if (NSMenuItem *menuItem = ::menuItem(item))
783             [menuItem setTitle:contextMenuItemTagShowSubstitutions(![[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible])];
784         return _data->_page->editorState().isContentEditable;
785     }
786
787     if (action == @selector(toggleSmartInsertDelete:)) {
788         bool checked = _data->_page->isSmartInsertDeleteEnabled();
789         [menuItem(item) setState:checked ? NSOnState : NSOffState];
790         return _data->_page->editorState().isContentEditable;
791     }
792
793     if (action == @selector(toggleAutomaticQuoteSubstitution:)) {
794         bool checked = TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
795         [menuItem(item) setState:checked ? NSOnState : NSOffState];
796         return _data->_page->editorState().isContentEditable;
797     }
798
799     if (action == @selector(toggleAutomaticDashSubstitution:)) {
800         bool checked = TextChecker::state().isAutomaticDashSubstitutionEnabled;
801         [menuItem(item) setState:checked ? NSOnState : NSOffState];
802         return _data->_page->editorState().isContentEditable;
803     }
804
805     if (action == @selector(toggleAutomaticLinkDetection:)) {
806         bool checked = TextChecker::state().isAutomaticLinkDetectionEnabled;
807         [menuItem(item) setState:checked ? NSOnState : NSOffState];
808         return _data->_page->editorState().isContentEditable;
809     }
810
811     if (action == @selector(toggleAutomaticTextReplacement:)) {
812         bool checked = TextChecker::state().isAutomaticTextReplacementEnabled;
813         [menuItem(item) setState:checked ? NSOnState : NSOffState];
814         return _data->_page->editorState().isContentEditable;
815     }
816
817     if (action == @selector(uppercaseWord:) || action == @selector(lowercaseWord:) || action == @selector(capitalizeWord:))
818         return _data->_page->editorState().selectionIsRange && _data->_page->editorState().isContentEditable;
819     
820     if (action == @selector(stopSpeaking:))
821         return [NSApp isSpeaking];
822     
823     // The centerSelectionInVisibleArea: selector is enabled if there's a selection range or if there's an insertion point in an editable area.
824     if (action == @selector(centerSelectionInVisibleArea:))
825         return _data->_page->editorState().selectionIsRange || (_data->_page->editorState().isContentEditable && !_data->_page->editorState().selectionIsNone);
826
827     // Next, handle editor commands. Start by returning YES for anything that is not an editor command.
828     // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized.
829     String commandName = commandNameForSelector([item action]);
830     if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName))
831         return YES;
832
833     // Add this item to the vector of items for a given command that are awaiting validation.
834     ValidationMap::AddResult addResult = _data->_validationMap.add(commandName, ValidationVector());
835     addResult.iterator->value.append(item);
836     if (addResult.isNewEntry) {
837         // If we are not already awaiting validation for this command, start the asynchronous validation process.
838         // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
839         // we asked for the same command; there is no guarantee the answer is still valid.
840         _data->_page->validateCommand(commandName, ValidateCommandCallback::create([self](bool error, StringImpl* commandName, bool isEnabled, int32_t state) {
841             // If the process exits before the command can be validated, we'll be called back with an error.
842             if (error)
843                 return;
844             
845             [self _setUserInterfaceItemState:nsStringFromWebCoreString(commandName) enabled:isEnabled state:state];
846         }));
847     }
848
849     // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called.
850     // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment.
851     // But returning NO here would be worse; that would make keyboard commands such as command-C fail.
852     return YES;
853 }
854
855 - (IBAction)startSpeaking:(id)sender
856 {
857     _data->_page->getSelectionOrContentsAsString(StringCallback::create([self](bool error, StringImpl* string) {
858         if (error)
859             return;
860         if (!string)
861             return;
862
863         [NSApp speakString:*string];
864     }));
865 }
866
867 - (IBAction)stopSpeaking:(id)sender
868 {
869     [NSApp stopSpeaking:sender];
870 }
871
872 - (IBAction)showGuessPanel:(id)sender
873 {
874     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
875     if (!checker) {
876         LOG_ERROR("No NSSpellChecker");
877         return;
878     }
879     
880     NSPanel *spellingPanel = [checker spellingPanel];
881     if ([spellingPanel isVisible]) {
882         [spellingPanel orderOut:sender];
883         return;
884     }
885     
886     _data->_page->advanceToNextMisspelling(true);
887     [spellingPanel orderFront:sender];
888 }
889
890 - (IBAction)checkSpelling:(id)sender
891 {
892     _data->_page->advanceToNextMisspelling(false);
893 }
894
895 - (void)changeSpelling:(id)sender
896 {
897     NSString *word = [[sender selectedCell] stringValue];
898
899     _data->_page->changeSpellingToWord(word);
900 }
901
902 - (IBAction)toggleContinuousSpellChecking:(id)sender
903 {
904     bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled;
905     TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled);
906
907     _data->_page->process().updateTextCheckerState();
908 }
909
910 - (BOOL)isGrammarCheckingEnabled
911 {
912     return TextChecker::state().isGrammarCheckingEnabled;
913 }
914
915 - (void)setGrammarCheckingEnabled:(BOOL)flag
916 {
917     if (static_cast<bool>(flag) == TextChecker::state().isGrammarCheckingEnabled)
918         return;
919     
920     TextChecker::setGrammarCheckingEnabled(flag);
921     _data->_page->process().updateTextCheckerState();
922 }
923
924 - (IBAction)toggleGrammarChecking:(id)sender
925 {
926     bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled;
927     TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled);
928
929     _data->_page->process().updateTextCheckerState();
930 }
931
932 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
933 {
934     TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
935
936     _data->_page->process().updateTextCheckerState();
937 }
938
939 - (void)orderFrontSubstitutionsPanel:(id)sender
940 {
941     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
942     if (!checker) {
943         LOG_ERROR("No NSSpellChecker");
944         return;
945     }
946     
947     NSPanel *substitutionsPanel = [checker substitutionsPanel];
948     if ([substitutionsPanel isVisible]) {
949         [substitutionsPanel orderOut:sender];
950         return;
951     }
952     [substitutionsPanel orderFront:sender];
953 }
954
955 - (IBAction)toggleSmartInsertDelete:(id)sender
956 {
957     _data->_page->setSmartInsertDeleteEnabled(!_data->_page->isSmartInsertDeleteEnabled());
958 }
959
960 - (BOOL)isAutomaticQuoteSubstitutionEnabled
961 {
962     return TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
963 }
964
965 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
966 {
967     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticQuoteSubstitutionEnabled)
968         return;
969
970     TextChecker::setAutomaticQuoteSubstitutionEnabled(flag);
971     _data->_page->process().updateTextCheckerState();
972 }
973
974 - (void)toggleAutomaticQuoteSubstitution:(id)sender
975 {
976     TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled);
977     _data->_page->process().updateTextCheckerState();
978 }
979
980 - (BOOL)isAutomaticDashSubstitutionEnabled
981 {
982     return TextChecker::state().isAutomaticDashSubstitutionEnabled;
983 }
984
985 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
986 {
987     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticDashSubstitutionEnabled)
988         return;
989
990     TextChecker::setAutomaticDashSubstitutionEnabled(flag);
991     _data->_page->process().updateTextCheckerState();
992 }
993
994 - (void)toggleAutomaticDashSubstitution:(id)sender
995 {
996     TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled);
997     _data->_page->process().updateTextCheckerState();
998 }
999
1000 - (BOOL)isAutomaticLinkDetectionEnabled
1001 {
1002     return TextChecker::state().isAutomaticLinkDetectionEnabled;
1003 }
1004
1005 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
1006 {
1007     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticLinkDetectionEnabled)
1008         return;
1009
1010     TextChecker::setAutomaticLinkDetectionEnabled(flag);
1011     _data->_page->process().updateTextCheckerState();
1012 }
1013
1014 - (void)toggleAutomaticLinkDetection:(id)sender
1015 {
1016     TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled);
1017     _data->_page->process().updateTextCheckerState();
1018 }
1019
1020 - (BOOL)isAutomaticTextReplacementEnabled
1021 {
1022     return TextChecker::state().isAutomaticTextReplacementEnabled;
1023 }
1024
1025 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
1026 {
1027     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticTextReplacementEnabled)
1028         return;
1029
1030     TextChecker::setAutomaticTextReplacementEnabled(flag);
1031     _data->_page->process().updateTextCheckerState();
1032 }
1033
1034 - (void)toggleAutomaticTextReplacement:(id)sender
1035 {
1036     TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled);
1037     _data->_page->process().updateTextCheckerState();
1038 }
1039
1040 - (void)uppercaseWord:(id)sender
1041 {
1042     _data->_page->uppercaseWord();
1043 }
1044
1045 - (void)lowercaseWord:(id)sender
1046 {
1047     _data->_page->lowercaseWord();
1048 }
1049
1050 - (void)capitalizeWord:(id)sender
1051 {
1052     _data->_page->capitalizeWord();
1053 }
1054
1055 - (void)displayIfNeeded
1056 {
1057     // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. In the meantime,
1058     // it is necessary to disable scren updates so we get a chance to redraw the corners before this 
1059     // display is visible.
1060     NSWindow *window = [self window];
1061     BOOL shouldMaskWindow = window && !NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect);
1062     if (shouldMaskWindow)
1063         NSDisableScreenUpdates();
1064
1065     [super displayIfNeeded];
1066
1067     if (shouldMaskWindow) {
1068         [window _maskRoundedBottomCorners:_data->_windowBottomCornerIntersectionRect];
1069         NSEnableScreenUpdates();
1070         _data->_windowBottomCornerIntersectionRect = NSZeroRect;
1071     }
1072 }
1073
1074 // Events
1075
1076 -(BOOL)shouldIgnoreMouseEvents
1077 {
1078     // FIXME: This check is surprisingly specific. Are there any other cases where we need to block mouse events?
1079     // Do we actually need to in thumbnail view? And if we do, what about non-mouse events?
1080 #if WK_API_ENABLED
1081     if (_data->_thumbnailView)
1082         return YES;
1083 #endif
1084     return NO;
1085 }
1086
1087 // Override this so that AppKit will send us arrow keys as key down events so we can
1088 // support them via the key bindings mechanism.
1089 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
1090 {
1091     return YES;
1092 }
1093
1094 - (void)_setMouseDownEvent:(NSEvent *)event
1095 {
1096     ASSERT(!event || [event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
1097     
1098     if (event == _data->_mouseDownEvent)
1099         return;
1100     
1101     [_data->_mouseDownEvent release];
1102     _data->_mouseDownEvent = [event retain];
1103 }
1104
1105 #if USE(ASYNC_NSTEXTINPUTCLIENT)
1106 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
1107     - (void)Selector:(NSEvent *)theEvent \
1108     { \
1109         if ([self shouldIgnoreMouseEvents]) \
1110             return; \
1111         if (NSTextInputContext *context = [self inputContext]) { \
1112             [context handleEvent:theEvent completionHandler:^(BOOL handled) { \
1113                 if (handled) \
1114                     LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
1115                 else { \
1116                     NativeWebMouseEvent webEvent(theEvent, self); \
1117                     _data->_page->handleMouseEvent(webEvent); \
1118                 } \
1119             }]; \
1120             return; \
1121         } \
1122         NativeWebMouseEvent webEvent(theEvent, self); \
1123         _data->_page->handleMouseEvent(webEvent); \
1124     }
1125 #else
1126 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
1127     - (void)Selector:(NSEvent *)theEvent \
1128     { \
1129         if ([self shouldIgnoreMouseEvents]) \
1130             return; \
1131         if ([[self inputContext] handleEvent:theEvent]) { \
1132             LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
1133             return; \
1134         } \
1135         NativeWebMouseEvent webEvent(theEvent, self); \
1136         _data->_page->handleMouseEvent(webEvent); \
1137     }
1138 #endif
1139
1140 NATIVE_MOUSE_EVENT_HANDLER(mouseEntered)
1141 NATIVE_MOUSE_EVENT_HANDLER(mouseExited)
1142 NATIVE_MOUSE_EVENT_HANDLER(mouseMovedInternal)
1143 NATIVE_MOUSE_EVENT_HANDLER(mouseDownInternal)
1144 NATIVE_MOUSE_EVENT_HANDLER(mouseUpInternal)
1145 NATIVE_MOUSE_EVENT_HANDLER(mouseDraggedInternal)
1146 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDown)
1147 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDragged)
1148 NATIVE_MOUSE_EVENT_HANDLER(otherMouseMoved)
1149 NATIVE_MOUSE_EVENT_HANDLER(otherMouseUp)
1150 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDown)
1151 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDragged)
1152 NATIVE_MOUSE_EVENT_HANDLER(rightMouseUp)
1153
1154 #undef NATIVE_MOUSE_EVENT_HANDLER
1155
1156 - (void)_ensureGestureController
1157 {
1158     if (_data->_gestureController)
1159         return;
1160
1161     _data->_gestureController = std::make_unique<ViewGestureController>(*_data->_page);
1162 }
1163
1164 - (void)scrollWheel:(NSEvent *)event
1165 {
1166     if ([self shouldIgnoreMouseEvents])
1167         return;
1168
1169     if (_data->_allowsBackForwardNavigationGestures) {
1170         [self _ensureGestureController];
1171         if (_data->_gestureController->handleScrollWheelEvent(event))
1172             return;
1173     }
1174
1175     NativeWebWheelEvent webEvent = NativeWebWheelEvent(event, self);
1176     _data->_page->handleWheelEvent(webEvent);
1177 }
1178
1179 - (void)mouseMoved:(NSEvent *)event
1180 {
1181     if ([self shouldIgnoreMouseEvents])
1182         return;
1183
1184     // When a view is first responder, it gets mouse moved events even when the mouse is outside its visible rect.
1185     if (self == [[self window] firstResponder] && !NSPointInRect([self convertPoint:[event locationInWindow] fromView:nil], [self visibleRect]))
1186         return;
1187
1188     [self mouseMovedInternal:event];
1189 }
1190
1191 - (void)mouseDown:(NSEvent *)event
1192 {
1193     if ([self shouldIgnoreMouseEvents])
1194         return;
1195
1196     [self _setMouseDownEvent:event];
1197     _data->_ignoringMouseDraggedEvents = NO;
1198     [self mouseDownInternal:event];
1199 }
1200
1201 - (void)mouseUp:(NSEvent *)event
1202 {
1203     if ([self shouldIgnoreMouseEvents])
1204         return;
1205
1206     [self _setMouseDownEvent:nil];
1207     [self mouseUpInternal:event];
1208 }
1209
1210 - (void)mouseDragged:(NSEvent *)event
1211 {
1212     if ([self shouldIgnoreMouseEvents])
1213         return;
1214
1215     if (_data->_ignoringMouseDraggedEvents)
1216         return;
1217     [self mouseDraggedInternal:event];
1218 }
1219
1220 - (BOOL)acceptsFirstMouse:(NSEvent *)event
1221 {
1222     // There's a chance that responding to this event will run a nested event loop, and
1223     // fetching a new event might release the old one. Retaining and then autoreleasing
1224     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1225     [[event retain] autorelease];
1226     
1227     if (![self hitTest:[event locationInWindow]])
1228         return NO;
1229     
1230     [self _setMouseDownEvent:event];
1231     bool result = _data->_page->acceptsFirstMouse([event eventNumber], WebEventFactory::createWebMouseEvent(event, self));
1232     [self _setMouseDownEvent:nil];
1233     return result;
1234 }
1235
1236 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
1237 {
1238     // If this is the active window or we don't have a range selection, there is no need to perform additional checks
1239     // and we can avoid making a synchronous call to the WebProcess.
1240     if ([[self window] isKeyWindow] || _data->_page->editorState().selectionIsNone || !_data->_page->editorState().selectionIsRange)
1241         return NO;
1242
1243     // There's a chance that responding to this event will run a nested event loop, and
1244     // fetching a new event might release the old one. Retaining and then autoreleasing
1245     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1246     [[event retain] autorelease];
1247     
1248     if (![self hitTest:[event locationInWindow]])
1249         return NO;
1250     
1251     [self _setMouseDownEvent:event];
1252     bool result = _data->_page->shouldDelayWindowOrderingForEvent(WebEventFactory::createWebMouseEvent(event, self));
1253     [self _setMouseDownEvent:nil];
1254     return result;
1255 }
1256
1257 - (void)_disableComplexTextInputIfNecessary
1258 {
1259     if (!_data->_pluginComplexTextInputIdentifier)
1260         return;
1261
1262     if (_data->_pluginComplexTextInputState != PluginComplexTextInputEnabled)
1263         return;
1264
1265     // Check if the text input window has been dismissed.
1266     if (![[WKTextInputWindowController sharedTextInputWindowController] hasMarkedText])
1267         [self _setPluginComplexTextInputState:PluginComplexTextInputDisabled];
1268 }
1269
1270 - (BOOL)_handlePluginComplexTextInputKeyDown:(NSEvent *)event
1271 {
1272     ASSERT(_data->_pluginComplexTextInputIdentifier);
1273     ASSERT(_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled);
1274
1275     BOOL usingLegacyCocoaTextInput = _data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy;
1276
1277     NSString *string = nil;
1278     BOOL didHandleEvent = [[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:event usingLegacyCocoaTextInput:usingLegacyCocoaTextInput string:&string];
1279
1280     if (string) {
1281         _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string);
1282
1283         if (!usingLegacyCocoaTextInput)
1284             _data->_pluginComplexTextInputState = PluginComplexTextInputDisabled;
1285     }
1286
1287     return didHandleEvent;
1288 }
1289
1290 - (BOOL)_tryHandlePluginComplexTextInputKeyDown:(NSEvent *)event
1291 {
1292     if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
1293         return NO;
1294
1295     // Check if the text input window has been dismissed and let the plug-in process know.
1296     // This is only valid with the updated Cocoa text input spec.
1297     [self _disableComplexTextInputIfNecessary];
1298
1299     // Try feeding the keyboard event directly to the plug-in.
1300     if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
1301         return [self _handlePluginComplexTextInputKeyDown:event];
1302
1303     return NO;
1304 }
1305
1306 static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result)
1307 {
1308     int length = [[string string] length];
1309     
1310     int i = 0;
1311     while (i < length) {
1312         NSRange range;
1313         NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)];
1314         
1315         if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
1316             Color color = Color::black;
1317             if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName])
1318                 color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
1319             result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1));
1320         }
1321         
1322         i = range.location + range.length;
1323     }
1324 }
1325
1326 #if USE(ASYNC_NSTEXTINPUTCLIENT)
1327
1328 - (void)_collectKeyboardLayoutCommandsForEvent:(NSEvent *)event to:(Vector<KeypressCommand>&)commands
1329 {
1330     if ([event type] != NSKeyDown)
1331         return;
1332
1333     ASSERT(!_data->_collectedKeypressCommands);
1334     _data->_collectedKeypressCommands = &commands;
1335
1336     if (NSTextInputContext *context = [self inputContext])
1337         [context handleEventByKeyboardLayout:event];
1338     else
1339         [self interpretKeyEvents:[NSArray arrayWithObject:event]];
1340
1341     _data->_collectedKeypressCommands = nullptr;
1342 }
1343
1344 - (void)_interpretKeyEvent:(NSEvent *)event completionHandler:(void(^)(BOOL handled, const Vector<KeypressCommand>& commands))completionHandler
1345 {
1346     if (![self inputContext]) {
1347         Vector<KeypressCommand> commands;
1348         [self _collectKeyboardLayoutCommandsForEvent:event to:commands];
1349         completionHandler(NO, commands);
1350         return;
1351     }
1352
1353     LOG(TextInput, "-> handleEventByInputMethod:%p %@", event, event);
1354     [[self inputContext] handleEventByInputMethod:event completionHandler:^(BOOL handled) {
1355         
1356         LOG(TextInput, "... handleEventByInputMethod%s handled", handled ? "" : " not");
1357         if (handled) {
1358             completionHandler(YES, Vector<KeypressCommand>());
1359             return;
1360         }
1361
1362         Vector<KeypressCommand> commands;
1363         [self _collectKeyboardLayoutCommandsForEvent:event to:commands];
1364         completionHandler(NO, commands);
1365     }];
1366 }
1367
1368 - (void)doCommandBySelector:(SEL)selector
1369 {
1370     LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector));
1371
1372     Vector<KeypressCommand>* keypressCommands = _data->_collectedKeypressCommands;
1373
1374     if (keypressCommands) {
1375         KeypressCommand command(NSStringFromSelector(selector));
1376         keypressCommands->append(command);
1377         LOG(TextInput, "...stored");
1378         _data->_page->registerKeypressCommandName(command.commandName);
1379     } else {
1380         // FIXME: Send the command to Editor synchronously and only send it along the
1381         // responder chain if it's a selector that does not correspond to an editing command.
1382         [super doCommandBySelector:selector];
1383     }
1384 }
1385
1386 - (void)insertText:(id)string
1387 {
1388     // Unlike an NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context,
1389     // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText
1390     // command ensures that a keypress event is dispatched as appropriate.
1391     [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
1392 }
1393
1394 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
1395 {
1396     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1397     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1398
1399     if (replacementRange.location != NSNotFound)
1400         LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length);
1401     else
1402         LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
1403
1404     NSString *text;
1405     Vector<TextAlternativeWithRange> dictationAlternatives;
1406
1407     if (isAttributedString) {
1408 #if USE(DICTATION_ALTERNATIVES)
1409         collectDictationTextAlternatives(string, dictationAlternatives);
1410 #endif
1411         // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data.
1412         text = [string string];
1413     } else
1414         text = string;
1415
1416     // insertText can be called for several reasons:
1417     // - If it's from normal key event processing (including key bindings), we save the action to perform it later.
1418     // - If it's from an input method, then we should go ahead and insert the text now.
1419     // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse),
1420     // then we also execute it immediately, as there will be no other chance.
1421     Vector<KeypressCommand>* keypressCommands = _data->_collectedKeypressCommands;
1422     if (keypressCommands) {
1423         ASSERT(replacementRange.location == NSNotFound);
1424         KeypressCommand command("insertText:", text);
1425         keypressCommands->append(command);
1426         LOG(TextInput, "...stored");
1427         _data->_page->registerKeypressCommandName(command.commandName);
1428         return;
1429     }
1430
1431     String eventText = text;
1432     eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
1433     if (!dictationAlternatives.isEmpty())
1434         _data->_page->insertDictatedTextAsync(eventText, replacementRange, dictationAlternatives);
1435     else
1436         _data->_page->insertTextAsync(eventText, replacementRange);
1437 }
1438
1439 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
1440 {
1441     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1442
1443     LOG(TextInput, "selectedRange");
1444     _data->_page->getSelectedRangeAsync(EditingRangeCallback::create([completionHandler](bool error, const EditingRange& editingRangeResult) {
1445         void (^completionHandlerBlock)(NSRange) = (void (^)(NSRange))completionHandler.get();
1446         if (error) {
1447             LOG(TextInput, "    ...selectedRange failed.");
1448             completionHandlerBlock(NSMakeRange(NSNotFound, 0));
1449             return;
1450         }
1451         NSRange result = editingRangeResult;
1452         if (result.location == NSNotFound)
1453             LOG(TextInput, "    -> selectedRange returned (NSNotFound, %llu)", result.length);
1454         else
1455             LOG(TextInput, "    -> selectedRange returned (%llu, %llu)", result.location, result.length);
1456         completionHandlerBlock(result);
1457     }));
1458 }
1459
1460 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
1461 {
1462     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1463
1464     LOG(TextInput, "markedRange");
1465     _data->_page->getMarkedRangeAsync(EditingRangeCallback::create([completionHandler](bool error, const EditingRange& editingRangeResult) {
1466         void (^completionHandlerBlock)(NSRange) = (void (^)(NSRange))completionHandler.get();
1467         if (error) {
1468             LOG(TextInput, "    ...markedRange failed.");
1469             completionHandlerBlock(NSMakeRange(NSNotFound, 0));
1470             return;
1471         }
1472         NSRange result = editingRangeResult;
1473         if (result.location == NSNotFound)
1474             LOG(TextInput, "    -> markedRange returned (NSNotFound, %llu)", result.length);
1475         else
1476             LOG(TextInput, "    -> markedRange returned (%llu, %llu)", result.location, result.length);
1477         completionHandlerBlock(result);
1478     }));
1479 }
1480
1481 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
1482 {
1483     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1484
1485     LOG(TextInput, "hasMarkedText");
1486     _data->_page->getMarkedRangeAsync(EditingRangeCallback::create([completionHandler](bool error, const EditingRange& editingRangeResult) {
1487         void (^completionHandlerBlock)(BOOL) = (void (^)(BOOL))completionHandler.get();
1488         if (error) {
1489             LOG(TextInput, "    ...hasMarkedText failed.");
1490             completionHandlerBlock(NO);
1491             return;
1492         }
1493         BOOL hasMarkedText = editingRangeResult.location != notFound;
1494         LOG(TextInput, "    -> hasMarkedText returned %u", hasMarkedText);
1495         completionHandlerBlock(hasMarkedText);
1496     }));
1497 }
1498
1499 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
1500 {
1501     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1502
1503     LOG(TextInput, "attributedSubstringFromRange:(%u, %u)", nsRange.location, nsRange.length);
1504     _data->_page->attributedSubstringForCharacterRangeAsync(nsRange, AttributedStringForCharacterRangeCallback::create([completionHandler](bool error, const AttributedString& string, const EditingRange& actualRange) {
1505         void (^completionHandlerBlock)(NSAttributedString *, NSRange) = (void (^)(NSAttributedString *, NSRange))completionHandler.get();
1506         if (error) {
1507             LOG(TextInput, "    ...attributedSubstringFromRange failed.");
1508             completionHandlerBlock(0, NSMakeRange(NSNotFound, 0));
1509             return;
1510         }
1511         LOG(TextInput, "    -> attributedSubstringFromRange returned %@", [string.string.get() string]);
1512         completionHandlerBlock([[string.string.get() retain] autorelease], actualRange);
1513     }));
1514 }
1515
1516 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
1517 {
1518     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1519
1520     LOG(TextInput, "firstRectForCharacterRange:(%u, %u)", theRange.location, theRange.length);
1521
1522     // Just to match NSTextView's behavior. Regression tests cannot detect this;
1523     // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
1524     // (type something; try ranges (1, -1) and (2, -1).
1525     if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
1526         theRange.length = 0;
1527
1528     if (theRange.location == NSNotFound) {
1529         LOG(TextInput, "    -> NSZeroRect");
1530         completionHandlerPtr(NSZeroRect, theRange);
1531         return;
1532     }
1533
1534     _data->_page->firstRectForCharacterRangeAsync(theRange, RectForCharacterRangeCallback::create([self, completionHandler](bool error, const IntRect& rect, const EditingRange& actualRange) {
1535         void (^completionHandlerBlock)(NSRect, NSRange) = (void (^)(NSRect, NSRange))completionHandler.get();
1536         if (error) {
1537             LOG(TextInput, "    ...firstRectForCharacterRange failed.");
1538             completionHandlerBlock(NSZeroRect, NSMakeRange(NSNotFound, 0));
1539             return;
1540         }
1541
1542         NSRect resultRect = [self convertRect:rect toView:nil];
1543         resultRect = [self.window convertRectToScreen:resultRect];
1544
1545         LOG(TextInput, "    -> firstRectForCharacterRange returned (%f, %f, %f, %f)", resultRect.origin.x, resultRect.origin.y, resultRect.size.width, resultRect.size.height);
1546         completionHandlerBlock(resultRect, actualRange);
1547     }));
1548 }
1549
1550 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
1551 {
1552     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1553
1554     LOG(TextInput, "characterIndexForPoint:(%f, %f)", thePoint.x, thePoint.y);
1555
1556     NSWindow *window = [self window];
1557
1558 #pragma clang diagnostic push
1559 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1560     if (window)
1561         thePoint = [window convertScreenToBase:thePoint];
1562 #pragma clang diagnostic pop
1563     thePoint = [self convertPoint:thePoint fromView:nil];  // the point is relative to the main frame
1564
1565     _data->_page->characterIndexForPointAsync(IntPoint(thePoint), UnsignedCallback::create([completionHandler](bool error, uint64_t result) {
1566         void (^completionHandlerBlock)(NSUInteger) = (void (^)(NSUInteger))completionHandler.get();
1567         if (error) {
1568             LOG(TextInput, "    ...characterIndexForPoint failed.");
1569             completionHandlerBlock(0);
1570             return;
1571         }
1572         if (result == notFound)
1573             result = NSNotFound;
1574         LOG(TextInput, "    -> characterIndexForPoint returned %lu", result);
1575         completionHandlerBlock(result);
1576     }));
1577 }
1578
1579 - (NSTextInputContext *)inputContext
1580 {
1581     bool collectingKeypressCommands = _data->_collectedKeypressCommands;
1582
1583     if (_data->_pluginComplexTextInputIdentifier && !collectingKeypressCommands)
1584         return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
1585
1586     // Disable text input machinery when in non-editable content. An invisible inline input area affects performance, and can prevent Expose from working.
1587     if (!_data->_page->editorState().isContentEditable)
1588         return nil;
1589
1590     return [super inputContext];
1591 }
1592
1593 - (void)unmarkText
1594 {
1595     LOG(TextInput, "unmarkText");
1596
1597     _data->_page->confirmCompositionAsync();
1598 }
1599
1600 - (void)setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
1601 {
1602     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1603     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1604
1605     LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u) replacementRange:(%u, %u)", isAttributedString ? [string string] : string, selectedRange.location, selectedRange.length, replacementRange.location, replacementRange.length);
1606
1607     Vector<CompositionUnderline> underlines;
1608     NSString *text;
1609
1610     if (isAttributedString) {
1611         // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation.
1612         text = [string string];
1613         extractUnderlines(string, underlines);
1614     } else
1615         text = string;
1616
1617     if (_data->_inSecureInputState) {
1618         // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField.
1619         // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard.
1620         ASSERT(!_data->_page->editorState().hasComposition);
1621         [self _notifyInputContextAboutDiscardedComposition];
1622         // FIXME: We should store the command to handle it after DOM event processing, as it's regular keyboard input now, not a composition.
1623         if ([text length] == 1 && isASCII([text characterAtIndex:0]))
1624             _data->_page->insertTextAsync(text, replacementRange);
1625         else
1626             NSBeep();
1627         return;
1628     }
1629
1630     _data->_page->setCompositionAsync(text, underlines, selectedRange, replacementRange);
1631 }
1632
1633 // Synchronous NSTextInputClient is still implemented to catch spurious sync calls. Remove when that is no longer needed.
1634
1635 - (NSRange)selectedRange NO_RETURN_DUE_TO_ASSERT
1636 {
1637     ASSERT_NOT_REACHED();
1638     return NSMakeRange(NSNotFound, 0);
1639 }
1640
1641 - (BOOL)hasMarkedText NO_RETURN_DUE_TO_ASSERT
1642 {
1643     ASSERT_NOT_REACHED();
1644     return NO;
1645 }
1646
1647 - (NSRange)markedRange NO_RETURN_DUE_TO_ASSERT
1648 {
1649     ASSERT_NOT_REACHED();
1650     return NSMakeRange(NSNotFound, 0);
1651 }
1652
1653 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange NO_RETURN_DUE_TO_ASSERT
1654 {
1655     ASSERT_NOT_REACHED();
1656     return nil;
1657 }
1658
1659 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint NO_RETURN_DUE_TO_ASSERT
1660 {
1661     ASSERT_NOT_REACHED();
1662     return 0;
1663 }
1664
1665 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange NO_RETURN_DUE_TO_ASSERT
1666
1667     ASSERT_NOT_REACHED();
1668     return NSMakeRect(0, 0, 0, 0);
1669 }
1670
1671 - (BOOL)performKeyEquivalent:(NSEvent *)event
1672 {
1673     // There's a chance that responding to this event will run a nested event loop, and
1674     // fetching a new event might release the old one. Retaining and then autoreleasing
1675     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1676     [[event retain] autorelease];
1677
1678     // We get Esc key here after processing either Esc or Cmd+period. The former starts as a keyDown, and the latter starts as a key equivalent,
1679     // but both get transformed to a cancelOperation: command, executing which passes an Esc key event to -performKeyEquivalent:.
1680     // Don't interpret this event again, avoiding re-entrancy and infinite loops.
1681     if ([[event charactersIgnoringModifiers] isEqualToString:@"\e"] && !([event modifierFlags] & NSDeviceIndependentModifierFlagsMask))
1682         return [super performKeyEquivalent:event];
1683
1684     if (_data->_keyDownEventBeingResent) {
1685         // WebCore has already seen the event, no need for custom processing.
1686         // Note that we can get multiple events for each event being re-sent. For example, for Cmd+'=' AppKit
1687         // first performs the original key equivalent, and if that isn't handled, it dispatches a synthetic Cmd+'+'.
1688         return [super performKeyEquivalent:event];
1689     }
1690
1691     ASSERT(event == [NSApp currentEvent]);
1692
1693     [self _disableComplexTextInputIfNecessary];
1694
1695     // Pass key combos through WebCore if there is a key binding available for
1696     // this event. This lets web pages have a crack at intercepting key-modified keypresses.
1697     // FIXME: Why is the firstResponder check needed?
1698     if (self == [[self window] firstResponder]) {
1699         [self _interpretKeyEvent:event completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1700             _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, handledByInputMethod, commands));
1701         }];
1702         return YES;
1703     }
1704     
1705     return [super performKeyEquivalent:event];
1706 }
1707
1708 - (void)keyUp:(NSEvent *)theEvent
1709 {
1710     LOG(TextInput, "keyUp:%p %@", theEvent, theEvent);
1711
1712     [self _interpretKeyEvent:theEvent completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1713         ASSERT(!handledByInputMethod || commands.isEmpty());
1714         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
1715     }];
1716 }
1717
1718 - (void)keyDown:(NSEvent *)theEvent
1719 {
1720     LOG(TextInput, "keyDown:%p %@%s", theEvent, theEvent, (theEvent == _data->_keyDownEventBeingResent) ? " (re-sent)" : "");
1721
1722     if ([self _tryHandlePluginComplexTextInputKeyDown:theEvent]) {
1723         LOG(TextInput, "...handled by plug-in");
1724         return;
1725     }
1726
1727     // We could be receiving a key down from AppKit if we have re-sent an event
1728     // that maps to an action that is currently unavailable (for example a copy when
1729     // there is no range selection).
1730     // If this is the case we should ignore the key down.
1731     if (_data->_keyDownEventBeingResent == theEvent) {
1732         [super keyDown:theEvent];
1733         return;
1734     }
1735
1736     [self _interpretKeyEvent:theEvent completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1737         ASSERT(!handledByInputMethod || commands.isEmpty());
1738         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
1739     }];
1740 }
1741
1742 - (void)flagsChanged:(NSEvent *)theEvent
1743 {
1744     LOG(TextInput, "flagsChanged:%p %@", theEvent, theEvent);
1745
1746     unsigned short keyCode = [theEvent keyCode];
1747
1748     // Don't make an event from the num lock and function keys
1749     if (!keyCode || keyCode == 10 || keyCode == 63)
1750         return;
1751
1752     [self _interpretKeyEvent:theEvent completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1753         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
1754     }];
1755 }
1756
1757 #else // USE(ASYNC_NSTEXTINPUTCLIENT)
1758
1759 - (BOOL)_interpretKeyEvent:(NSEvent *)event savingCommandsTo:(Vector<WebCore::KeypressCommand>&)commands
1760 {
1761     ASSERT(!_data->_interpretKeyEventsParameters);
1762     ASSERT(commands.isEmpty());
1763
1764     if ([event type] == NSFlagsChanged)
1765         return NO;
1766
1767     WKViewInterpretKeyEventsParameters parameters;
1768     parameters.eventInterpretationHadSideEffects = false;
1769     parameters.executingSavedKeypressCommands = false;
1770     // We assume that an input method has consumed the event, and only change this assumption if one of the NSTextInput methods is called.
1771     // We assume the IM will *not* consume hotkey sequences.
1772     parameters.consumedByIM = !([event modifierFlags] & NSCommandKeyMask);
1773     parameters.commands = &commands;
1774     _data->_interpretKeyEventsParameters = &parameters;
1775
1776     LOG(TextInput, "-> interpretKeyEvents:%p %@", event, event);
1777     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
1778
1779     _data->_interpretKeyEventsParameters = nullptr;
1780
1781     // An input method may consume an event and not tell us (e.g. when displaying a candidate window),
1782     // in which case we should not bubble the event up the DOM.
1783     if (parameters.consumedByIM) {
1784         ASSERT(commands.isEmpty());
1785         LOG(TextInput, "...event %p was consumed by an input method", event);
1786         return YES;
1787     }
1788
1789     LOG(TextInput, "...interpretKeyEvents for event %p done, returns %d", event, parameters.eventInterpretationHadSideEffects);
1790
1791     // 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.
1792     return parameters.eventInterpretationHadSideEffects;
1793 }
1794
1795 - (void)_executeSavedKeypressCommands
1796 {
1797     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1798     if (!parameters || parameters->commands->isEmpty())
1799         return;
1800
1801     // We could be called again if the execution of one command triggers a call to selectedRange.
1802     // In this case, the state is up to date, and we don't need to execute any more saved commands to return a result.
1803     if (parameters->executingSavedKeypressCommands)
1804         return;
1805
1806     LOG(TextInput, "Executing %u saved keypress commands...", parameters->commands->size());
1807
1808     parameters->executingSavedKeypressCommands = true;
1809     parameters->eventInterpretationHadSideEffects |= _data->_page->executeKeypressCommands(*parameters->commands);
1810     parameters->commands->clear();
1811     parameters->executingSavedKeypressCommands = false;
1812
1813     LOG(TextInput, "...done executing saved keypress commands.");
1814 }
1815
1816 - (void)doCommandBySelector:(SEL)selector
1817 {
1818     LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector));
1819
1820     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1821     if (parameters)
1822         parameters->consumedByIM = false;
1823
1824     // As in insertText:replacementRange:, we assume that the call comes from an input method if there is marked text.
1825     bool isFromInputMethod = _data->_page->editorState().hasComposition;
1826
1827     if (parameters && !isFromInputMethod) {
1828         KeypressCommand command(NSStringFromSelector(selector));
1829         parameters->commands->append(command);
1830         LOG(TextInput, "...stored");
1831         _data->_page->registerKeypressCommandName(command.commandName);
1832     } else {
1833         // FIXME: Send the command to Editor synchronously and only send it along the
1834         // responder chain if it's a selector that does not correspond to an editing command.
1835         [super doCommandBySelector:selector];
1836     }
1837 }
1838
1839 - (void)insertText:(id)string
1840 {
1841     // Unlike an NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context,
1842     // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText
1843     // command ensures that a keypress event is dispatched as appropriate.
1844     [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
1845 }
1846
1847 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
1848 {
1849     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1850     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1851
1852     if (replacementRange.location != NSNotFound)
1853         LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length);
1854     else
1855         LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
1856     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1857     if (parameters)
1858         parameters->consumedByIM = false;
1859
1860     NSString *text;
1861     bool isFromInputMethod = _data->_page->editorState().hasComposition;
1862
1863     Vector<TextAlternativeWithRange> dictationAlternatives;
1864
1865     if (isAttributedString) {
1866 #if USE(DICTATION_ALTERNATIVES)
1867         collectDictationTextAlternatives(string, dictationAlternatives);
1868 #endif
1869         // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data.
1870         text = [string string];
1871     } else
1872         text = string;
1873
1874     // insertText can be called for several reasons:
1875     // - If it's from normal key event processing (including key bindings), we may need to save the action to perform it later.
1876     // - 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.
1877     // 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.
1878     // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse),
1879     // then we also execute it immediately, as there will be no other chance.
1880     if (parameters && !isFromInputMethod) {
1881         // FIXME: Handle replacementRange in this case, too. It's known to occur in practice when canceling Press and Hold (see <rdar://11940670>).
1882         ASSERT(replacementRange.location == NSNotFound);
1883         KeypressCommand command("insertText:", text);
1884         parameters->commands->append(command);
1885         _data->_page->registerKeypressCommandName(command.commandName);
1886         return;
1887     }
1888
1889     String eventText = text;
1890     eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
1891     bool eventHandled;
1892     if (!dictationAlternatives.isEmpty())
1893         eventHandled = _data->_page->insertDictatedText(eventText, replacementRange, dictationAlternatives);
1894     else
1895         eventHandled = _data->_page->insertText(eventText, replacementRange);
1896
1897     if (parameters)
1898         parameters->eventInterpretationHadSideEffects |= eventHandled;
1899 }
1900
1901 - (NSRange)selectedRange
1902 {
1903     [self _executeSavedKeypressCommands];
1904
1905     EditingRange selectedRange;
1906     _data->_page->getSelectedRange(selectedRange);
1907
1908     NSRange result = selectedRange;
1909     if (result.location == NSNotFound)
1910         LOG(TextInput, "selectedRange -> (NSNotFound, %u)", result.length);
1911     else
1912         LOG(TextInput, "selectedRange -> (%u, %u)", result.location, result.length);
1913
1914     return result;
1915 }
1916
1917 - (BOOL)hasMarkedText
1918 {
1919     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1920
1921     BOOL result;
1922     if (parameters) {
1923         result = _data->_page->editorState().hasComposition;
1924         if (result) {
1925             // A saved command can confirm a composition, but it cannot start a new one.
1926             [self _executeSavedKeypressCommands];
1927             result = _data->_page->editorState().hasComposition;
1928         }
1929     } else {
1930         EditingRange markedRange;
1931         _data->_page->getMarkedRange(markedRange);
1932         result = markedRange.location != notFound;
1933     }
1934
1935     LOG(TextInput, "hasMarkedText -> %u", result);
1936     return result;
1937 }
1938
1939 - (void)unmarkText
1940 {
1941     [self _executeSavedKeypressCommands];
1942
1943     LOG(TextInput, "unmarkText");
1944
1945     // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
1946     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1947
1948     if (parameters) {
1949         parameters->eventInterpretationHadSideEffects = true;
1950         parameters->consumedByIM = false;
1951     }
1952
1953     _data->_page->confirmComposition();
1954 }
1955
1956 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
1957 {
1958     [self _executeSavedKeypressCommands];
1959
1960     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1961     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1962
1963     LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelectedRange.location, newSelectedRange.length);
1964
1965     // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
1966     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1967
1968     if (parameters) {
1969         parameters->eventInterpretationHadSideEffects = true;
1970         parameters->consumedByIM = false;
1971     }
1972     
1973     Vector<CompositionUnderline> underlines;
1974     NSString *text;
1975
1976     if (isAttributedString) {
1977         // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation.
1978         text = [string string];
1979         extractUnderlines(string, underlines);
1980     } else
1981         text = string;
1982
1983     if (_data->_page->editorState().isInPasswordField) {
1984         // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField.
1985         // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard.
1986         ASSERT(!_data->_page->editorState().hasComposition);
1987         [self _notifyInputContextAboutDiscardedComposition];
1988         if ([text length] == 1 && [[text decomposedStringWithCanonicalMapping] characterAtIndex:0] < 0x80) {
1989             _data->_page->insertText(text, replacementRange);
1990         } else
1991             NSBeep();
1992         return;
1993     }
1994
1995     _data->_page->setComposition(text, underlines, newSelectedRange, replacementRange);
1996 }
1997
1998 - (NSRange)markedRange
1999 {
2000     [self _executeSavedKeypressCommands];
2001
2002     EditingRange markedRange;
2003     _data->_page->getMarkedRange(markedRange);
2004
2005     NSRange result = markedRange;
2006     if (result.location == NSNotFound)
2007         LOG(TextInput, "markedRange -> (NSNotFound, %u)", result.length);
2008     else
2009         LOG(TextInput, "markedRange -> (%u, %u)", result.location, result.length);
2010
2011     return result;
2012 }
2013
2014 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
2015 {
2016     [self _executeSavedKeypressCommands];
2017
2018     if (!_data->_page->editorState().isContentEditable) {
2019         LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> nil", nsRange.location, nsRange.length);
2020         return nil;
2021     }
2022
2023     if (_data->_page->editorState().isInPasswordField)
2024         return nil;
2025
2026     AttributedString result;
2027     _data->_page->getAttributedSubstringFromRange(nsRange, result);
2028
2029     if (actualRange) {
2030         *actualRange = nsRange;
2031         actualRange->length = [result.string length];
2032     }
2033
2034     LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> \"%@\"", nsRange.location, nsRange.length, [result.string string]);
2035     return [[result.string retain] autorelease];
2036 }
2037
2038 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
2039 {
2040     [self _executeSavedKeypressCommands];
2041
2042     NSWindow *window = [self window];
2043     
2044 #pragma clang diagnostic push
2045 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2046     if (window)
2047         thePoint = [window convertScreenToBase:thePoint];
2048 #pragma clang diagnostic pop
2049     thePoint = [self convertPoint:thePoint fromView:nil];  // the point is relative to the main frame
2050     
2051     uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint));
2052     if (result == notFound)
2053         result = NSNotFound;
2054     LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result);
2055     return result;
2056 }
2057
2058 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
2059
2060     [self _executeSavedKeypressCommands];
2061
2062     // Just to match NSTextView's behavior. Regression tests cannot detect this;
2063     // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
2064     // (type something; try ranges (1, -1) and (2, -1).
2065     if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
2066         theRange.length = 0;
2067
2068     if (theRange.location == NSNotFound) {
2069         if (actualRange)
2070             *actualRange = theRange;
2071         LOG(TextInput, "firstRectForCharacterRange:(NSNotFound, %u) -> NSZeroRect", theRange.length);
2072         return NSZeroRect;
2073     }
2074
2075     NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange);
2076     resultRect = [self convertRect:resultRect toView:nil];
2077     resultRect = [self.window convertRectToScreen:resultRect];
2078
2079     if (actualRange) {
2080         // FIXME: Update actualRange to match the range of first rect.
2081         *actualRange = theRange;
2082     }
2083
2084     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);
2085     return resultRect;
2086 }
2087
2088 - (BOOL)performKeyEquivalent:(NSEvent *)event
2089 {
2090     // There's a chance that responding to this event will run a nested event loop, and
2091     // fetching a new event might release the old one. Retaining and then autoreleasing
2092     // the current event prevents that from causing a problem inside WebKit or AppKit code.
2093     [[event retain] autorelease];
2094
2095     // We get Esc key here after processing either Esc or Cmd+period. The former starts as a keyDown, and the latter starts as a key equivalent,
2096     // but both get transformed to a cancelOperation: command, executing which passes an Esc key event to -performKeyEquivalent:.
2097     // Don't interpret this event again, avoiding re-entrancy and infinite loops.
2098     if ([[event charactersIgnoringModifiers] isEqualToString:@"\e"] && !([event modifierFlags] & NSDeviceIndependentModifierFlagsMask))
2099         return [super performKeyEquivalent:event];
2100
2101     if (_data->_keyDownEventBeingResent) {
2102         // WebCore has already seen the event, no need for custom processing.
2103         // Note that we can get multiple events for each event being re-sent. For example, for Cmd+'=' AppKit
2104         // first performs the original key equivalent, and if that isn't handled, it dispatches a synthetic Cmd+'+'.
2105         return [super performKeyEquivalent:event];
2106     }
2107
2108     ASSERT(event == [NSApp currentEvent]);
2109
2110     [self _disableComplexTextInputIfNecessary];
2111
2112     // Pass key combos through WebCore if there is a key binding available for
2113     // this event. This lets web pages have a crack at intercepting key-modified keypresses.
2114     // FIXME: Why is the firstResponder check needed?
2115     if (self == [[self window] firstResponder]) {
2116         Vector<KeypressCommand> commands;
2117         BOOL handledByInputMethod = [self _interpretKeyEvent:event savingCommandsTo:commands];
2118         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, handledByInputMethod, commands));
2119         return YES;
2120     }
2121     
2122     return [super performKeyEquivalent:event];
2123 }
2124
2125 - (void)keyUp:(NSEvent *)theEvent
2126 {
2127     LOG(TextInput, "keyUp:%p %@", theEvent, theEvent);
2128     // We don't interpret the keyUp event, as this breaks key bindings (see <https://bugs.webkit.org/show_bug.cgi?id=130100>).
2129     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, false, Vector<KeypressCommand>()));
2130 }
2131
2132 - (void)keyDown:(NSEvent *)theEvent
2133 {
2134     LOG(TextInput, "keyDown:%p %@%s", theEvent, theEvent, (theEvent == _data->_keyDownEventBeingResent) ? " (re-sent)" : "");
2135
2136     // There's a chance that responding to this event will run a nested event loop, and
2137     // fetching a new event might release the old one. Retaining and then autoreleasing
2138     // the current event prevents that from causing a problem inside WebKit or AppKit code.
2139     [[theEvent retain] autorelease];
2140
2141     if ([self _tryHandlePluginComplexTextInputKeyDown:theEvent]) {
2142         LOG(TextInput, "...handled by plug-in");
2143         return;
2144     }
2145
2146     // We could be receiving a key down from AppKit if we have re-sent an event
2147     // that maps to an action that is currently unavailable (for example a copy when
2148     // there is no range selection).
2149     // If this is the case we should ignore the key down.
2150     if (_data->_keyDownEventBeingResent == theEvent) {
2151         [super keyDown:theEvent];
2152         return;
2153     }
2154
2155     Vector<KeypressCommand> commands;
2156     BOOL handledByInputMethod = [self _interpretKeyEvent:theEvent savingCommandsTo:commands];
2157     if (!commands.isEmpty()) {
2158         // An input method may make several actions per keypress. For example, pressing Return with Korean IM both confirms it and sends a newline.
2159         // IM-like actions are handled immediately (so the return value from UI process is true), but there are saved commands that
2160         // should be handled like normal text input after DOM event dispatch.
2161         handledByInputMethod = NO;
2162     }
2163
2164     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
2165 }
2166
2167 - (void)flagsChanged:(NSEvent *)theEvent
2168 {
2169     LOG(TextInput, "flagsChanged:%p %@", theEvent, theEvent);
2170
2171     // There's a chance that responding to this event will run a nested event loop, and
2172     // fetching a new event might release the old one. Retaining and then autoreleasing
2173     // the current event prevents that from causing a problem inside WebKit or AppKit code.
2174     [[theEvent retain] autorelease];
2175
2176     unsigned short keyCode = [theEvent keyCode];
2177
2178     // Don't make an event from the num lock and function keys
2179     if (!keyCode || keyCode == 10 || keyCode == 63)
2180         return;
2181
2182     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, false, Vector<KeypressCommand>()));
2183 }
2184
2185 #endif // USE(ASYNC_NSTEXTINPUTCLIENT)
2186
2187 - (NSArray *)validAttributesForMarkedText
2188 {
2189     static NSArray *validAttributes;
2190     if (!validAttributes) {
2191         validAttributes = [[NSArray alloc] initWithObjects:
2192                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
2193                            NSMarkedClauseSegmentAttributeName,
2194 #if USE(DICTATION_ALTERNATIVES)
2195                            NSTextAlternativesAttributeName,
2196 #endif
2197                            nil];
2198         // NSText also supports the following attributes, but it's
2199         // hard to tell which are really required for text input to
2200         // work well; I have not seen any input method make use of them yet.
2201         //     NSFontAttributeName, NSForegroundColorAttributeName,
2202         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
2203         CFRetain(validAttributes);
2204     }
2205     LOG(TextInput, "validAttributesForMarkedText -> (...)");
2206     return validAttributes;
2207 }
2208
2209 #if ENABLE(DRAG_SUPPORT)
2210 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2211 {
2212     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2213     NSPoint windowMouseLoc = windowImageLoc;
2214    
2215     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2216     _data->_ignoringMouseDraggedEvents = YES;
2217     
2218     _data->_page->dragEnded(IntPoint(windowMouseLoc), globalPoint(windowMouseLoc, [self window]), operation);
2219 }
2220
2221 - (DragApplicationFlags)applicationFlags:(id <NSDraggingInfo>)draggingInfo
2222 {
2223     uint32_t flags = 0;
2224     if ([NSApp modalWindow])
2225         flags = DragApplicationIsModal;
2226     if ([[self window] attachedSheet])
2227         flags |= DragApplicationHasAttachedSheet;
2228     if ([draggingInfo draggingSource] == self)
2229         flags |= DragApplicationIsSource;
2230     if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
2231         flags |= DragApplicationIsCopyKeyDown;
2232     return static_cast<DragApplicationFlags>(flags);
2233 }
2234
2235 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2236 {
2237     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2238     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2239     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2240
2241     _data->_page->resetCurrentDragInformation();
2242     _data->_page->dragEntered(dragData, [[draggingInfo draggingPasteboard] name]);
2243     return NSDragOperationCopy;
2244 }
2245
2246 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2247 {
2248     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2249     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2250     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2251     _data->_page->dragUpdated(dragData, [[draggingInfo draggingPasteboard] name]);
2252     
2253     NSInteger numberOfValidItemsForDrop = _data->_page->currentDragNumberOfFilesToBeAccepted();
2254     NSDraggingFormation draggingFormation = NSDraggingFormationNone;
2255     if (_data->_page->currentDragIsOverFileInput() && numberOfValidItemsForDrop > 0)
2256         draggingFormation = NSDraggingFormationList;
2257
2258     if ([draggingInfo numberOfValidItemsForDrop] != numberOfValidItemsForDrop)
2259         [draggingInfo setNumberOfValidItemsForDrop:numberOfValidItemsForDrop];
2260     if ([draggingInfo draggingFormation] != draggingFormation)
2261         [draggingInfo setDraggingFormation:draggingFormation];
2262
2263     return _data->_page->currentDragOperation();
2264 }
2265
2266 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2267 {
2268     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2269     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2270     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2271     _data->_page->dragExited(dragData, [[draggingInfo draggingPasteboard] name]);
2272     _data->_page->resetCurrentDragInformation();
2273 }
2274
2275 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2276 {
2277     return YES;
2278 }
2279
2280 // FIXME: This code is more or less copied from Pasteboard::getBestURL.
2281 // It would be nice to be able to share the code somehow.
2282 static bool maybeCreateSandboxExtensionFromPasteboard(NSPasteboard *pasteboard, SandboxExtension::Handle& sandboxExtensionHandle)
2283 {
2284     NSArray *types = [pasteboard types];
2285     if (![types containsObject:NSFilenamesPboardType])
2286         return false;
2287
2288     NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
2289     if ([files count] != 1)
2290         return false;
2291
2292     NSString *file = [files objectAtIndex:0];
2293     BOOL isDirectory;
2294     if (![[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory])
2295         return false;
2296
2297     if (isDirectory)
2298         return false;
2299
2300     SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle);
2301     return true;
2302 }
2303
2304 static void createSandboxExtensionsForFileUpload(NSPasteboard *pasteboard, SandboxExtension::HandleArray& handles)
2305 {
2306     NSArray *types = [pasteboard types];
2307     if (![types containsObject:NSFilenamesPboardType])
2308         return;
2309
2310     NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
2311     handles.allocate([files count]);
2312     for (unsigned i = 0; i < [files count]; i++) {
2313         NSString *file = [files objectAtIndex:i];
2314         if (![[NSFileManager defaultManager] fileExistsAtPath:file])
2315             continue;
2316         SandboxExtension::Handle handle;
2317         SandboxExtension::createHandle(file, SandboxExtension::ReadOnly, handles[i]);
2318     }
2319 }
2320
2321 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2322 {
2323     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2324     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2325     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2326
2327     SandboxExtension::Handle sandboxExtensionHandle;
2328     bool createdExtension = maybeCreateSandboxExtensionFromPasteboard([draggingInfo draggingPasteboard], sandboxExtensionHandle);
2329     if (createdExtension)
2330         _data->_page->process().willAcquireUniversalFileReadSandboxExtension();
2331
2332     SandboxExtension::HandleArray sandboxExtensionForUpload;
2333     createSandboxExtensionsForFileUpload([draggingInfo draggingPasteboard], sandboxExtensionForUpload);
2334
2335     _data->_page->performDragOperation(dragData, [[draggingInfo draggingPasteboard] name], sandboxExtensionHandle, sandboxExtensionForUpload);
2336
2337     return YES;
2338 }
2339
2340 // This code is needed to support drag and drop when the drag types cannot be matched.
2341 // This is the case for elements that do not place content
2342 // in the drag pasteboard automatically when the drag start (i.e. dragging a DIV element).
2343 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
2344 {
2345     if ([[self superview] mouse:*point inRect:[self frame]])
2346         return self;
2347     return nil;
2348 }
2349 #endif // ENABLE(DRAG_SUPPORT)
2350
2351 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)loc
2352 {
2353     NSPoint localPoint = [self convertPoint:loc fromView:nil];
2354     NSRect visibleThumbRect = NSRect(_data->_page->visibleScrollerThumbRect());
2355     return NSMouseInRect(localPoint, visibleThumbRect, [self isFlipped]);
2356 }
2357
2358 - (void)addWindowObserversForWindow:(NSWindow *)window
2359 {
2360     if (window) {
2361         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
2362                                                      name:NSWindowDidBecomeKeyNotification object:nil];
2363         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
2364                                                      name:NSWindowDidResignKeyNotification object:nil];
2365         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) 
2366                                                      name:NSWindowDidMiniaturizeNotification object:window];
2367         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
2368                                                      name:NSWindowDidDeminiaturizeNotification object:window];
2369         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMove:)
2370                                                      name:NSWindowDidMoveNotification object:window];
2371         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResize:) 
2372                                                      name:NSWindowDidResizeNotification object:window];
2373         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOffScreen:) 
2374                                                      name:@"NSWindowDidOrderOffScreenNotification" object:window];
2375         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOnScreen:) 
2376                                                      name:@"_NSWindowDidBecomeVisible" object:window];
2377         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeBackingProperties:)
2378                                                      name:NSWindowDidChangeBackingPropertiesNotification object:window];
2379         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeScreen:)
2380                                                      name:NSWindowDidChangeScreenNotification object:window];
2381         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeLayerHosting:)
2382                                                      name:@"_NSWindowDidChangeContentsHostedInLayerSurfaceNotification" object:window];
2383 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2384         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeOcclusionState:)
2385                                                      name:NSWindowDidChangeOcclusionStateNotification object:window];
2386 #endif
2387     }
2388 }
2389
2390 - (void)removeWindowObservers
2391 {
2392     NSWindow *window = [self window];
2393     if (!window)
2394         return;
2395
2396     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
2397     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
2398     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
2399     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
2400     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
2401     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
2402     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowWillOrderOffScreenNotification" object:window];
2403     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowDidOrderOffScreenNotification" object:window];
2404     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"_NSWindowDidBecomeVisible" object:window];
2405     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeBackingPropertiesNotification object:window];
2406     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeScreenNotification object:window];
2407     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"_NSWindowDidChangeContentsHostedInLayerSurfaceNotification" object:window];
2408 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2409     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeOcclusionStateNotification object:window];
2410 #endif
2411 }
2412
2413 - (void)viewWillMoveToWindow:(NSWindow *)window
2414 {
2415     NSWindow *currentWindow = [self window];
2416     if (window == currentWindow)
2417         return;
2418
2419     _data->_pageClient->viewWillMoveToAnotherWindow();
2420     
2421     [self removeWindowObservers];
2422     [self addWindowObserversForWindow:window];
2423 }
2424
2425 - (void)viewDidMoveToWindow
2426 {
2427     if ([self window]) {
2428         [self doWindowDidChangeScreen];
2429
2430         ViewState::Flags viewStateChanges = ViewState::WindowIsActive | ViewState::IsVisible;
2431         if ([self isDeferringViewInWindowChanges])
2432             _data->_viewInWindowChangeWasDeferred = YES;
2433         else
2434             viewStateChanges |= ViewState::IsInWindow;
2435         _data->_page->viewStateDidChange(viewStateChanges);
2436
2437         [self _updateWindowAndViewFrames];
2438
2439         if (!_data->_flagsChangedEventMonitor) {
2440             _data->_flagsChangedEventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSFlagsChangedMask handler:^(NSEvent *flagsChangedEvent) {
2441                 [self _postFakeMouseMovedEventForFlagsChangedEvent:flagsChangedEvent];
2442                 return flagsChangedEvent;
2443             }];
2444         }
2445
2446         [self _accessibilityRegisterUIProcessTokens];
2447     } else {
2448         ViewState::Flags viewStateChanges = ViewState::WindowIsActive | ViewState::IsVisible;
2449         if ([self isDeferringViewInWindowChanges])
2450             _data->_viewInWindowChangeWasDeferred = YES;
2451         else
2452             viewStateChanges |= ViewState::IsInWindow;
2453         _data->_page->viewStateDidChange(viewStateChanges);
2454
2455         [NSEvent removeMonitor:_data->_flagsChangedEventMonitor];
2456         _data->_flagsChangedEventMonitor = nil;
2457
2458         WKHideWordDefinitionWindow();
2459     }
2460
2461     _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]);
2462 }
2463
2464 - (void)doWindowDidChangeScreen
2465 {
2466     _data->_page->windowScreenDidChange((PlatformDisplayID)[[[[[self window] screen] deviceDescription] objectForKey:@"NSScreenNumber"] intValue]);
2467 }
2468
2469 - (void)_windowDidBecomeKey:(NSNotification *)notification
2470 {
2471     NSWindow *keyWindow = [notification object];
2472     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet]) {
2473         [self _updateSecureInputState];
2474         _data->_page->viewStateDidChange(ViewState::WindowIsActive);
2475     }
2476 }
2477
2478 - (void)_windowDidChangeScreen:(NSNotification *)notification
2479 {
2480     [self doWindowDidChangeScreen];
2481 }
2482
2483 - (void)_windowDidChangeLayerHosting:(NSNotification *)notification
2484 {
2485     _data->_page->layerHostingModeDidChange();
2486 }
2487
2488 - (void)_windowDidResignKey:(NSNotification *)notification
2489 {
2490     NSWindow *formerKeyWindow = [notification object];
2491     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) {
2492         [self _updateSecureInputState];
2493         _data->_page->viewStateDidChange(ViewState::WindowIsActive);
2494     }
2495 }
2496
2497 - (void)_windowDidMiniaturize:(NSNotification *)notification
2498 {
2499     _data->_page->viewStateDidChange(ViewState::IsVisible);
2500 }
2501
2502 - (void)_windowDidDeminiaturize:(NSNotification *)notification
2503 {
2504     _data->_page->viewStateDidChange(ViewState::IsVisible);
2505 }
2506
2507 - (void)_windowDidMove:(NSNotification *)notification
2508 {
2509     [self _updateWindowAndViewFrames];    
2510 }
2511
2512 - (void)_windowDidResize:(NSNotification *)notification
2513 {
2514     [self _updateWindowAndViewFrames];
2515 }
2516
2517 - (void)_windowDidOrderOffScreen:(NSNotification *)notification
2518 {
2519     _data->_page->viewStateDidChange(ViewState::IsVisible | ViewState::WindowIsActive);
2520 }
2521
2522 - (void)_windowDidOrderOnScreen:(NSNotification *)notification
2523 {
2524     _data->_page->viewStateDidChange(ViewState::IsVisible | ViewState::WindowIsActive);
2525 }
2526
2527 - (void)_windowDidChangeBackingProperties:(NSNotification *)notification
2528 {
2529     CGFloat oldBackingScaleFactor = [[notification.userInfo objectForKey:NSBackingPropertyOldScaleFactorKey] doubleValue];
2530     CGFloat newBackingScaleFactor = [self _intrinsicDeviceScaleFactor]; 
2531     if (oldBackingScaleFactor == newBackingScaleFactor)
2532         return; 
2533
2534     _data->_page->setIntrinsicDeviceScaleFactor(newBackingScaleFactor);
2535 }
2536
2537 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2538 - (void)_windowDidChangeOcclusionState:(NSNotification *)notification
2539 {
2540     _data->_page->viewStateDidChange(ViewState::IsVisible);
2541 }
2542 #endif
2543
2544 - (void)drawRect:(NSRect)rect
2545 {
2546     LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
2547     _data->_page->endPrinting();
2548 }
2549
2550 - (BOOL)isOpaque
2551 {
2552     return _data->_page->drawsBackground();
2553 }
2554
2555 - (BOOL)mouseDownCanMoveWindow
2556 {
2557     // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent,
2558     // but we don't want a drag in the NSView to move the window, even if it's transparent.
2559     return NO;
2560 }
2561
2562 - (void)viewDidHide
2563 {
2564     _data->_page->viewStateDidChange(ViewState::IsVisible);
2565 }
2566
2567 - (void)viewDidUnhide
2568 {
2569     _data->_page->viewStateDidChange(ViewState::IsVisible);
2570 }
2571
2572 - (void)viewDidChangeBackingProperties
2573 {
2574     NSColorSpace *colorSpace = [[self window] colorSpace];
2575     if ([colorSpace isEqualTo:_data->_colorSpace.get()])
2576         return;
2577
2578     _data->_colorSpace = nullptr;
2579     if (DrawingAreaProxy *drawingArea = _data->_page->drawingArea())
2580         drawingArea->colorSpaceDidChange();
2581 }
2582
2583 - (void)_activeSpaceDidChange:(NSNotification *)notification
2584 {
2585     _data->_page->viewStateDidChange(ViewState::IsVisible);
2586 }
2587
2588 - (void)_accessibilityRegisterUIProcessTokens
2589 {
2590     // Initialize remote accessibility when the window connection has been established.
2591     NSData *remoteElementToken = WKAXRemoteTokenForElement(self);
2592     NSData *remoteWindowToken = WKAXRemoteTokenForElement([self window]);
2593     IPC::DataReference elementToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteElementToken bytes]), [remoteElementToken length]);
2594     IPC::DataReference windowToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteWindowToken bytes]), [remoteWindowToken length]);
2595     _data->_page->registerUIProcessAccessibilityTokens(elementToken, windowToken);
2596 }
2597
2598 - (void)_updateRemoteAccessibilityRegistration:(BOOL)registerProcess
2599 {
2600     // When the tree is connected/disconnected, the remote accessibility registration
2601     // needs to be updated with the pid of the remote process. If the process is going
2602     // away, that information is not present in WebProcess
2603     pid_t pid = 0;
2604     if (registerProcess)
2605         pid = _data->_page->process().processIdentifier();
2606     else if (!registerProcess) {
2607         pid = WKAXRemoteProcessIdentifier(_data->_remoteAccessibilityChild.get());
2608         _data->_remoteAccessibilityChild = nil;
2609     }
2610     if (pid)
2611         WKAXRegisterRemoteProcess(registerProcess, pid); 
2612 }
2613
2614 - (void)enableAccessibilityIfNecessary
2615 {
2616     if (WebCore::AXObjectCache::accessibilityEnabled())
2617         return;
2618
2619     // After enabling accessibility update the window frame on the web process so that the
2620     // correct accessibility position is transmitted (when AX is off, that position is not calculated).
2621     WebCore::AXObjectCache::enableAccessibility();
2622     [self _updateWindowAndViewFrames];
2623 }
2624
2625 - (id)accessibilityFocusedUIElement
2626 {
2627     [self enableAccessibilityIfNecessary];
2628     return _data->_remoteAccessibilityChild.get();
2629 }
2630
2631 - (BOOL)accessibilityIsIgnored
2632 {
2633     return NO;
2634 }
2635
2636 - (id)accessibilityHitTest:(NSPoint)point
2637 {
2638     [self enableAccessibilityIfNecessary];
2639     return _data->_remoteAccessibilityChild.get();
2640 }
2641
2642 - (id)accessibilityAttributeValue:(NSString*)attribute
2643 {
2644     [self enableAccessibilityIfNecessary];
2645
2646     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
2647
2648         id child = nil;
2649         if (_data->_remoteAccessibilityChild)
2650             child = _data->_remoteAccessibilityChild.get();
2651         
2652         if (!child)
2653             return nil;
2654         return [NSArray arrayWithObject:child];
2655     }
2656     if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
2657         return NSAccessibilityGroupRole;
2658     if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
2659         return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil);
2660     if ([attribute isEqualToString:NSAccessibilityParentAttribute])
2661         return NSAccessibilityUnignoredAncestor([self superview]);
2662     if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
2663         return [NSNumber numberWithBool:YES];
2664     
2665     return [super accessibilityAttributeValue:attribute];
2666 }
2667
2668 - (NSView *)hitTest:(NSPoint)point
2669 {
2670     NSView *hitView = [super hitTest:point];
2671     if (hitView && _data && hitView == _data->_layerHostingView)
2672         hitView = self;
2673
2674     return hitView;
2675 }
2676
2677 - (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent
2678 {
2679     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved location:[[flagsChangedEvent window] mouseLocationOutsideOfEventStream]
2680         modifierFlags:[flagsChangedEvent modifierFlags] timestamp:[flagsChangedEvent timestamp] windowNumber:[flagsChangedEvent windowNumber]
2681         context:[flagsChangedEvent context] eventNumber:0 clickCount:0 pressure:0];
2682     NativeWebMouseEvent webEvent(fakeEvent, self);
2683     _data->_page->handleMouseEvent(webEvent);
2684 }
2685
2686 - (NSInteger)conversationIdentifier
2687 {
2688     return (NSInteger)self;
2689 }
2690
2691 - (float)_intrinsicDeviceScaleFactor
2692 {
2693     NSWindow *window = [self window];
2694     if (window)
2695         return [window backingScaleFactor];
2696     return [[NSScreen mainScreen] backingScaleFactor];
2697 }
2698
2699 - (void)_setDrawingAreaSize:(NSSize)size
2700 {
2701     if (!_data->_page->drawingArea())
2702         return;
2703     
2704     _data->_page->drawingArea()->setSize(IntSize(size), IntSize(0, 0), IntSize(_data->_resizeScrollOffset));
2705     _data->_resizeScrollOffset = NSZeroSize;
2706 }
2707
2708 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
2709 - (void)quickLookWithEvent:(NSEvent *)event
2710 {
2711     NSPoint locationInViewCoordinates = [self convertPoint:[event locationInWindow] fromView:nil];
2712     _data->_page->performDictionaryLookupAtLocation(FloatPoint(locationInViewCoordinates.x, locationInViewCoordinates.y));
2713 }
2714 #endif
2715
2716 - (std::unique_ptr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy
2717 {
2718     if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"WebKit2UseRemoteLayerTreeDrawingArea"] boolValue])
2719         return std::make_unique<RemoteLayerTreeDrawingAreaProxy>(_data->_page.get());
2720
2721     return std::make_unique<TiledCoreAnimationDrawingAreaProxy>(_data->_page.get());
2722 }
2723
2724 - (BOOL)_isFocused
2725 {
2726     if (_data->_inBecomeFirstResponder)
2727         return YES;
2728     if (_data->_inResignFirstResponder)
2729         return NO;
2730     return [[self window] firstResponder] == self;
2731 }
2732
2733 - (WebKit::ColorSpaceData)_colorSpace
2734 {
2735     if (!_data->_colorSpace) {
2736         if ([self window])
2737             _data->_colorSpace = [[self window] colorSpace];
2738         else
2739             _data->_colorSpace = [[NSScreen mainScreen] colorSpace];
2740     }
2741         
2742     ColorSpaceData colorSpaceData;
2743     colorSpaceData.cgColorSpace = [_data->_colorSpace CGColorSpace];
2744
2745     return colorSpaceData;    
2746 }
2747
2748 - (void)_processDidExit
2749 {
2750     if (_data->_layerHostingView)
2751         [self _setAcceleratedCompositingModeRootLayer:nil];
2752
2753     [self _updateRemoteAccessibilityRegistration:NO];
2754
2755     _data->_gestureController = nullptr;
2756 }
2757
2758 - (void)_pageClosed
2759 {
2760     [self _updateRemoteAccessibilityRegistration:NO];
2761 }
2762
2763 - (void)_didRelaunchProcess
2764 {
2765     [self _accessibilityRegisterUIProcessTokens];
2766 }
2767
2768 - (void)_preferencesDidChange
2769 {
2770     BOOL needsViewFrameInWindowCoordinates = _data->_page->preferences().pluginsEnabled();
2771
2772     if (!!needsViewFrameInWindowCoordinates == !!_data->_needsViewFrameInWindowCoordinates)
2773         return;
2774
2775     _data->_needsViewFrameInWindowCoordinates = needsViewFrameInWindowCoordinates;
2776     if ([self window])
2777         [self _updateWindowAndViewFrames];
2778 }
2779
2780 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
2781 {
2782     ValidationVector items = _data->_validationMap.take(commandName);
2783     size_t size = items.size();
2784     for (size_t i = 0; i < size; ++i) {
2785         ValidationItem item = items[i].get();
2786         [menuItem(item) setState:newState];
2787         [menuItem(item) setEnabled:isEnabled];
2788         [toolbarItem(item) setEnabled:isEnabled];
2789         // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
2790     }
2791 }
2792
2793 - (BOOL)_tryPostProcessPluginComplexTextInputKeyDown:(NSEvent *)event
2794 {
2795     if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
2796         return NO;
2797
2798     // In the legacy text input model, the event has already been sent to the input method.
2799     if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
2800         return NO;
2801
2802     return [self _handlePluginComplexTextInputKeyDown:event];
2803 }
2804
2805 - (void)_doneWithKeyEvent:(NSEvent *)event eventWasHandled:(BOOL)eventWasHandled
2806 {
2807     if ([event type] != NSKeyDown)
2808         return;
2809
2810     if ([self _tryPostProcessPluginComplexTextInputKeyDown:event])
2811         return;
2812     
2813     if (eventWasHandled) {
2814         [NSCursor setHiddenUntilMouseMoves:YES];
2815         return;
2816     }
2817
2818     // resending the event may destroy this WKView
2819     RetainPtr<WKView> protector(self);
2820
2821     ASSERT(!_data->_keyDownEventBeingResent);
2822     _data->_keyDownEventBeingResent = event;
2823     [NSApp _setCurrentEvent:event];
2824     [NSApp sendEvent:event];
2825
2826     _data->_keyDownEventBeingResent = nullptr;
2827 }
2828
2829 - (NSRect)_convertToDeviceSpace:(NSRect)rect
2830 {
2831     return toDeviceSpace(rect, [self window]);
2832 }
2833
2834 - (NSRect)_convertToUserSpace:(NSRect)rect
2835 {
2836     return toUserSpace(rect, [self window]);
2837 }
2838
2839 // Any non-zero value will do, but using something recognizable might help us debug some day.
2840 #define TRACKING_RECT_TAG 0xBADFACE
2841
2842 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2843 {
2844     ASSERT(_data->_trackingRectOwner == nil);
2845     _data->_trackingRectOwner = owner;
2846     _data->_trackingRectUserData = data;
2847     return TRACKING_RECT_TAG;
2848 }
2849
2850 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2851 {
2852     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
2853     ASSERT(_data->_trackingRectOwner == nil);
2854     _data->_trackingRectOwner = owner;
2855     _data->_trackingRectUserData = data;
2856     return TRACKING_RECT_TAG;
2857 }
2858
2859 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
2860 {
2861     ASSERT(count == 1);
2862     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
2863     ASSERT(_data->_trackingRectOwner == nil);
2864     _data->_trackingRectOwner = owner;
2865     _data->_trackingRectUserData = userDataList[0];
2866     trackingNums[0] = TRACKING_RECT_TAG;
2867 }
2868
2869 - (void)removeTrackingRect:(NSTrackingRectTag)tag
2870 {
2871     if (!_data)
2872         return;
2873
2874     if (tag == 0)
2875         return;
2876     
2877     if (tag == TRACKING_RECT_TAG) {
2878         _data->_trackingRectOwner = nil;
2879         return;
2880     }
2881     
2882     if (tag == _data->_lastToolTipTag) {
2883         [super removeTrackingRect:tag];
2884         _data->_lastToolTipTag = 0;
2885         return;
2886     }
2887
2888     // If any other tracking rect is being removed, we don't know how it was created
2889     // and it's possible there's a leak involved (see 3500217)
2890     ASSERT_NOT_REACHED();
2891 }
2892
2893 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
2894 {
2895     int i;
2896     for (i = 0; i < count; ++i) {
2897         int tag = tags[i];
2898         if (tag == 0)
2899             continue;
2900         ASSERT(tag == TRACKING_RECT_TAG);
2901         if (_data != nil) {
2902             _data->_trackingRectOwner = nil;
2903         }
2904     }
2905 }
2906
2907 - (void)_sendToolTipMouseExited
2908 {
2909     // Nothing matters except window, trackingNumber, and userData.
2910     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
2911         location:NSMakePoint(0, 0)
2912         modifierFlags:0
2913         timestamp:0
2914         windowNumber:[[self window] windowNumber]
2915         context:NULL
2916         eventNumber:0
2917         trackingNumber:TRACKING_RECT_TAG
2918         userData:_data->_trackingRectUserData];
2919     [_data->_trackingRectOwner mouseExited:fakeEvent];
2920 }
2921
2922 - (void)_sendToolTipMouseEntered
2923 {
2924     // Nothing matters except window, trackingNumber, and userData.
2925     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
2926         location:NSMakePoint(0, 0)
2927         modifierFlags:0
2928         timestamp:0
2929         windowNumber:[[self window] windowNumber]
2930         context:NULL
2931         eventNumber:0
2932         trackingNumber:TRACKING_RECT_TAG
2933         userData:_data->_trackingRectUserData];
2934     [_data->_trackingRectOwner mouseEntered:fakeEvent];
2935 }
2936
2937 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
2938 {
2939     return nsStringFromWebCoreString(_data->_page->toolTip());
2940 }
2941
2942 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
2943 {
2944     if (oldToolTip)
2945         [self _sendToolTipMouseExited];
2946
2947     if (newToolTip && [newToolTip length] > 0) {
2948         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
2949         [self removeAllToolTips];
2950         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
2951         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
2952         [self _sendToolTipMouseEntered];
2953     }
2954 }
2955
2956 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut animate:(BOOL)animate
2957 {
2958     if (!findIndicator) {
2959         _data->_findIndicatorWindow = nullptr;
2960         return;
2961     }
2962
2963     if (!_data->_findIndicatorWindow)
2964         _data->_findIndicatorWindow = std::make_unique<FindIndicatorWindow>(self);
2965
2966     _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut, animate);
2967 }
2968
2969 - (CALayer *)_rootLayer
2970 {
2971     return [_data->_layerHostingView layer];
2972 }
2973
2974 - (void)_setAcceleratedCompositingModeRootLayer:(CALayer *)rootLayer
2975 {
2976     [rootLayer web_disableAllActions];
2977
2978     _data->_rootLayer = rootLayer;
2979
2980 #if WK_API_ENABLED
2981     if (_data->_thumbnailView) {
2982         [self _updateThumbnailViewLayer];
2983         return;
2984     }
2985 #endif
2986
2987     [CATransaction begin];
2988     [CATransaction setDisableActions:YES];
2989
2990     if (rootLayer) {
2991         if (!_data->_layerHostingView) {
2992             // Create an NSView that will host our layer tree.
2993             _data->_layerHostingView = adoptNS([[WKFlippedView alloc] initWithFrame:[self bounds]]);
2994             [_data->_layerHostingView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
2995
2996
2997             [self addSubview:_data->_layerHostingView.get() positioned:NSWindowBelow relativeTo:nil];
2998
2999             // Create a root layer that will back the NSView.
3000             RetainPtr<CALayer> layer = adoptNS([[CALayer alloc] init]);
3001             [layer setDelegate:[WebActionDisablingCALayerDelegate shared]];
3002 #ifndef NDEBUG
3003             [layer setName:@"Hosting root layer"];
3004 #endif
3005
3006             [_data->_layerHostingView setLayer:layer.get()];
3007             [_data->_layerHostingView setWantsLayer:YES];
3008         }
3009
3010         [_data->_layerHostingView layer].sublayers = [NSArray arrayWithObject:rootLayer];
3011     } else {
3012         if (_data->_layerHostingView) {
3013             [_data->_layerHostingView removeFromSuperview];
3014             [_data->_layerHostingView setLayer:nil];
3015             [_data->_layerHostingView setWantsLayer:NO];
3016
3017             _data->_layerHostingView = nullptr;
3018         }
3019     }
3020
3021     [CATransaction commit];
3022 }
3023
3024 - (CALayer *)_acceleratedCompositingModeRootLayer
3025 {
3026     return _data->_rootLayer.get();
3027 }
3028
3029 static RefPtr<IOSurface> createIOSurfaceFromImage(CGImageRef image)
3030 {
3031     size_t width = CGImageGetWidth(image);
3032     size_t height = CGImageGetHeight(image);
3033
3034     RefPtr<IOSurface> surface = IOSurface::create(IntSize(width, height), ColorSpaceDeviceRGB);
3035     RetainPtr<CGContextRef> surfaceContext = surface->ensurePlatformContext();
3036     CGContextDrawImage(surfaceContext.get(), CGRectMake(0, 0, width, height), image);
3037     CGContextFlush(surfaceContext.get());
3038
3039     return surface;
3040 }
3041
3042 - (ViewSnapshot)_takeViewSnapshot
3043 {
3044     NSWindow *window = self.window;
3045
3046     ViewSnapshot snapshot;
3047
3048     if (![window windowNumber])
3049         return snapshot;
3050
3051     // FIXME: This should use CGWindowListCreateImage once <rdar://problem/15709646> is resolved.
3052     CGSWindowID windowID = [window windowNumber];
3053     CGImageRef cgWindowImage = nullptr;
3054     CGSCaptureWindowsContentsToRect(CGSMainConnectionID(), &windowID, 1, CGRectNull, &cgWindowImage);
3055     RetainPtr<CGImageRef> windowSnapshotImage = adoptCF(cgWindowImage);
3056
3057     [self _ensureGestureController];
3058
3059     NSRect windowCaptureRect;
3060     FloatRect boundsForCustomSwipeViews = _data->_gestureController->windowRelativeBoundsForCustomSwipeViews();
3061     if (!boundsForCustomSwipeViews.isEmpty())
3062         windowCaptureRect = boundsForCustomSwipeViews;
3063     else {
3064         NSRect unobscuredBounds = self.bounds;
3065         float topContentInset = _data->_page->topContentInset();
3066         unobscuredBounds.origin.y += topContentInset;
3067         unobscuredBounds.size.height -= topContentInset;
3068         windowCaptureRect = [self convertRect:unobscuredBounds toView:nil];
3069     }
3070
3071     NSRect windowCaptureScreenRect = [window convertRectToScreen:windowCaptureRect];
3072     CGRect windowScreenRect;
3073     CGSGetScreenRectForWindow(CGSMainConnectionID(), (CGSWindowID)[window windowNumber], &windowScreenRect);
3074
3075     NSRect croppedImageRect = windowCaptureRect;
3076     croppedImageRect.origin.y = windowScreenRect.size.height - windowCaptureScreenRect.size.height - NSMinY(windowCaptureRect);
3077
3078     auto croppedSnapshotImage = adoptCF(CGImageCreateWithImageInRect(windowSnapshotImage.get(), NSRectToCGRect([window convertRectToBacking:croppedImageRect])));
3079
3080     snapshot.surface = createIOSurfaceFromImage(croppedSnapshotImage.get());
3081     snapshot.imageSizeInBytes = snapshot.surface->totalBytes();
3082     return snapshot;
3083 }
3084
3085 - (void)_wheelEventWasNotHandledByWebCore:(NSEvent *)event
3086 {
3087     if (_data->_gestureController)
3088         _data->_gestureController->wheelEventWasNotHandledByWebCore(event);
3089 }
3090
3091 - (void)_setAccessibilityWebProcessToken:(NSData *)data
3092 {
3093     _data->_remoteAccessibilityChild = WKAXRemoteElementForToken(data);
3094     [self _updateRemoteAccessibilityRegistration:YES];
3095 }
3096
3097 - (void)_pluginFocusOrWindowFocusChanged:(BOOL)pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
3098 {
3099     BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
3100
3101     if (pluginHasFocusAndWindowHasFocus) {
3102         // Check if we're already allowing text input for this plug-in.
3103         if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
3104             return;
3105
3106         _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
3107
3108     } else {
3109         // Check if we got a request to unfocus a plug-in that isn't focused.
3110         if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
3111             return;
3112
3113         _data->_pluginComplexTextInputIdentifier = 0;
3114     }
3115
3116     if (inputSourceChanged) {
3117         // The input source changed, go ahead and discard any entered text.
3118         [[WKTextInputWindowController sharedTextInputWindowController] unmarkText];
3119     }
3120
3121     // This will force the current input context to be updated to its correct value.
3122     [NSApp updateWindows];
3123 }
3124
3125 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
3126 {
3127     if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier) {
3128         // We're asked to update the state for a plug-in that doesn't have focus.
3129         return;
3130     }
3131
3132     [self _setPluginComplexTextInputState:pluginComplexTextInputState];
3133 }
3134
3135 - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag
3136 {
3137     IntSize size([image size]);
3138     size.scale(1.0 / _data->_page->deviceScaleFactor());
3139     [image setSize:size];
3140     
3141     // The call below could release this WKView.
3142     RetainPtr<WKView> protector(self);
3143     
3144 #pragma clang diagnostic push
3145 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3146     [self dragImage:image
3147                  at:clientPoint
3148              offset:NSZeroSize
3149               event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent
3150          pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
3151              source:self
3152           slideBack:YES];
3153 #pragma clang diagnostic pop
3154 }
3155
3156 static bool matchesExtensionOrEquivalent(NSString *filename, NSString *extension)
3157 {
3158     NSString *extensionAsSuffix = [@"." stringByAppendingString:extension];
3159     return hasCaseInsensitiveSuffix(filename, extensionAsSuffix) || (stringIsCaseInsensitiveEqualToString(extension, @"jpeg")
3160                                                                      && hasCaseInsensitiveSuffix(filename, @".jpg"));
3161 }
3162
3163 - (void)_setPromisedData:(WebCore::Image *)image withFileName:(NSString *)filename withExtension:(NSString *)extension withTitle:(NSString *)title withURL:(NSString *)url withVisibleURL:(NSString *)visibleUrl withArchive:(WebCore::SharedBuffer*) archiveBuffer forPasteboard:(NSString *)pasteboardName
3164
3165 {
3166     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName];
3167     RetainPtr<NSMutableArray> types = adoptNS([[NSMutableArray alloc] initWithObjects:NSFilesPromisePboardType, nil]);
3168     
3169     [types addObjectsFromArray:archiveBuffer ? PasteboardTypes::forImagesWithArchive() : PasteboardTypes::forImages()];
3170     [pasteboard declareTypes:types.get() owner:self];
3171     if (!matchesExtensionOrEquivalent(filename, extension))
3172         filename = [[filename stringByAppendingString:@"."] stringByAppendingString:extension];
3173
3174     [pasteboard setString:visibleUrl forType:NSStringPboardType];
3175     [pasteboard setString:visibleUrl forType:PasteboardTypes::WebURLPboardType];
3176     [pasteboard setString:title forType:PasteboardTypes::WebURLNamePboardType];
3177     [pasteboard setPropertyList:[NSArray arrayWithObjects:[NSArray arrayWithObject:visibleUrl], [NSArray arrayWithObject:title], nil] forType:PasteboardTypes::WebURLsWithTitlesPboardType];
3178     [pasteboard setPropertyList:[NSArray arrayWithObject:extension] forType:NSFilesPromisePboardType];
3179
3180     if (archiveBuffer)
3181         [pasteboard setData:archiveBuffer->createNSData().get() forType:PasteboardTypes::WebArchivePboardType];
3182
3183     _data->_promisedImage = image;
3184     _data->_promisedFilename = filename;
3185     _data->_promisedURL = url;
3186 }
3187
3188 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
3189 {
3190     _data->_promisedImage = 0;
3191     _data->_promisedFilename = "";
3192     _data->_promisedURL = "";
3193 }
3194
3195 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
3196 {
3197     // FIXME: need to support NSRTFDPboardType
3198
3199     if ([type isEqual:NSTIFFPboardType] && _data->_promisedImage) {
3200         [pasteboard setData:(NSData *)_data->_promisedImage->getTIFFRepresentation() forType:NSTIFFPboardType];
3201         _data->_promisedImage = 0;
3202     }
3203 }
3204
3205 static BOOL fileExists(NSString *path)
3206 {
3207     struct stat statBuffer;
3208     return !lstat([path fileSystemRepresentation], &statBuffer);
3209 }
3210
3211 static NSString *pathWithUniqueFilenameForPath(NSString *path)
3212 {
3213     // "Fix" the filename of the path.
3214     NSString *filename = filenameByFixingIllegalCharacters([path lastPathComponent]);
3215     path = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:filename];
3216     
3217     if (fileExists(path)) {
3218         // Don't overwrite existing file by appending "-n", "-n.ext" or "-n.ext.ext" to the filename.
3219         NSString *extensions = nil;
3220         NSString *pathWithoutExtensions;
3221         NSString *lastPathComponent = [path lastPathComponent];
3222         NSRange periodRange = [lastPathComponent rangeOfString:@"."];
3223         
3224         if (periodRange.location == NSNotFound) {
3225             pathWithoutExtensions = path;
3226         } else {
3227             extensions = [lastPathComponent substringFromIndex:periodRange.location + 1];
3228             lastPathComponent = [lastPathComponent substringToIndex:periodRange.location];
3229             pathWithoutExtensions = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:lastPathComponent];
3230         }
3231         
3232         for (unsigned i = 1; ; i++) {
3233             NSString *pathWithAppendedNumber = [NSString stringWithFormat:@"%@-%d", pathWithoutExtensions, i];
3234             path = [extensions length] ? [pathWithAppendedNumber stringByAppendingPathExtension:extensions] : pathWithAppendedNumber;
3235             if (!fileExists(path))
3236                 break;
3237         }
3238     }
3239     
3240     return path;
3241 }
3242
3243 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
3244 {
3245     RetainPtr<NSFileWrapper> wrapper;
3246     RetainPtr<NSData> data;
3247     
3248     if (_data->_promisedImage) {
3249         data = _data->_promisedImage->data()->createNSData();
3250         wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:data.get()]);
3251         [wrapper setPreferredFilename:_data->_promisedFilename];
3252     }
3253     
3254     if (!wrapper) {
3255         LOG_ERROR("Failed to create image file.");
3256         return nil;
3257     }
3258     
3259     // FIXME: Report an error if we fail to create a file.
3260     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
3261     path = pathWithUniqueFilenameForPath(path);
3262     if (![wrapper writeToURL:[NSURL fileURLWithPath:path] options:NSFileWrapperWritingWithNameUpdating originalContentsURL:nil error:nullptr])
3263         LOG_ERROR("Failed to create image file via -[NSFileWrapper writeToURL:options:originalContentsURL:error:]");
3264
3265     if (!_data->_promisedURL.isEmpty())
3266         WebCore::setMetadataURL(_data->_promisedURL, "", String(path));
3267     
3268     return [NSArray arrayWithObject:[path lastPathComponent]];
3269 }
3270
3271 - (void)_updateSecureInputState
3272 {
3273     if (![[self window] isKeyWindow] || ![self _isFocused]) {
3274         if (_data->_inSecureInputState) {
3275             DisableSecureEventInput();
3276             _data->_inSecureInputState = NO;
3277         }
3278         return;
3279     }
3280     // WKView has a single input context for all editable areas (except for plug-ins).
3281     NSTextInputContext *context = [super inputContext];
3282     bool isInPasswordField = _data->_page->editorState().isInPasswordField;
3283
3284     if (isInPasswordField) {
3285         if (!_data->_inSecureInputState)
3286             EnableSecureEventInput();
3287         static NSArray *romanInputSources = [[NSArray alloc] initWithObjects:&NSAllRomanInputSourcesLocaleIdentifier count:1];
3288         LOG(TextInput, "-> setAllowedInputSourceLocales:romanInputSources");
3289         [context setAllowedInputSourceLocales:romanInputSources];
3290     } else {
3291         if (_data->_inSecureInputState)
3292             DisableSecureEventInput();
3293         LOG(TextInput, "-> setAllowedInputSourceLocales:nil");
3294         [context setAllowedInputSourceLocales:nil];
3295     }
3296     _data->_inSecureInputState = isInPasswordField;
3297 }
3298
3299 - (void)_resetSecureInputState
3300 {
3301     if (_data->_inSecureInputState) {
3302         DisableSecureEventInput();
3303         _data->_inSecureInputState = NO;
3304     }
3305 }
3306
3307 - (void)_notifyInputContextAboutDiscardedComposition
3308 {
3309     // <rdar://problem/9359055>: -discardMarkedText can only be called for active contexts.
3310     // FIXME: We fail to ever notify the input context if something (e.g. a navigation) happens while the window is not key.
3311     // This is not a problem when the window is key, because we discard marked text on resigning first responder.
3312     if (![[self window] isKeyWindow] || self != [[self window] firstResponder])
3313         return;
3314
3315     LOG(TextInput, "-> discardMarkedText");
3316     [[super inputContext] discardMarkedText]; // Inform the input method that we won't have an inline input area despite having been asked to.
3317 }
3318
3319 #if ENABLE(FULLSCREEN_API)
3320 - (BOOL)_hasFullScreenWindowController
3321 {
3322     return (bool)_data->_fullScreenWindowController;
3323 }
3324
3325 - (WKFullScreenWindowController *)_fullScreenWindowController
3326 {
3327     if (!_data->_fullScreenWindowController)
3328         _data->_fullScreenWindowController = adoptNS([[WKFullScreenWindowController alloc] initWithWindow:[self createFullScreenWindow] webView:self]);
3329
3330     return _data->_fullScreenWindowController.get();
3331 }
3332
3333 - (void)_closeFullScreenWindowController
3334 {
3335     if (!_data->_fullScreenWindowController)
3336         return;
3337
3338     [_data->_fullScreenWindowController close];
3339     _data->_fullScreenWindowController = nullptr;
3340 }
3341 #endif
3342
3343 - (bool)_executeSavedCommandBySelector:(SEL)selector
3344 {
3345     LOG(TextInput, "Executing previously saved command %s", sel_getName(selector));
3346     // The sink does two things: 1) Tells us if the responder went unhandled, and
3347     // 2) prevents any NSBeep; we don't ever want to beep here.
3348     RetainPtr<WKResponderChainSink> sink = adoptNS([[WKResponderChainSink alloc] initWithResponderChain:self]);
3349     [super doCommandBySelector:selector];
3350     [sink detach];
3351     return ![sink didReceiveUnhandledCommand];
3352 }
3353
3354 - (void)_setIntrinsicContentSize:(NSSize)intrinsicContentSize
3355 {
3356     // If the intrinsic content size is less than the minimum layout width, the content flowed to fit,
3357     // so we can report that that dimension is flexible. If not, we need to report our intrinsic width
3358     // so that autolayout will know to provide space for us.
3359
3360     NSSize intrinsicContentSizeAcknowledgingFlexibleWidth = intrinsicContentSize;
3361     if (intrinsicContentSize.width < _data->_page->minimumLayoutSize().width())
3362         intrinsicContentSizeAcknowledgingFlexibleWidth.width = NSViewNoInstrinsicMetric;
3363
3364     _data->_intrinsicContentSize = intrinsicContentSizeAcknowledgingFlexibleWidth;
3365     [self invalidateIntrinsicContentSize];
3366 }
3367
3368 - (void)_cacheWindowBottomCornerRect
3369 {
3370     // FIXME: We should remove this code when <rdar://problem/9362085> is resolved.
3371     NSWindow *window = [self window];
3372     if (!window)
3373         return;
3374
3375     _data->_windowBottomCornerIntersectionRect = [window _intersectBottomCornersWithRect:[self convertRect:[self visibleRect] toView:nil]];
3376     if (!NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect))
3377         [self setNeedsDisplayInRect:[self convertRect:_data->_windowBottomCornerIntersectionRect fromView:nil]];
3378 }
3379
3380 - (NSInteger)spellCheckerDocumentTag
3381 {
3382     if (!_data->_hasSpellCheckerDocumentTag) {
3383         _data->_spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
3384         _data->_hasSpellCheckerDocumentTag = YES;
3385     }
3386     return _data->_spellCheckerDocumentTag;
3387 }
3388
3389 - (void)handleAcceptedAlternativeText:(NSString*)text
3390 {
3391     _data->_page->handleAlternativeTextUIResult(text);
3392 }
3393
3394 - (void)_setSuppressVisibilityUpdates:(BOOL)suppressVisibilityUpdates
3395 {
3396     _data->_page->setSuppressVisibilityUpdates(suppressVisibilityUpdates);
3397 }
3398
3399 - (BOOL)_suppressVisibilityUpdates
3400 {
3401     return _data->_page->suppressVisibilityUpdates();
3402 }
3403
3404 - (instancetype)initWithFrame:(NSRect)frame context:(WebContext&)context configuration:(WebPageConfiguration)webPageConfiguration webView:(WKWebView *)webView
3405 {
3406     self = [super initWithFrame:frame];
3407     if (!self)
3408         return nil;
3409
3410     [NSApp registerServicesMenuSendTypes:PasteboardTypes::forSelection() returnTypes:PasteboardTypes::forEditing()];
3411
3412     InitializeWebKit2();
3413
3414     // Legacy style scrollbars have design details that rely on tracking the mouse all the time.
3415     NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect;
3416     if (WKRecommendedScrollerStyle() == NSScrollerStyleLegacy)
3417         options |= NSTrackingActiveAlways;
3418     else
3419         options |= NSTrackingActiveInKeyWindow;
3420
3421     NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame
3422                                                                 options:options
3423                                                                   owner:self
3424                                                                userInfo:nil];
3425     [self addTrackingArea:trackingArea];
3426     [trackingArea release];
3427
3428     _data = [[WKViewData alloc] init];
3429     _data->_pageClient = std::make_unique<PageClientImpl>(self, webView);
3430     _data->_page = context.createWebPage(*_data->_pageClient, std::move(webPageConfiguration));
3431     _data->_page->setAddsVisitedLinks(context.historyClient().addsVisitedLinks());
3432
3433     _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]);
3434     _data->_page->initializeWebPage();
3435
3436     _data->_mouseDownEvent = nil;
3437     _data->_ignoringMouseDraggedEvents = NO;
3438     _data->_clipsToVisibleRect = NO;
3439     _data->_useContentPreparationRectForVisibleRect = NO;
3440     _data->_windowOcclusionDetectionEnabled = YES;
3441
3442     _data->_intrinsicContentSize = NSMakeSize(NSViewNoInstrinsicMetric, NSViewNoInstrinsicMetric);
3443
3444     _data->_needsViewFrameInWindowCoordinates = _data->_page->preferences().pluginsEnabled();
3445     
3446     [self _registerDraggedTypes];
3447
3448     self.wantsLayer = YES;
3449
3450     // Explicitly set the layer contents placement so AppKit will make sure that our layer has masksToBounds set to YES.
3451     self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft;
3452
3453     WebContext::statistics().wkViewCount++;
3454
3455     NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
3456     [workspaceNotificationCenter addObserver:self selector:@selector(_activeSpaceDidChange:) name:NSWorkspaceActiveSpaceDidChangeNotification object:nil];
3457
3458     return self;
3459 }
3460
3461 - (void)_registerDraggedTypes
3462 {
3463     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:PasteboardTypes::forEditing()];
3464     [types addObjectsFromArray:PasteboardTypes::forURL()];
3465     [self registerForDraggedTypes:[types allObjects]];
3466     [types release];
3467 }
3468
3469 #if WK_API_ENABLED
3470 - (void)_setThumbnailView:(_WKThumbnailView *)thumbnailView
3471 {
3472     ASSERT(!_data->_thumbnailView || !thumbnailView);
3473
3474     _data->_thumbnailView = thumbnailView;
3475
3476     if (thumbnailView)
3477         [self _updateThumbnailViewLayer];
3478     else
3479         [self _setAcceleratedCompositingModeRootLayer:_data->_rootLayer.get()];
3480
3481     _data->_page->viewStateDidChange(ViewState::WindowIsActive | ViewState::IsInWindow | ViewState::IsVisible);
3482 }
3483
3484 - (_WKThumbnailView *)_thumbnailView
3485 {
3486     return _data->_thumbnailView;
3487 }
3488
3489 - (void)_updateThumbnailViewLayer
3490 {
3491     _WKThumbnailView *thumbnailView = _data->_thumbnailView;
3492     ASSERT(thumbnailView);
3493
3494     if (!thumbnailView.usesSnapshot || thumbnailView._waitingForSnapshot)
3495         [self _reparentLayerTreeInThumbnailView];
3496 }
3497
3498 - (void)_reparentLayerTreeInThumbnailView
3499 {
3500     _data->_thumbnailView._thumbnailLayer = _data->_rootLayer.get();
3501 }
3502 #endif // WK_API_ENABLED
3503
3504 @end
3505
3506 @implementation WKView (Private)
3507
3508 - (void)saveBackForwardSnapshotForCurrentItem
3509 {
3510     _data->_page->recordNavigationSnapshot();
3511 }
3512
3513 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef
3514 {
3515     return [self initWithFrame:frame contextRef:contextRef pageGroupRef:pageGroupRef relatedToPage:nil];
3516 }
3517
3518 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef relatedToPage:(WKPageRef)relatedPage
3519 {
3520     WebPageConfiguration webPageConfiguration;
3521     webPageConfiguration.pageGroup = toImpl(pageGroupRef);
3522     webPageConfiguration.relatedPage = toImpl(relatedPage);
3523
3524     return [self initWithFrame:frame context:*toImpl(contextRef) configuration:webPageConfiguration webView:nil];
3525 }
3526
3527 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
3528 - (BOOL)wantsUpdateLayer
3529 {
3530     return YES;
3531 }
3532
3533 - (void)updateLayer
3534 {
3535     if ([self drawsBackground] && ![self drawsTransparentBackground])
3536         self.layer.backgroundColor = CGColorGetConstantColor(kCGColorWhite);
3537     else
3538         self.layer.backgroundColor = CGColorGetConstantColor(kCGColorClear);
3539
3540     // If asynchronous geometry updates have been sent by forceAsyncDrawingAreaSizeUpdate,
3541     // then subsequent calls to setFrameSize should not result in us waiting for the did
3542     // udpate response if setFrameSize is called.
3543     if ([self frameSizeUpdatesDisabled])
3544         return;
3545
3546     if (DrawingAreaProxy* drawingArea = _data->_page->drawingArea())
3547         drawingArea->waitForPossibleGeometryUpdate();
3548 }
3549 #endif
3550
3551 - (WKPageRef)pageRef
3552 {
3553     return toAPI(_data->_page.get());
3554 }
3555
3556 - (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef
3557 {
3558     // PDF documents are already paginated, so we can't change them to add headers and footers.
3559     return !toImpl(frameRef)->isDisplayingPDFDocument();
3560 }
3561
3562 - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef
3563 {
3564     LOG(View, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data());
3565
3566     // FIXME: If the frame cannot be printed (e.g. if it contains an encrypted PDF that disallows
3567     // printing), this function should return nil.
3568     RetainPtr<WKPrintingView> printingView = adoptNS([[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef) view:self]);
3569     // NSPrintOperation takes ownership of the view.
3570     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get() printInfo:printInfo];
3571     [printOperation setCanSpawnSeparateThread:YES];
3572     [printOperation setJobTitle:toImpl(frameRef)->title()];
3573     printingView->_printOperation = printOperation;
3574     return printOperation;
3575 }
3576
3577 - (void)setFrame:(NSRect)rect andScrollBy:(NSSize)offset
3578 {
3579     ASSERT(NSEqualSizes(_data->_resizeScrollOffset, NSZeroSize));
3580
3581     _data->_resizeScrollOffset = offset;
3582     [self setFrame:rect];
3583 }
3584
3585 - (void)disableFrameSizeUpdates
3586 {
3587     _data->_frameSizeUpdatesDisabledCount++;
3588 }
3589
3590 - (void)enableFrameSizeUpdates
3591 {
3592     if (!_data->_frameSizeUpdatesDisabledCount)
3593         return;
3594     
3595     if (!(--_data->_frameSizeUpdatesDisabledCount)) {
3596         if (_data->_clipsToVisibleRect)
3597             [self _updateViewExposedRect];
3598         [self _setDrawingAreaSize:[self frame].size];
3599     }
3600 }
3601
3602 - (BOOL)frameSizeUpdatesDisabled
3603 {
3604     return _data->_frameSizeUpdatesDisabledCount > 0;
3605 }
3606
3607 + (void)hideWordDefinitionWindow
3608 {
3609     WKHideWordDefinitionWindow();
3610 }
3611
3612 - (CGFloat)minimumLayoutWidth
3613 {
3614     static BOOL loggedDeprecationWarning = NO;
3615
3616     if (!loggedDeprecationWarning) {
3617         NSLog(@"Please use minimumSizeForAutoLayout instead of minimumLayoutWidth.");
3618         loggedDeprecationWarning = YES;
3619     }
3620
3621     return self.minimumSizeForAutoLayout.width;
3622 }
3623
3624 - (void)setMinimumLayoutWidth:(CGFloat)minimumLayoutWidth
3625 {
3626     static BOOL loggedDeprecationWarning = NO;
3627
3628     if (!loggedDeprecationWarning) {
3629         NSLog(@"Please use setMinimumSizeForAutoLayout: instead of setMinimumLayoutWidth:.");
3630         loggedDeprecationWarning = YES;
3631     }
3632
3633     [self setMinimumWidthForAutoLayout:minimumLayoutWidth];
3634 }
3635
3636 - (CGFloat)minimumWidthForAutoLayout
3637 {
3638     return self.minimumSizeForAutoLayout.width;
3639 }
3640
3641 - (void)setMinimumWidthForAutoLayout:(CGFloat)minimumLayoutWidth
3642 {
3643     self.minimumSizeForAutoLayout = NSMakeSize(minimumLayoutWidth, self.minimumSizeForAutoLayout.height);
3644 }
3645
3646 - (NSSize)minimumSizeForAutoLayout
3647 {
3648     return _data->_page->minimumLayoutSize();
3649 }
3650
3651 - (void)setMinimumSizeForAutoLayout:(NSSize)minimumSizeForAutoLayout
3652 {
3653     BOOL expandsToFit = minimumSizeForAutoLayout.width > 0;
3654
3655     _data->_page->setMinimumLayoutSize(IntSize(minimumSizeForAutoLayout.width, minimumSizeForAutoLayout.height));
3656     _data->_page->setMainFrameIsScrollable(!expandsToFit);
3657
3658     [self setShouldClipToVisibleRect:expandsToFit];
3659 }
3660
3661 - (BOOL)shouldExpandToViewHeightForAutoLayout
3662 {
3663     return _data->_page->autoSizingShouldExpandToViewHeight();
3664 }
3665
3666 - (void)setShouldExpandToViewHeightForAutoLayout:(BOOL)shouldExpand
3667 {
3668     return _data->_page->setAutoSizingShouldExpandToViewHeight(shouldExpand);
3669 }
3670
3671 - (BOOL)shouldClipToVisibleRect
3672 {
3673     return _data->_clipsToVisibleRect;
3674 }
3675
3676 - (void)setShouldClipToVisibleRect:(BOOL)clipsToVisibleRect
3677 {
3678     _data->_clipsToVisibleRect = clipsToVisibleRect;
3679     [self _updateViewExposedRect];
3680 }
3681
3682 - (NSColor *)underlayColor
3683 {
3684     Color webColor = _data->_page->underlayColor();
3685     if (!webColor.isValid())
3686         return nil;
3687
3688     return nsColor(webColor);
3689 }
3690
3691 - (void)setUnderlayColor:(NSColor *)underlayColor
3692 {
3693     _data->_page->setUnderlayColor(colorFromNSColor(underlayColor));
3694 }
3695
3696 - (NSView *)fullScreenPlaceholderView
3697 {
3698 #if ENABLE(FULLSCREEN_API)
3699     if (_data->_fullScreenWindowController && [_data->_fullScreenWindowController isFullScreen])
3700         return [_data->_fullScreenWindowController webViewPlaceholder];
3701 #endif
3702     return nil;
3703 }
3704
3705 - (NSWindow *)createFullScreenWindow
3706 {
3707 #if ENABLE(FULLSCREEN_API)
3708 #if __MAC_OS_X_VERSION_MIN_REQUIRED <= 1080
3709     NSRect contentRect = NSZeroRect;
3710 #else
3711     NSRect contentRect = [[NSScreen mainScreen] frame];
3712 #endif
3713     return [[[WebCoreFullScreenWindow alloc] initWithContentRect:contentRect styleMask:(NSBorderlessWindowMask | NSResizableWindowMask) backing:NSBackingStoreBuffered defer:NO] autorelease];
3714 #else
3715     return nil;
3716 #endif
3717 }
3718
3719 - (void)beginDeferringViewInWindowChanges
3720 {
3721     if (_data->_shouldDeferViewInWindowChanges) {
3722         NSLog(@"beginDeferringViewInWindowChanges was called while already deferring view-in-window changes!");
3723         return;
3724     }
3725
3726     _data->_shouldDeferViewInWindowChanges = YES;
3727 }
3728
3729 - (void)endDeferringViewInWindowChanges
3730 {
3731     if (!_data->_shouldDeferViewInWindowChanges) {
3732         NSLog(@"endDeferringViewInWindowChanges was called without beginDeferringViewInWindowChanges!");
3733         return;
3734     }
3735
3736     _data->_shouldDeferViewInWindowChanges = NO;
3737
3738     if (_data->_viewInWindowChangeWasDeferred) {
3739         _data->_page->viewStateDidChange(ViewState::IsInWindow);
3740         _data->_viewInWindowChangeWasDeferred = NO;
3741     }
3742 }
3743
3744 - (void)endDeferringViewInWindowChangesSync
3745 {
3746     if (!_data->_shouldDeferViewInWindowChanges) {
3747         NSLog(@"endDeferringViewInWindowChangesSync was called without beginDeferringViewInWindowChanges!");
3748         return;
3749     }
3750
3751     PageClient* pageClient = _data->_pageClient.get();
3752     bool hasPendingViewInWindowChange = _data->_viewInWindowChangeWasDeferred && _data->_page->isInWindow() != pageClient->isViewInWindow();
3753
3754     _data->_shouldDeferViewInWindowChanges = NO;
3755
3756     if (_data->_viewInWindowChangeWasDeferred) {
3757         _data->_page->viewStateDidChange(ViewState::IsInWindow, hasPendingViewInWindowChange ? WebPageProxy::WantsReplyOrNot::DoesWantReply : WebPageProxy::WantsReplyOrNot::DoesNotWantReply);
3758         _data->_viewInWindowChangeWasDeferred = NO;
3759     }
3760
3761     if (hasPendingViewInWindowChange)
3762         _data->_page->waitForDidUpdateViewState();
3763 }
3764
3765 - (BOOL)isDeferringViewInWindowChanges
3766 {
3767     return _data->_shouldDeferViewInWindowChanges;
3768 }
3769
3770 - (BOOL)windowOcclusionDetectionEnabled
3771 {
3772     return _data->_windowOcclusionDetectionEnabled;
3773 }
3774
3775 - (void)setWindowOcclusionDetectionEnabled:(BOOL)flag
3776 {
3777     _data->_windowOcclusionDetectionEnabled = flag;
3778 }
3779
3780 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
3781 {
3782     _data->_allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
3783     _data->_page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
3784     _data->_page->setShouldUseImplicitRubberBandControl(allowsBackForwardNavigationGestures);
3785 }
3786
3787 - (BOOL)allowsBackForwardNavigationGestures
3788 {
3789     return _data->_allowsBackForwardNavigationGestures;
3790 }
3791
3792 - (void)_setTopContentInset:(CGFloat)contentInset
3793 {
3794     _data->_page->setTopContentInset(contentInset);
3795 }
3796
3797 - (CGFloat)_topContentInset
3798 {
3799     return _data->_page->topContentInset();
3800 }
3801
3802 - (NSColor *)_pageExtendedBackgroundColor
3803 {
3804     WebCore::Color color = _data->_page->pageExtendedBackgroundColor();
3805     if (!color.isValid())
3806         return nil;
3807
3808     return nsColor(color);
3809 }
3810
3811 // This method forces a drawing area geometry update, even if frame size updates are disabled.
3812 // The updated is performed asynchronously; we don't wait for the geometry update before returning.
3813 // The area drawn need not match the current frame size - if it differs it will be anchored to the
3814 // frame according to the current contentAnchor.
3815 - (void)forceAsyncDrawingAreaSizeUpdate:(NSSize)size
3816 {
3817     if (_data->_clipsToVisibleRect)
3818         [self _updateViewExposedRect];
3819     [self _setDrawingAreaSize:size];
3820
3821     // If a geometry update is pending the new update won't be sent. Poll without waiting for any
3822     // pending did-update message now, such that the new update can be sent. We do so after setting
3823     // the drawing area size such that the latest update is sent.
3824     if (DrawingAreaProxy* drawingArea = _data->_page->drawingArea())
3825         drawingArea->waitForPossibleGeometryUpdate(std::chrono::milliseconds::zero());
3826 }
3827
3828 - (void)waitForAsyncDrawingAreaSizeUpdate
3829 {
3830     if (DrawingAreaProxy* drawingArea = _data->_page->drawingArea()) {
3831         // If a geometry update is still pending then the action of receiving the
3832         // first geometry update may result in another update being scheduled -
3833         // we should wait for this to complete too.
3834         drawingArea->waitForPossibleGeometryUpdate(DrawingAreaProxy::didUpdateBackingStoreStateTimeout() / 2);
3835         drawingArea->waitForPossibleGeometryUpdate(DrawingAreaProxy::didUpdateBackingStoreStateTimeout() / 2);
3836     }
3837 }
3838
3839 - (BOOL)isUsingUISideCompositing
3840 {
3841     if (DrawingAreaProxy* drawingArea = _data->_page->drawingArea())
3842         return drawingArea->type() == DrawingAreaTypeRemoteLayerTree;
3843
3844     return NO;
3845 }
3846
3847 - (void)setAllowsMagnification:(BOOL)allowsMagnification
3848 {
3849     _data->_allowsMagnification = allowsMagnification;
3850 }
3851
3852 - (BOOL)allowsMagnification
3853 {
3854     return _data->_allowsMagnification;
3855 }
3856
3857 - (void)magnifyWithEvent:(NSEvent *)event
3858 {
3859     if (!_data->_allowsMagnification) {
3860         [super magnifyWithEvent:event];
3861         return;
3862     }
3863
3864     [self _ensureGestureController];
3865
3866     _data->_gestureController->handleMagnificationGesture(event.magnification, [self convertPoint:event.locationInWindow fromView:nil]);
3867 }
3868
3869 - (void)smartMagnifyWithEvent:(NSEvent *)event
3870 {
3871     if (!_data->_allowsMagnification) {
3872         [super smartMagnifyWithEvent:event];
3873         return;
3874     }
3875
3876     [self _ensureGestureController];
3877
3878     _data->_gestureController->handleSmartMagnificationGesture([self convertPoint:event.locationInWindow fromView:nil]);
3879 }
3880
3881 -(void)endGestureWithEvent:(NSEvent *)event
3882 {
3883     if (!_data->_gestureController) {
3884         [super endGestureWithEvent:event];
3885         return;
3886     }
3887
3888     _data->_gestureController->endActiveGesture();
3889 }
3890
3891 - (void)setMagnification:(double)magnification centeredAtPoint:(NSPoint)point
3892 {
3893     _data->_page->scalePageInViewCoordinates(magnification, roundedIntPoint(point));
3894 }
3895
3896 - (void)setMagnification:(double)magnification
3897 {
3898     FloatPoint viewCenter(NSMidX([self bounds]), NSMidY([self bounds]));
3899     _data->_page->scalePageInViewCoordinates(magnification, roundedIntPoint(viewCenter));
3900 }
3901
3902 - (double)magnification
3903 {
3904     if (_data->_gestureController)
3905         return _data->_gestureController->magnification();
3906
3907     return _data->_page->pageScaleFactor();
3908 }
3909
3910 - (void)_setCustomSwipeViews:(NSArray *)customSwipeViews
3911 {
3912     if (!customSwipeViews.count && !_data->_gestureController)
3913         return;
3914
3915     [self _ensureGestureController];
3916
3917     Vector<RetainPtr<NSView>> views;
3918     for (NSView *view in customSwipeViews)
3919         views.append(view);
3920
3921     _data->_gestureController->setCustomSwipeViews(views);
3922 }
3923
3924 - (void)_setCustomSwipeViewsTopContentInset:(float)topContentInset
3925 {
3926     [self _ensureGestureController];
3927     _data->_gestureController->setCustomSwipeViewsTopContentInset(topContentInset);
3928 }
3929
3930 - (BOOL)_tryToSwipeWithEvent:(NSEvent *)event ignoringPinnedState:(BOOL)ignoringPinnedState
3931 {
3932     if (!_data->_allowsBackForwardNavigationGestures)
3933         return NO;
3934
3935     [self _ensureGestureController];
3936
3937     BOOL wasIgnoringPinnedState = _data->_gestureController->shouldIgnorePinnedState();
3938     _data->_gestureController->setShouldIgnorePinnedState(ignoringPinnedState);
3939
3940     BOOL handledEvent = _data->_gestureController->handleScrollWheelEvent(event);
3941
3942     _data->_gestureController->setShouldIgnorePinnedState(wasIgnoringPinnedState);
3943
3944     return handledEvent;
3945 }
3946
3947 @end
3948
3949 @implementation WKResponderChainSink
3950
3951 - (id)initWithResponderChain:(NSResponder *)chain
3952 {
3953     self = [super init];
3954     if (!self)
3955         return nil;
3956     _lastResponderInChain = chain;
3957     while (NSResponder *next = [_lastResponderInChain nextResponder])
3958         _lastResponderInChain = next;
3959     [_lastResponderInChain setNextResponder:self];
3960     return self;
3961 }
3962
3963 - (void)detach
3964 {
3965     // This assumes that the responder chain was either unmodified since
3966     // -initWithResponderChain: was called, or was modified in such a way
3967     // that _lastResponderInChain is still in the chain, and self was not
3968     // moved earlier in the chain than _lastResponderInChain.
3969     NSResponder *responderBeforeSelf = _lastResponderInChain;    
3970     NSResponder *next = [responderBeforeSelf nextResponder];
3971     for (; next && next != self; next = [next nextResponder])
3972         responderBeforeSelf = next;
3973     
3974     // Nothing to be done if we are no longer in the responder chain.
3975     if (next != self)
3976         return;
3977     
3978     [responderBeforeSelf setNextResponder:[self nextResponder]];
3979     _lastResponderInChain = nil;
3980 }
3981
3982 - (bool)didReceiveUnhandledCommand
3983 {
3984     return _didReceiveUnhandledCommand;
3985 }
3986
3987 - (void)noResponderFor:(SEL)selector
3988 {
3989     _didReceiveUnhandledCommand = true;
3990 }
3991
3992 - (void)doCommandBySelector:(SEL)selector
3993 {
3994     _didReceiveUnhandledCommand = true;
3995 }
3996
3997 - (BOOL)tryToPerform:(SEL)action with:(id)object
3998 {
3999     _didReceiveUnhandledCommand = true;
4000     return YES;
4001 }
4002
4003 @end
4004
4005 #endif // PLATFORM(MAC)