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