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