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