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