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