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