Web Inspector: Switching tabs to window with inspector open prohibits typing into...
[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 "ActionMenuHitTestResult.h"
39 #import "AttributedString.h"
40 #import "ColorSpaceData.h"
41 #import "DataReference.h"
42 #import "EditingRange.h"
43 #import "EditorState.h"
44 #import "LayerTreeContext.h"
45 #import "Logging.h"
46 #import "NativeWebKeyboardEvent.h"
47 #import "NativeWebMouseEvent.h"
48 #import "NativeWebWheelEvent.h"
49 #import "PageClientImpl.h"
50 #import "PasteboardTypes.h"
51 #import "RemoteLayerTreeDrawingAreaProxy.h"
52 #import "StringUtilities.h"
53 #import "TextChecker.h"
54 #import "TextCheckerState.h"
55 #import "TiledCoreAnimationDrawingAreaProxy.h"
56 #import "ViewGestureController.h"
57 #import "ViewSnapshotStore.h"
58 #import "WKAPICast.h"
59 #import "WKActionMenuController.h"
60 #import "WKActionMenuItemTypes.h"
61 #import "WKFullScreenWindowController.h"
62 #import "WKImmediateActionController.h"
63 #import "WKPrintingView.h"
64 #import "WKProcessPoolInternal.h"
65 #import "WKStringCF.h"
66 #import "WKTextInputWindowController.h"
67 #import "WKViewInternal.h"
68 #import "WKViewPrivate.h"
69 #import "WebBackForwardList.h"
70 #import "WebEventFactory.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     [self _dismissContentRelativeChildWindows];
1371 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
1372     [_data->_actionMenuController wkView:self willHandleMouseDown:event];
1373 #endif
1374     [self mouseDownInternal:event];
1375 }
1376
1377 - (void)mouseUp:(NSEvent *)event
1378 {
1379     if (_data->_ignoresNonWheelEvents)
1380         return;
1381
1382     [self _setMouseDownEvent:nil];
1383     [self mouseUpInternal:event];
1384 }
1385
1386 - (void)mouseDragged:(NSEvent *)event
1387 {
1388     if (_data->_ignoresNonWheelEvents)
1389         return;
1390
1391     if (_data->_ignoringMouseDraggedEvents)
1392         return;
1393     [self mouseDraggedInternal:event];
1394 }
1395
1396 - (BOOL)acceptsFirstMouse:(NSEvent *)event
1397 {
1398     // There's a chance that responding to this event will run a nested event loop, and
1399     // fetching a new event might release the old one. Retaining and then autoreleasing
1400     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1401     [[event retain] autorelease];
1402     
1403     if (![self hitTest:[event locationInWindow]])
1404         return NO;
1405     
1406     [self _setMouseDownEvent:event];
1407     bool result = _data->_page->acceptsFirstMouse([event eventNumber], WebEventFactory::createWebMouseEvent(event, self));
1408     [self _setMouseDownEvent:nil];
1409     return result;
1410 }
1411
1412 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
1413 {
1414     // If this is the active window or we don't have a range selection, there is no need to perform additional checks
1415     // and we can avoid making a synchronous call to the WebProcess.
1416     if ([[self window] isKeyWindow] || _data->_page->editorState().selectionIsNone || !_data->_page->editorState().selectionIsRange)
1417         return NO;
1418
1419     // There's a chance that responding to this event will run a nested event loop, and
1420     // fetching a new event might release the old one. Retaining and then autoreleasing
1421     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1422     [[event retain] autorelease];
1423     
1424     if (![self hitTest:[event locationInWindow]])
1425         return NO;
1426     
1427     [self _setMouseDownEvent:event];
1428     bool result = _data->_page->shouldDelayWindowOrderingForEvent(WebEventFactory::createWebMouseEvent(event, self));
1429     [self _setMouseDownEvent:nil];
1430     return result;
1431 }
1432
1433 - (void)_disableComplexTextInputIfNecessary
1434 {
1435     if (!_data->_pluginComplexTextInputIdentifier)
1436         return;
1437
1438     if (_data->_pluginComplexTextInputState != PluginComplexTextInputEnabled)
1439         return;
1440
1441     // Check if the text input window has been dismissed.
1442     if (![[WKTextInputWindowController sharedTextInputWindowController] hasMarkedText])
1443         [self _setPluginComplexTextInputState:PluginComplexTextInputDisabled];
1444 }
1445
1446 - (BOOL)_handlePluginComplexTextInputKeyDown:(NSEvent *)event
1447 {
1448     ASSERT(_data->_pluginComplexTextInputIdentifier);
1449     ASSERT(_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled);
1450
1451     BOOL usingLegacyCocoaTextInput = _data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy;
1452
1453     NSString *string = nil;
1454     BOOL didHandleEvent = [[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:event usingLegacyCocoaTextInput:usingLegacyCocoaTextInput string:&string];
1455
1456     if (string) {
1457         _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string);
1458
1459         if (!usingLegacyCocoaTextInput)
1460             _data->_pluginComplexTextInputState = PluginComplexTextInputDisabled;
1461     }
1462
1463     return didHandleEvent;
1464 }
1465
1466 - (BOOL)_tryHandlePluginComplexTextInputKeyDown:(NSEvent *)event
1467 {
1468     if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
1469         return NO;
1470
1471     // Check if the text input window has been dismissed and let the plug-in process know.
1472     // This is only valid with the updated Cocoa text input spec.
1473     [self _disableComplexTextInputIfNecessary];
1474
1475     // Try feeding the keyboard event directly to the plug-in.
1476     if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
1477         return [self _handlePluginComplexTextInputKeyDown:event];
1478
1479     return NO;
1480 }
1481
1482 static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result)
1483 {
1484     int length = [[string string] length];
1485     
1486     int i = 0;
1487     while (i < length) {
1488         NSRange range;
1489         NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)];
1490         
1491         if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
1492             Color color = Color::black;
1493             if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName])
1494                 color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
1495             result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1));
1496         }
1497         
1498         i = range.location + range.length;
1499     }
1500 }
1501
1502 #if USE(ASYNC_NSTEXTINPUTCLIENT)
1503
1504 - (void)_collectKeyboardLayoutCommandsForEvent:(NSEvent *)event to:(Vector<KeypressCommand>&)commands
1505 {
1506     if ([event type] != NSKeyDown)
1507         return;
1508
1509     ASSERT(!_data->_collectedKeypressCommands);
1510     _data->_collectedKeypressCommands = &commands;
1511
1512     if (NSTextInputContext *context = [self inputContext])
1513         [context handleEventByKeyboardLayout:event];
1514     else
1515         [self interpretKeyEvents:[NSArray arrayWithObject:event]];
1516
1517     _data->_collectedKeypressCommands = nullptr;
1518 }
1519
1520 - (void)_interpretKeyEvent:(NSEvent *)event completionHandler:(void(^)(BOOL handled, const Vector<KeypressCommand>& commands))completionHandler
1521 {
1522     // For regular Web content, input methods run before passing a keydown to DOM, but plug-ins get an opportunity to handle the event first.
1523     // There is no need to collect commands, as the plug-in cannot execute them.
1524     if (_data->_pluginComplexTextInputIdentifier) {
1525         completionHandler(NO, Vector<KeypressCommand>());
1526         return;
1527     }
1528
1529     if (![self inputContext]) {
1530         Vector<KeypressCommand> commands;
1531         [self _collectKeyboardLayoutCommandsForEvent:event to:commands];
1532         completionHandler(NO, commands);
1533         return;
1534     }
1535
1536     LOG(TextInput, "-> handleEventByInputMethod:%p %@", event, event);
1537     [[self inputContext] handleEventByInputMethod:event completionHandler:^(BOOL handled) {
1538         
1539         LOG(TextInput, "... handleEventByInputMethod%s handled", handled ? "" : " not");
1540         if (handled) {
1541             completionHandler(YES, Vector<KeypressCommand>());
1542             return;
1543         }
1544
1545         Vector<KeypressCommand> commands;
1546         [self _collectKeyboardLayoutCommandsForEvent:event to:commands];
1547         completionHandler(NO, commands);
1548     }];
1549 }
1550
1551 - (void)doCommandBySelector:(SEL)selector
1552 {
1553     LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector));
1554
1555     Vector<KeypressCommand>* keypressCommands = _data->_collectedKeypressCommands;
1556
1557     if (keypressCommands) {
1558         KeypressCommand command(NSStringFromSelector(selector));
1559         keypressCommands->append(command);
1560         LOG(TextInput, "...stored");
1561         _data->_page->registerKeypressCommandName(command.commandName);
1562     } else {
1563         // FIXME: Send the command to Editor synchronously and only send it along the
1564         // responder chain if it's a selector that does not correspond to an editing command.
1565         [super doCommandBySelector:selector];
1566     }
1567 }
1568
1569 - (void)insertText:(id)string
1570 {
1571     // Unlike an NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context,
1572     // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText
1573     // command ensures that a keypress event is dispatched as appropriate.
1574     [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
1575 }
1576
1577 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
1578 {
1579     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1580     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1581
1582     if (replacementRange.location != NSNotFound)
1583         LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length);
1584     else
1585         LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
1586
1587     NSString *text;
1588     Vector<TextAlternativeWithRange> dictationAlternatives;
1589
1590     bool registerUndoGroup = false;
1591     if (isAttributedString) {
1592 #if USE(DICTATION_ALTERNATIVES)
1593         collectDictationTextAlternatives(string, dictationAlternatives);
1594 #endif
1595 #if USE(INSERTION_UNDO_GROUPING)
1596         registerUndoGroup = shouldRegisterInsertionUndoGroup(string);
1597 #endif
1598         // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data.
1599         text = [string string];
1600     } else
1601         text = string;
1602
1603     // insertText can be called for several reasons:
1604     // - If it's from normal key event processing (including key bindings), we save the action to perform it later.
1605     // - If it's from an input method, then we should go ahead and insert the text now.
1606     // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse),
1607     // then we also execute it immediately, as there will be no other chance.
1608     Vector<KeypressCommand>* keypressCommands = _data->_collectedKeypressCommands;
1609     if (keypressCommands) {
1610         ASSERT(replacementRange.location == NSNotFound);
1611         KeypressCommand command("insertText:", text);
1612         keypressCommands->append(command);
1613         LOG(TextInput, "...stored");
1614         _data->_page->registerKeypressCommandName(command.commandName);
1615         return;
1616     }
1617
1618     String eventText = text;
1619     eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
1620     if (!dictationAlternatives.isEmpty())
1621         _data->_page->insertDictatedTextAsync(eventText, replacementRange, dictationAlternatives, registerUndoGroup);
1622     else
1623         _data->_page->insertTextAsync(eventText, replacementRange, registerUndoGroup);
1624 }
1625
1626 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
1627 {
1628     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1629
1630     LOG(TextInput, "selectedRange");
1631     _data->_page->getSelectedRangeAsync([completionHandler](const EditingRange& editingRangeResult, CallbackBase::Error error) {
1632         void (^completionHandlerBlock)(NSRange) = (void (^)(NSRange))completionHandler.get();
1633         if (error != CallbackBase::Error::None) {
1634             LOG(TextInput, "    ...selectedRange failed.");
1635             completionHandlerBlock(NSMakeRange(NSNotFound, 0));
1636             return;
1637         }
1638         NSRange result = editingRangeResult;
1639         if (result.location == NSNotFound)
1640             LOG(TextInput, "    -> selectedRange returned (NSNotFound, %llu)", result.length);
1641         else
1642             LOG(TextInput, "    -> selectedRange returned (%llu, %llu)", result.location, result.length);
1643         completionHandlerBlock(result);
1644     });
1645 }
1646
1647 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
1648 {
1649     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1650
1651     LOG(TextInput, "markedRange");
1652     _data->_page->getMarkedRangeAsync([completionHandler](const EditingRange& editingRangeResult, CallbackBase::Error error) {
1653         void (^completionHandlerBlock)(NSRange) = (void (^)(NSRange))completionHandler.get();
1654         if (error != CallbackBase::Error::None) {
1655             LOG(TextInput, "    ...markedRange failed.");
1656             completionHandlerBlock(NSMakeRange(NSNotFound, 0));
1657             return;
1658         }
1659         NSRange result = editingRangeResult;
1660         if (result.location == NSNotFound)
1661             LOG(TextInput, "    -> markedRange returned (NSNotFound, %llu)", result.length);
1662         else
1663             LOG(TextInput, "    -> markedRange returned (%llu, %llu)", result.location, result.length);
1664         completionHandlerBlock(result);
1665     });
1666 }
1667
1668 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
1669 {
1670     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1671
1672     LOG(TextInput, "hasMarkedText");
1673     _data->_page->getMarkedRangeAsync([completionHandler](const EditingRange& editingRangeResult, CallbackBase::Error error) {
1674         void (^completionHandlerBlock)(BOOL) = (void (^)(BOOL))completionHandler.get();
1675         if (error != CallbackBase::Error::None) {
1676             LOG(TextInput, "    ...hasMarkedText failed.");
1677             completionHandlerBlock(NO);
1678             return;
1679         }
1680         BOOL hasMarkedText = editingRangeResult.location != notFound;
1681         LOG(TextInput, "    -> hasMarkedText returned %u", hasMarkedText);
1682         completionHandlerBlock(hasMarkedText);
1683     });
1684 }
1685
1686 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
1687 {
1688     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1689
1690     LOG(TextInput, "attributedSubstringFromRange:(%u, %u)", nsRange.location, nsRange.length);
1691     _data->_page->attributedSubstringForCharacterRangeAsync(nsRange, [completionHandler](const AttributedString& string, const EditingRange& actualRange, CallbackBase::Error error) {
1692         void (^completionHandlerBlock)(NSAttributedString *, NSRange) = (void (^)(NSAttributedString *, NSRange))completionHandler.get();
1693         if (error != CallbackBase::Error::None) {
1694             LOG(TextInput, "    ...attributedSubstringFromRange failed.");
1695             completionHandlerBlock(0, NSMakeRange(NSNotFound, 0));
1696             return;
1697         }
1698         LOG(TextInput, "    -> attributedSubstringFromRange returned %@", [string.string.get() string]);
1699         completionHandlerBlock([[string.string.get() retain] autorelease], actualRange);
1700     });
1701 }
1702
1703 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
1704 {
1705     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1706
1707     LOG(TextInput, "firstRectForCharacterRange:(%u, %u)", theRange.location, theRange.length);
1708
1709     // Just to match NSTextView's behavior. Regression tests cannot detect this;
1710     // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
1711     // (type something; try ranges (1, -1) and (2, -1).
1712     if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
1713         theRange.length = 0;
1714
1715     if (theRange.location == NSNotFound) {
1716         LOG(TextInput, "    -> NSZeroRect");
1717         completionHandlerPtr(NSZeroRect, theRange);
1718         return;
1719     }
1720
1721     _data->_page->firstRectForCharacterRangeAsync(theRange, [self, completionHandler](const IntRect& rect, const EditingRange& actualRange, CallbackBase::Error error) {
1722         void (^completionHandlerBlock)(NSRect, NSRange) = (void (^)(NSRect, NSRange))completionHandler.get();
1723         if (error != CallbackBase::Error::None) {
1724             LOG(TextInput, "    ...firstRectForCharacterRange failed.");
1725             completionHandlerBlock(NSZeroRect, NSMakeRange(NSNotFound, 0));
1726             return;
1727         }
1728
1729         NSRect resultRect = [self convertRect:rect toView:nil];
1730         resultRect = [self.window convertRectToScreen:resultRect];
1731
1732         LOG(TextInput, "    -> firstRectForCharacterRange returned (%f, %f, %f, %f)", resultRect.origin.x, resultRect.origin.y, resultRect.size.width, resultRect.size.height);
1733         completionHandlerBlock(resultRect, actualRange);
1734     });
1735 }
1736
1737 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
1738 {
1739     RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1740
1741     LOG(TextInput, "characterIndexForPoint:(%f, %f)", thePoint.x, thePoint.y);
1742
1743     NSWindow *window = [self window];
1744
1745 #pragma clang diagnostic push
1746 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1747     if (window)
1748         thePoint = [window convertScreenToBase:thePoint];
1749 #pragma clang diagnostic pop
1750     thePoint = [self convertPoint:thePoint fromView:nil];  // the point is relative to the main frame
1751
1752     _data->_page->characterIndexForPointAsync(IntPoint(thePoint), [completionHandler](uint64_t result, CallbackBase::Error error) {
1753         void (^completionHandlerBlock)(NSUInteger) = (void (^)(NSUInteger))completionHandler.get();
1754         if (error != CallbackBase::Error::None) {
1755             LOG(TextInput, "    ...characterIndexForPoint failed.");
1756             completionHandlerBlock(0);
1757             return;
1758         }
1759         if (result == notFound)
1760             result = NSNotFound;
1761         LOG(TextInput, "    -> characterIndexForPoint returned %lu", result);
1762         completionHandlerBlock(result);
1763     });
1764 }
1765
1766 - (NSTextInputContext *)inputContext
1767 {
1768     if (_data->_pluginComplexTextInputIdentifier) {
1769         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.
1770         return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
1771     }
1772
1773     // Disable text input machinery when in non-editable content. An invisible inline input area affects performance, and can prevent Expose from working.
1774     if (!_data->_page->editorState().isContentEditable)
1775         return nil;
1776
1777     return [super inputContext];
1778 }
1779
1780 - (void)unmarkText
1781 {
1782     LOG(TextInput, "unmarkText");
1783
1784     _data->_page->confirmCompositionAsync();
1785 }
1786
1787 - (void)setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
1788 {
1789     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1790     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1791
1792     LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u) replacementRange:(%u, %u)", isAttributedString ? [string string] : string, selectedRange.location, selectedRange.length, replacementRange.location, replacementRange.length);
1793
1794     Vector<CompositionUnderline> underlines;
1795     NSString *text;
1796
1797     if (isAttributedString) {
1798         // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation.
1799         text = [string string];
1800         extractUnderlines(string, underlines);
1801     } else
1802         text = string;
1803
1804     if (_data->_inSecureInputState) {
1805         // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField.
1806         // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard.
1807         ASSERT(!_data->_page->editorState().hasComposition);
1808         [self _notifyInputContextAboutDiscardedComposition];
1809         // FIXME: We should store the command to handle it after DOM event processing, as it's regular keyboard input now, not a composition.
1810         if ([text length] == 1 && isASCII([text characterAtIndex:0]))
1811             _data->_page->insertTextAsync(text, replacementRange);
1812         else
1813             NSBeep();
1814         return;
1815     }
1816
1817     _data->_page->setCompositionAsync(text, underlines, selectedRange, replacementRange);
1818 }
1819
1820 // Synchronous NSTextInputClient is still implemented to catch spurious sync calls. Remove when that is no longer needed.
1821
1822 - (NSRange)selectedRange NO_RETURN_DUE_TO_ASSERT
1823 {
1824     ASSERT_NOT_REACHED();
1825     return NSMakeRange(NSNotFound, 0);
1826 }
1827
1828 - (BOOL)hasMarkedText NO_RETURN_DUE_TO_ASSERT
1829 {
1830     ASSERT_NOT_REACHED();
1831     return NO;
1832 }
1833
1834 - (NSRange)markedRange NO_RETURN_DUE_TO_ASSERT
1835 {
1836     ASSERT_NOT_REACHED();
1837     return NSMakeRange(NSNotFound, 0);
1838 }
1839
1840 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange NO_RETURN_DUE_TO_ASSERT
1841 {
1842     ASSERT_NOT_REACHED();
1843     return nil;
1844 }
1845
1846 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint NO_RETURN_DUE_TO_ASSERT
1847 {
1848     ASSERT_NOT_REACHED();
1849     return 0;
1850 }
1851
1852 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange NO_RETURN_DUE_TO_ASSERT
1853
1854     ASSERT_NOT_REACHED();
1855     return NSMakeRect(0, 0, 0, 0);
1856 }
1857
1858 - (BOOL)performKeyEquivalent:(NSEvent *)event
1859 {
1860     if (_data->_ignoresNonWheelEvents)
1861         return NO;
1862
1863     // There's a chance that responding to this event will run a nested event loop, and
1864     // fetching a new event might release the old one. Retaining and then autoreleasing
1865     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1866     [[event retain] autorelease];
1867
1868     // 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,
1869     // but both get transformed to a cancelOperation: command, executing which passes an Esc key event to -performKeyEquivalent:.
1870     // Don't interpret this event again, avoiding re-entrancy and infinite loops.
1871     if ([[event charactersIgnoringModifiers] isEqualToString:@"\e"] && !([event modifierFlags] & NSDeviceIndependentModifierFlagsMask))
1872         return [super performKeyEquivalent:event];
1873
1874     if (_data->_keyDownEventBeingResent) {
1875         // WebCore has already seen the event, no need for custom processing.
1876         // Note that we can get multiple events for each event being re-sent. For example, for Cmd+'=' AppKit
1877         // first performs the original key equivalent, and if that isn't handled, it dispatches a synthetic Cmd+'+'.
1878         return [super performKeyEquivalent:event];
1879     }
1880
1881     ASSERT(event == [NSApp currentEvent]);
1882
1883     [self _disableComplexTextInputIfNecessary];
1884
1885     // Pass key combos through WebCore if there is a key binding available for
1886     // this event. This lets webpages have a crack at intercepting key-modified keypresses.
1887     // FIXME: Why is the firstResponder check needed?
1888     if (self == [[self window] firstResponder]) {
1889         [self _interpretKeyEvent:event completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1890             _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, handledByInputMethod, commands));
1891         }];
1892         return YES;
1893     }
1894     
1895     return [super performKeyEquivalent:event];
1896 }
1897
1898 - (void)keyUp:(NSEvent *)theEvent
1899 {
1900     if (_data->_ignoresNonWheelEvents)
1901         return;
1902
1903     LOG(TextInput, "keyUp:%p %@", theEvent, theEvent);
1904
1905     [self _interpretKeyEvent:theEvent completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1906         ASSERT(!handledByInputMethod || commands.isEmpty());
1907         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
1908     }];
1909 }
1910
1911 - (void)keyDown:(NSEvent *)theEvent
1912 {
1913     if (_data->_ignoresNonWheelEvents)
1914         return;
1915
1916     LOG(TextInput, "keyDown:%p %@%s", theEvent, theEvent, (theEvent == _data->_keyDownEventBeingResent) ? " (re-sent)" : "");
1917
1918     if ([self _tryHandlePluginComplexTextInputKeyDown:theEvent]) {
1919         LOG(TextInput, "...handled by plug-in");
1920         return;
1921     }
1922
1923     // We could be receiving a key down from AppKit if we have re-sent an event
1924     // that maps to an action that is currently unavailable (for example a copy when
1925     // there is no range selection).
1926     // If this is the case we should ignore the key down.
1927     if (_data->_keyDownEventBeingResent == theEvent) {
1928         [super keyDown:theEvent];
1929         return;
1930     }
1931
1932     [self _interpretKeyEvent:theEvent completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1933         ASSERT(!handledByInputMethod || commands.isEmpty());
1934         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
1935     }];
1936 }
1937
1938 - (void)flagsChanged:(NSEvent *)theEvent
1939 {
1940     if (_data->_ignoresNonWheelEvents)
1941         return;
1942
1943     LOG(TextInput, "flagsChanged:%p %@", theEvent, theEvent);
1944
1945     unsigned short keyCode = [theEvent keyCode];
1946
1947     // Don't make an event from the num lock and function keys
1948     if (!keyCode || keyCode == 10 || keyCode == 63)
1949         return;
1950
1951     [self _interpretKeyEvent:theEvent completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1952         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
1953     }];
1954 }
1955
1956 #else // USE(ASYNC_NSTEXTINPUTCLIENT)
1957
1958 - (BOOL)_interpretKeyEvent:(NSEvent *)event savingCommandsTo:(Vector<WebCore::KeypressCommand>&)commands
1959 {
1960     ASSERT(!_data->_interpretKeyEventsParameters);
1961     ASSERT(commands.isEmpty());
1962
1963     if ([event type] == NSFlagsChanged)
1964         return NO;
1965
1966     WKViewInterpretKeyEventsParameters parameters;
1967     parameters.eventInterpretationHadSideEffects = false;
1968     parameters.executingSavedKeypressCommands = false;
1969     // We assume that an input method has consumed the event, and only change this assumption if one of the NSTextInput methods is called.
1970     // We assume the IM will *not* consume hotkey sequences.
1971     parameters.consumedByIM = !([event modifierFlags] & NSCommandKeyMask);
1972     parameters.commands = &commands;
1973     _data->_interpretKeyEventsParameters = &parameters;
1974
1975     LOG(TextInput, "-> interpretKeyEvents:%p %@", event, event);
1976     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
1977
1978     _data->_interpretKeyEventsParameters = nullptr;
1979
1980     // An input method may consume an event and not tell us (e.g. when displaying a candidate window),
1981     // in which case we should not bubble the event up the DOM.
1982     if (parameters.consumedByIM) {
1983         ASSERT(commands.isEmpty());
1984         LOG(TextInput, "...event %p was consumed by an input method", event);
1985         return YES;
1986     }
1987
1988     LOG(TextInput, "...interpretKeyEvents for event %p done, returns %d", event, parameters.eventInterpretationHadSideEffects);
1989
1990     // 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.
1991     return parameters.eventInterpretationHadSideEffects;
1992 }
1993
1994 - (void)_executeSavedKeypressCommands
1995 {
1996     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1997     if (!parameters || parameters->commands->isEmpty())
1998         return;
1999
2000     // We could be called again if the execution of one command triggers a call to selectedRange.
2001     // In this case, the state is up to date, and we don't need to execute any more saved commands to return a result.
2002     if (parameters->executingSavedKeypressCommands)
2003         return;
2004
2005     LOG(TextInput, "Executing %u saved keypress commands...", parameters->commands->size());
2006
2007     parameters->executingSavedKeypressCommands = true;
2008     parameters->eventInterpretationHadSideEffects |= _data->_page->executeKeypressCommands(*parameters->commands);
2009     parameters->commands->clear();
2010     parameters->executingSavedKeypressCommands = false;
2011
2012     LOG(TextInput, "...done executing saved keypress commands.");
2013 }
2014
2015 - (void)doCommandBySelector:(SEL)selector
2016 {
2017     LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector));
2018
2019     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
2020     if (parameters)
2021         parameters->consumedByIM = false;
2022
2023     // As in insertText:replacementRange:, we assume that the call comes from an input method if there is marked text.
2024     bool isFromInputMethod = _data->_page->editorState().hasComposition;
2025
2026     if (parameters && !isFromInputMethod) {
2027         KeypressCommand command(NSStringFromSelector(selector));
2028         parameters->commands->append(command);
2029         LOG(TextInput, "...stored");
2030         _data->_page->registerKeypressCommandName(command.commandName);
2031     } else {
2032         // FIXME: Send the command to Editor synchronously and only send it along the
2033         // responder chain if it's a selector that does not correspond to an editing command.
2034         [super doCommandBySelector:selector];
2035     }
2036 }
2037
2038 - (void)insertText:(id)string
2039 {
2040     // Unlike an NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context,
2041     // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText
2042     // command ensures that a keypress event is dispatched as appropriate.
2043     [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
2044 }
2045
2046 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
2047 {
2048     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
2049     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
2050
2051     if (replacementRange.location != NSNotFound)
2052         LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length);
2053     else
2054         LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
2055     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
2056     if (parameters)
2057         parameters->consumedByIM = false;
2058
2059     NSString *text;
2060     bool isFromInputMethod = _data->_page->editorState().hasComposition;
2061
2062     Vector<TextAlternativeWithRange> dictationAlternatives;
2063
2064     if (isAttributedString) {
2065 #if USE(DICTATION_ALTERNATIVES)
2066         collectDictationTextAlternatives(string, dictationAlternatives);
2067 #endif
2068         // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data.
2069         text = [string string];
2070     } else
2071         text = string;
2072
2073     // insertText can be called for several reasons:
2074     // - If it's from normal key event processing (including key bindings), we may need to save the action to perform it later.
2075     // - If it's from an input method, then we should go ahead and insert the text now. We assume it's from the input method if we have marked text.
2076     // 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.
2077     // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse),
2078     // then we also execute it immediately, as there will be no other chance.
2079     if (parameters && !isFromInputMethod) {
2080         // FIXME: Handle replacementRange in this case, too. It's known to occur in practice when canceling Press and Hold (see <rdar://11940670>).
2081         ASSERT(replacementRange.location == NSNotFound);
2082         KeypressCommand command("insertText:", text);
2083         parameters->commands->append(command);
2084         _data->_page->registerKeypressCommandName(command.commandName);
2085         return;
2086     }
2087
2088     String eventText = text;
2089     eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
2090     bool eventHandled;
2091     if (!dictationAlternatives.isEmpty())
2092         eventHandled = _data->_page->insertDictatedText(eventText, replacementRange, dictationAlternatives);
2093     else
2094         eventHandled = _data->_page->insertText(eventText, replacementRange);
2095
2096     if (parameters)
2097         parameters->eventInterpretationHadSideEffects |= eventHandled;
2098 }
2099
2100 - (NSTextInputContext *)inputContext
2101 {
2102     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
2103
2104     if (_data->_pluginComplexTextInputIdentifier && !parameters)
2105         return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
2106
2107     // Disable text input machinery when in non-editable content. An invisible inline input area affects performance, and can prevent Expose from working.
2108     if (!_data->_page->editorState().isContentEditable)
2109         return nil;
2110
2111     return [super inputContext];
2112 }
2113
2114 - (NSRange)selectedRange
2115 {
2116     [self _executeSavedKeypressCommands];
2117
2118     EditingRange selectedRange;
2119     _data->_page->getSelectedRange(selectedRange);
2120
2121     NSRange result = selectedRange;
2122     if (result.location == NSNotFound)
2123         LOG(TextInput, "selectedRange -> (NSNotFound, %u)", result.length);
2124     else
2125         LOG(TextInput, "selectedRange -> (%u, %u)", result.location, result.length);
2126
2127     return result;
2128 }
2129
2130 - (BOOL)hasMarkedText
2131 {
2132     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
2133
2134     BOOL result;
2135     if (parameters) {
2136         result = _data->_page->editorState().hasComposition;
2137         if (result) {
2138             // A saved command can confirm a composition, but it cannot start a new one.
2139             [self _executeSavedKeypressCommands];
2140             result = _data->_page->editorState().hasComposition;
2141         }
2142     } else {
2143         EditingRange markedRange;
2144         _data->_page->getMarkedRange(markedRange);
2145         result = markedRange.location != notFound;
2146     }
2147
2148     LOG(TextInput, "hasMarkedText -> %u", result);
2149     return result;
2150 }
2151
2152 - (void)unmarkText
2153 {
2154     [self _executeSavedKeypressCommands];
2155
2156     LOG(TextInput, "unmarkText");
2157
2158     // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
2159     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
2160
2161     if (parameters) {
2162         parameters->eventInterpretationHadSideEffects = true;
2163         parameters->consumedByIM = false;
2164     }
2165
2166     _data->_page->confirmComposition();
2167 }
2168
2169 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
2170 {
2171     [self _executeSavedKeypressCommands];
2172
2173     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
2174     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
2175
2176     LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelectedRange.location, newSelectedRange.length);
2177
2178     // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
2179     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
2180
2181     if (parameters) {
2182         parameters->eventInterpretationHadSideEffects = true;
2183         parameters->consumedByIM = false;
2184     }
2185     
2186     Vector<CompositionUnderline> underlines;
2187     NSString *text;
2188
2189     if (isAttributedString) {
2190         // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation.
2191         text = [string string];
2192         extractUnderlines(string, underlines);
2193     } else
2194         text = string;
2195
2196     if (_data->_page->editorState().isInPasswordField) {
2197         // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField.
2198         // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard.
2199         ASSERT(!_data->_page->editorState().hasComposition);
2200         [self _notifyInputContextAboutDiscardedComposition];
2201         if ([text length] == 1 && [[text decomposedStringWithCanonicalMapping] characterAtIndex:0] < 0x80) {
2202             _data->_page->insertText(text, replacementRange);
2203         } else
2204             NSBeep();
2205         return;
2206     }
2207
2208     _data->_page->setComposition(text, underlines, newSelectedRange, replacementRange);
2209 }
2210
2211 - (NSRange)markedRange
2212 {
2213     [self _executeSavedKeypressCommands];
2214
2215     EditingRange markedRange;
2216     _data->_page->getMarkedRange(markedRange);
2217
2218     NSRange result = markedRange;
2219     if (result.location == NSNotFound)
2220         LOG(TextInput, "markedRange -> (NSNotFound, %u)", result.length);
2221     else
2222         LOG(TextInput, "markedRange -> (%u, %u)", result.location, result.length);
2223
2224     return result;
2225 }
2226
2227 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
2228 {
2229     [self _executeSavedKeypressCommands];
2230
2231     if (!_data->_page->editorState().isContentEditable) {
2232         LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> nil", nsRange.location, nsRange.length);
2233         return nil;
2234     }
2235
2236     if (_data->_page->editorState().isInPasswordField)
2237         return nil;
2238
2239     AttributedString result;
2240     _data->_page->getAttributedSubstringFromRange(nsRange, result);
2241
2242     if (actualRange) {
2243         *actualRange = nsRange;
2244         actualRange->length = [result.string length];
2245     }
2246
2247     LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> \"%@\"", nsRange.location, nsRange.length, [result.string string]);
2248     return [[result.string retain] autorelease];
2249 }
2250
2251 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
2252 {
2253     [self _executeSavedKeypressCommands];
2254
2255     NSWindow *window = [self window];
2256     
2257 #pragma clang diagnostic push
2258 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2259     if (window)
2260         thePoint = [window convertScreenToBase:thePoint];
2261 #pragma clang diagnostic pop
2262     thePoint = [self convertPoint:thePoint fromView:nil];  // the point is relative to the main frame
2263     
2264     uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint));
2265     if (result == notFound)
2266         result = NSNotFound;
2267     LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result);
2268     return result;
2269 }
2270
2271 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
2272
2273     [self _executeSavedKeypressCommands];
2274
2275     // Just to match NSTextView's behavior. Regression tests cannot detect this;
2276     // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
2277     // (type something; try ranges (1, -1) and (2, -1).
2278     if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
2279         theRange.length = 0;
2280
2281     if (theRange.location == NSNotFound) {
2282         if (actualRange)
2283             *actualRange = theRange;
2284         LOG(TextInput, "firstRectForCharacterRange:(NSNotFound, %u) -> NSZeroRect", theRange.length);
2285         return NSZeroRect;
2286     }
2287
2288     NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange);
2289     resultRect = [self convertRect:resultRect toView:nil];
2290     resultRect = [self.window convertRectToScreen:resultRect];
2291
2292     if (actualRange) {
2293         // FIXME: Update actualRange to match the range of first rect.
2294         *actualRange = theRange;
2295     }
2296
2297     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);
2298     return resultRect;
2299 }
2300
2301 - (BOOL)performKeyEquivalent:(NSEvent *)event
2302 {
2303     if (_data->_ignoresNonWheelEvents)
2304         return NO;
2305
2306     // There's a chance that responding to this event will run a nested event loop, and
2307     // fetching a new event might release the old one. Retaining and then autoreleasing
2308     // the current event prevents that from causing a problem inside WebKit or AppKit code.
2309     [[event retain] autorelease];
2310
2311     // 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,
2312     // but both get transformed to a cancelOperation: command, executing which passes an Esc key event to -performKeyEquivalent:.
2313     // Don't interpret this event again, avoiding re-entrancy and infinite loops.
2314     if ([[event charactersIgnoringModifiers] isEqualToString:@"\e"] && !([event modifierFlags] & NSDeviceIndependentModifierFlagsMask))
2315         return [super performKeyEquivalent:event];
2316
2317     if (_data->_keyDownEventBeingResent) {
2318         // WebCore has already seen the event, no need for custom processing.
2319         // Note that we can get multiple events for each event being re-sent. For example, for Cmd+'=' AppKit
2320         // first performs the original key equivalent, and if that isn't handled, it dispatches a synthetic Cmd+'+'.
2321         return [super performKeyEquivalent:event];
2322     }
2323
2324     ASSERT(event == [NSApp currentEvent]);
2325
2326     [self _disableComplexTextInputIfNecessary];
2327
2328     // Pass key combos through WebCore if there is a key binding available for
2329     // this event. This lets webpages have a crack at intercepting key-modified keypresses.
2330     // FIXME: Why is the firstResponder check needed?
2331     if (self == [[self window] firstResponder]) {
2332         Vector<KeypressCommand> commands;
2333         BOOL handledByInputMethod = [self _interpretKeyEvent:event savingCommandsTo:commands];
2334         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, handledByInputMethod, commands));
2335         return YES;
2336     }
2337     
2338     return [super performKeyEquivalent:event];
2339 }
2340
2341 - (void)keyUp:(NSEvent *)theEvent
2342 {
2343     if (_data->_ignoresNonWheelEvents)
2344         return;
2345
2346     LOG(TextInput, "keyUp:%p %@", theEvent, theEvent);
2347     // We don't interpret the keyUp event, as this breaks key bindings (see <https://bugs.webkit.org/show_bug.cgi?id=130100>).
2348     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, false, Vector<KeypressCommand>()));
2349 }
2350
2351 - (void)keyDown:(NSEvent *)theEvent
2352 {
2353     if (_data->_ignoresNonWheelEvents)
2354         return;
2355
2356     LOG(TextInput, "keyDown:%p %@%s", theEvent, theEvent, (theEvent == _data->_keyDownEventBeingResent) ? " (re-sent)" : "");
2357
2358     // There's a chance that responding to this event will run a nested event loop, and
2359     // fetching a new event might release the old one. Retaining and then autoreleasing
2360     // the current event prevents that from causing a problem inside WebKit or AppKit code.
2361     [[theEvent retain] autorelease];
2362
2363     if ([self _tryHandlePluginComplexTextInputKeyDown:theEvent]) {
2364         LOG(TextInput, "...handled by plug-in");
2365         return;
2366     }
2367
2368     // We could be receiving a key down from AppKit if we have re-sent an event
2369     // that maps to an action that is currently unavailable (for example a copy when
2370     // there is no range selection).
2371     // If this is the case we should ignore the key down.
2372     if (_data->_keyDownEventBeingResent == theEvent) {
2373         [super keyDown:theEvent];
2374         return;
2375     }
2376
2377     Vector<KeypressCommand> commands;
2378     BOOL handledByInputMethod = [self _interpretKeyEvent:theEvent savingCommandsTo:commands];
2379     if (!commands.isEmpty()) {
2380         // An input method may make several actions per keypress. For example, pressing Return with Korean IM both confirms it and sends a newline.
2381         // IM-like actions are handled immediately (so the return value from UI process is true), but there are saved commands that
2382         // should be handled like normal text input after DOM event dispatch.
2383         handledByInputMethod = NO;
2384     }
2385
2386     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
2387 }
2388
2389 - (void)flagsChanged:(NSEvent *)theEvent
2390 {
2391     if (_data->_ignoresNonWheelEvents)
2392         return;
2393
2394     LOG(TextInput, "flagsChanged:%p %@", theEvent, theEvent);
2395
2396     // There's a chance that responding to this event will run a nested event loop, and
2397     // fetching a new event might release the old one. Retaining and then autoreleasing
2398     // the current event prevents that from causing a problem inside WebKit or AppKit code.
2399     [[theEvent retain] autorelease];
2400
2401     unsigned short keyCode = [theEvent keyCode];
2402
2403     // Don't make an event from the num lock and function keys
2404     if (!keyCode || keyCode == 10 || keyCode == 63)
2405         return;
2406
2407     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, false, Vector<KeypressCommand>()));
2408 }
2409
2410 #endif // USE(ASYNC_NSTEXTINPUTCLIENT)
2411
2412 - (NSArray *)validAttributesForMarkedText
2413 {
2414     static NSArray *validAttributes;
2415     if (!validAttributes) {
2416         validAttributes = [[NSArray alloc] initWithObjects:
2417                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
2418                            NSMarkedClauseSegmentAttributeName,
2419 #if USE(DICTATION_ALTERNATIVES)
2420                            NSTextAlternativesAttributeName,
2421 #endif
2422 #if USE(INSERTION_UNDO_GROUPING)
2423                            NSTextInsertionUndoableAttributeName,
2424 #endif
2425                            nil];
2426         // NSText also supports the following attributes, but it's
2427         // hard to tell which are really required for text input to
2428         // work well; I have not seen any input method make use of them yet.
2429         //     NSFontAttributeName, NSForegroundColorAttributeName,
2430         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
2431         CFRetain(validAttributes);
2432     }
2433     LOG(TextInput, "validAttributesForMarkedText -> (...)");
2434     return validAttributes;
2435 }
2436
2437 #if ENABLE(DRAG_SUPPORT)
2438 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2439 {
2440     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2441     NSPoint windowMouseLoc = windowImageLoc;
2442    
2443     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2444     _data->_ignoringMouseDraggedEvents = YES;
2445     
2446     _data->_page->dragEnded(IntPoint(windowMouseLoc), globalPoint(windowMouseLoc, [self window]), operation);
2447 }
2448
2449 - (DragApplicationFlags)applicationFlags:(id <NSDraggingInfo>)draggingInfo
2450 {
2451     uint32_t flags = 0;
2452     if ([NSApp modalWindow])
2453         flags = DragApplicationIsModal;
2454     if ([[self window] attachedSheet])
2455         flags |= DragApplicationHasAttachedSheet;
2456     if ([draggingInfo draggingSource] == self)
2457         flags |= DragApplicationIsSource;
2458     if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
2459         flags |= DragApplicationIsCopyKeyDown;
2460     return static_cast<DragApplicationFlags>(flags);
2461 }
2462
2463 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2464 {
2465     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2466     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2467     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2468
2469     _data->_page->resetCurrentDragInformation();
2470     _data->_page->dragEntered(dragData, [[draggingInfo draggingPasteboard] name]);
2471     return NSDragOperationCopy;
2472 }
2473
2474 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2475 {
2476     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2477     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2478     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2479     _data->_page->dragUpdated(dragData, [[draggingInfo draggingPasteboard] name]);
2480     
2481     NSInteger numberOfValidItemsForDrop = _data->_page->currentDragNumberOfFilesToBeAccepted();
2482     NSDraggingFormation draggingFormation = NSDraggingFormationNone;
2483     if (_data->_page->currentDragIsOverFileInput() && numberOfValidItemsForDrop > 0)
2484         draggingFormation = NSDraggingFormationList;
2485
2486     if ([draggingInfo numberOfValidItemsForDrop] != numberOfValidItemsForDrop)
2487         [draggingInfo setNumberOfValidItemsForDrop:numberOfValidItemsForDrop];
2488     if ([draggingInfo draggingFormation] != draggingFormation)
2489         [draggingInfo setDraggingFormation:draggingFormation];
2490
2491     return _data->_page->currentDragOperation();
2492 }
2493
2494 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2495 {
2496     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2497     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2498     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2499     _data->_page->dragExited(dragData, [[draggingInfo draggingPasteboard] name]);
2500     _data->_page->resetCurrentDragInformation();
2501 }
2502
2503 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2504 {
2505     return YES;
2506 }
2507
2508 // FIXME: This code is more or less copied from Pasteboard::getBestURL.
2509 // It would be nice to be able to share the code somehow.
2510 static bool maybeCreateSandboxExtensionFromPasteboard(NSPasteboard *pasteboard, SandboxExtension::Handle& sandboxExtensionHandle)
2511 {
2512     NSArray *types = [pasteboard types];
2513     if (![types containsObject:NSFilenamesPboardType])
2514         return false;
2515
2516     NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
2517     if ([files count] != 1)
2518         return false;
2519
2520     NSString *file = [files objectAtIndex:0];
2521     BOOL isDirectory;
2522     if (![[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory])
2523         return false;
2524
2525     if (isDirectory)
2526         return false;
2527
2528     SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle);
2529     return true;
2530 }
2531
2532 static void createSandboxExtensionsForFileUpload(NSPasteboard *pasteboard, SandboxExtension::HandleArray& handles)
2533 {
2534     NSArray *types = [pasteboard types];
2535     if (![types containsObject:NSFilenamesPboardType])
2536         return;
2537
2538     NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
2539     handles.allocate([files count]);
2540     for (unsigned i = 0; i < [files count]; i++) {
2541         NSString *file = [files objectAtIndex:i];
2542         if (![[NSFileManager defaultManager] fileExistsAtPath:file])
2543             continue;
2544         SandboxExtension::Handle handle;
2545         SandboxExtension::createHandle(file, SandboxExtension::ReadOnly, handles[i]);
2546     }
2547 }
2548
2549 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2550 {
2551     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2552     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2553     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2554
2555     SandboxExtension::Handle sandboxExtensionHandle;
2556     bool createdExtension = maybeCreateSandboxExtensionFromPasteboard([draggingInfo draggingPasteboard], sandboxExtensionHandle);
2557     if (createdExtension)
2558         _data->_page->process().willAcquireUniversalFileReadSandboxExtension();
2559
2560     SandboxExtension::HandleArray sandboxExtensionForUpload;
2561     createSandboxExtensionsForFileUpload([draggingInfo draggingPasteboard], sandboxExtensionForUpload);
2562
2563     _data->_page->performDragOperation(dragData, [[draggingInfo draggingPasteboard] name], sandboxExtensionHandle, sandboxExtensionForUpload);
2564
2565     return YES;
2566 }
2567
2568 // This code is needed to support drag and drop when the drag types cannot be matched.
2569 // This is the case for elements that do not place content
2570 // in the drag pasteboard automatically when the drag start (i.e. dragging a DIV element).
2571 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
2572 {
2573     if ([[self superview] mouse:*point inRect:[self frame]])
2574         return self;
2575     return nil;
2576 }
2577 #endif // ENABLE(DRAG_SUPPORT)
2578
2579 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)loc
2580 {
2581     NSPoint localPoint = [self convertPoint:loc fromView:nil];
2582     NSRect visibleThumbRect = NSRect(_data->_page->visibleScrollerThumbRect());
2583     return NSMouseInRect(localPoint, visibleThumbRect, [self isFlipped]);
2584 }
2585
2586 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2587 static void* keyValueObservingContext = &keyValueObservingContext;
2588 #endif
2589
2590 - (void)addWindowObserversForWindow:(NSWindow *)window
2591 {
2592     if (window) {
2593         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
2594                                                      name:NSWindowDidBecomeKeyNotification object:nil];
2595         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
2596                                                      name:NSWindowDidResignKeyNotification object:nil];
2597         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) 
2598                                                      name:NSWindowDidMiniaturizeNotification object:window];
2599         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
2600                                                      name:NSWindowDidDeminiaturizeNotification object:window];
2601         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMove:)
2602                                                      name:NSWindowDidMoveNotification object:window];
2603         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResize:) 
2604                                                      name:NSWindowDidResizeNotification object:window];
2605         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeBackingProperties:)
2606                                                      name:NSWindowDidChangeBackingPropertiesNotification object:window];
2607         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeScreen:)
2608                                                      name:NSWindowDidChangeScreenNotification object:window];
2609         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeLayerHosting:)
2610                                                      name:@"_NSWindowDidChangeContentsHostedInLayerSurfaceNotification" object:window];
2611         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeOcclusionState:)
2612                                                      name:NSWindowDidChangeOcclusionStateNotification object:window];
2613         [[NSFontPanel sharedFontPanel] addObserver:self
2614                                         forKeyPath:@"visible"
2615                                            options:NSKeyValueObservingOptionNew
2616                                            context:nil];
2617 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2618         [window addObserver:self forKeyPath:@"contentLayoutRect" options:NSKeyValueObservingOptionInitial context:keyValueObservingContext];
2619         [window addObserver:self forKeyPath:@"titlebarAppearsTransparent" options:NSKeyValueObservingOptionInitial context:keyValueObservingContext];
2620 #endif
2621         [_data->_windowVisibilityObserver startObserving:window];
2622     }
2623 }
2624
2625 - (void)removeWindowObservers
2626 {
2627     NSWindow *window = _data->_targetWindowForMovePreparation ? _data->_targetWindowForMovePreparation : [self window];
2628     if (!window)
2629         return;
2630
2631     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
2632     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
2633     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
2634     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
2635     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
2636     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
2637     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeBackingPropertiesNotification object:window];
2638     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeScreenNotification object:window];
2639     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"_NSWindowDidChangeContentsHostedInLayerSurfaceNotification" object:window];
2640     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeOcclusionStateNotification object:window];
2641     [[NSFontPanel sharedFontPanel] removeObserver:self forKeyPath:@"visible" context:nil];
2642 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2643     [window removeObserver:self forKeyPath:@"contentLayoutRect" context:keyValueObservingContext];
2644     [window removeObserver:self forKeyPath:@"titlebarAppearsTransparent" context:keyValueObservingContext];
2645 #endif
2646     [_data->_windowVisibilityObserver stopObserving:window];
2647 }
2648
2649 - (void)viewWillMoveToWindow:(NSWindow *)window
2650 {
2651     // If we're in the middle of preparing to move to a window, we should only be moved to that window.
2652     ASSERT(!_data->_targetWindowForMovePreparation || (_data->_targetWindowForMovePreparation == window));
2653
2654     NSWindow *currentWindow = [self window];
2655     if (window == currentWindow)
2656         return;
2657
2658     _data->_pageClient->viewWillMoveToAnotherWindow();
2659     
2660     [self removeWindowObservers];
2661     [self addWindowObserversForWindow:window];
2662 }
2663
2664 - (void)viewDidMoveToWindow
2665 {
2666     NSWindow *window = _data->_targetWindowForMovePreparation ? _data->_targetWindowForMovePreparation : self.window;
2667
2668     if (window) {
2669         [self doWindowDidChangeScreen];
2670
2671         ViewState::Flags viewStateChanges = ViewState::WindowIsActive | ViewState::IsVisible;
2672         if ([self isDeferringViewInWindowChanges])
2673             _data->_viewInWindowChangeWasDeferred = YES;
2674         else
2675             viewStateChanges |= ViewState::IsInWindow;
2676         _data->_page->viewStateDidChange(viewStateChanges);
2677
2678         [self _updateWindowAndViewFrames];
2679
2680         // FIXME(135509) This call becomes unnecessary once 135509 is fixed; remove.
2681         _data->_page->layerHostingModeDidChange();
2682
2683         if (!_data->_flagsChangedEventMonitor) {
2684             _data->_flagsChangedEventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSFlagsChangedMask handler:^(NSEvent *flagsChangedEvent) {
2685                 [self _postFakeMouseMovedEventForFlagsChangedEvent:flagsChangedEvent];
2686                 return flagsChangedEvent;
2687             }];
2688         }
2689
2690         [self _accessibilityRegisterUIProcessTokens];
2691
2692 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2693         if (_data->_immediateActionGestureRecognizer && ![[self gestureRecognizers] containsObject:_data->_immediateActionGestureRecognizer.get()] && !_data->_ignoresNonWheelEvents)
2694             [self addGestureRecognizer:_data->_immediateActionGestureRecognizer.get()];
2695 #endif
2696     } else {
2697         ViewState::Flags viewStateChanges = ViewState::WindowIsActive | ViewState::IsVisible;
2698         if ([self isDeferringViewInWindowChanges])
2699             _data->_viewInWindowChangeWasDeferred = YES;
2700         else
2701             viewStateChanges |= ViewState::IsInWindow;
2702         _data->_page->viewStateDidChange(viewStateChanges);
2703
2704         [NSEvent removeMonitor:_data->_flagsChangedEventMonitor];
2705         _data->_flagsChangedEventMonitor = nil;
2706
2707         [self _dismissContentRelativeChildWindows];
2708
2709 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2710         if (_data->_immediateActionGestureRecognizer)
2711             [self removeGestureRecognizer:_data->_immediateActionGestureRecognizer.get()];
2712 #endif
2713     }
2714
2715     _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]);
2716 }
2717
2718 - (void)doWindowDidChangeScreen
2719 {
2720     NSWindow *window = _data->_targetWindowForMovePreparation ? _data->_targetWindowForMovePreparation : self.window;
2721     _data->_page->windowScreenDidChange((PlatformDisplayID)[[[[window screen] deviceDescription] objectForKey:@"NSScreenNumber"] intValue]);
2722 }
2723
2724 - (void)_windowDidBecomeKey:(NSNotification *)notification
2725 {
2726     NSWindow *keyWindow = [notification object];
2727     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet]) {
2728         [self _updateSecureInputState];
2729         _data->_page->viewStateDidChange(ViewState::WindowIsActive);
2730     }
2731 }
2732
2733 - (void)_windowDidChangeScreen:(NSNotification *)notification
2734 {
2735     [self doWindowDidChangeScreen];
2736 }
2737
2738 - (void)_windowDidChangeLayerHosting:(NSNotification *)notification
2739 {
2740     _data->_page->layerHostingModeDidChange();
2741 }
2742
2743 - (void)_windowDidResignKey:(NSNotification *)notification
2744 {
2745     NSWindow *formerKeyWindow = [notification object];
2746     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) {
2747         [self _updateSecureInputState];
2748         _data->_page->viewStateDidChange(ViewState::WindowIsActive);
2749     }
2750 }
2751
2752 - (void)_windowDidMiniaturize:(NSNotification *)notification
2753 {
2754     _data->_page->viewStateDidChange(ViewState::IsVisible);
2755 }
2756
2757 - (void)_windowDidDeminiaturize:(NSNotification *)notification
2758 {
2759     _data->_page->viewStateDidChange(ViewState::IsVisible);
2760 }
2761
2762 - (void)_windowDidMove:(NSNotification *)notification
2763 {
2764     [self _updateWindowAndViewFrames];    
2765 }
2766
2767 - (void)_windowDidResize:(NSNotification *)notification
2768 {
2769     [self _updateWindowAndViewFrames];
2770 }
2771
2772 - (void)_windowDidOrderOffScreen:(NSNotification *)notification
2773 {
2774     _data->_page->viewStateDidChange(ViewState::IsVisible | ViewState::WindowIsActive);
2775 }
2776
2777 - (void)_windowDidOrderOnScreen:(NSNotification *)notification
2778 {
2779     _data->_page->viewStateDidChange(ViewState::IsVisible | ViewState::WindowIsActive);
2780 }
2781
2782 - (void)_windowDidChangeBackingProperties:(NSNotification *)notification
2783 {
2784     CGFloat oldBackingScaleFactor = [[notification.userInfo objectForKey:NSBackingPropertyOldScaleFactorKey] doubleValue];
2785     CGFloat newBackingScaleFactor = [self _intrinsicDeviceScaleFactor]; 
2786     if (oldBackingScaleFactor == newBackingScaleFactor)
2787         return; 
2788
2789     _data->_page->setIntrinsicDeviceScaleFactor(newBackingScaleFactor);
2790 }
2791
2792 - (void)_windowDidChangeOcclusionState:(NSNotification *)notification
2793 {
2794     _data->_page->viewStateDidChange(ViewState::IsVisible);
2795 }
2796
2797 - (void)drawRect:(NSRect)rect
2798 {
2799     LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
2800     _data->_page->endPrinting();
2801 }
2802
2803 - (BOOL)isOpaque
2804 {
2805     return _data->_page->drawsBackground();
2806 }
2807
2808 - (BOOL)mouseDownCanMoveWindow
2809 {
2810     // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent,
2811     // but we don't want a drag in the NSView to move the window, even if it's transparent.
2812     return NO;
2813 }
2814
2815 - (void)viewDidHide
2816 {
2817     _data->_page->viewStateDidChange(ViewState::IsVisible);
2818 }
2819
2820 - (void)viewDidUnhide
2821 {
2822     _data->_page->viewStateDidChange(ViewState::IsVisible);
2823 }
2824
2825 - (void)viewDidChangeBackingProperties
2826 {
2827     NSColorSpace *colorSpace = [[self window] colorSpace];
2828     if ([colorSpace isEqualTo:_data->_colorSpace.get()])
2829         return;
2830
2831     _data->_colorSpace = nullptr;
2832     if (DrawingAreaProxy *drawingArea = _data->_page->drawingArea())
2833         drawingArea->colorSpaceDidChange();
2834 }
2835
2836 - (void)_activeSpaceDidChange:(NSNotification *)notification
2837 {
2838     _data->_page->viewStateDidChange(ViewState::IsVisible);
2839 }
2840
2841 - (void)_dictionaryLookupPopoverWillClose:(NSNotification *)notification
2842 {
2843     [self _setTextIndicator:nil fadeOut:NO];
2844 }
2845
2846 - (void)_accessibilityRegisterUIProcessTokens
2847 {
2848     // Initialize remote accessibility when the window connection has been established.
2849     NSData *remoteElementToken = WKAXRemoteTokenForElement(self);
2850     NSData *remoteWindowToken = WKAXRemoteTokenForElement([self window]);
2851     IPC::DataReference elementToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteElementToken bytes]), [remoteElementToken length]);
2852     IPC::DataReference windowToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteWindowToken bytes]), [remoteWindowToken length]);
2853     _data->_page->registerUIProcessAccessibilityTokens(elementToken, windowToken);
2854 }
2855
2856 - (void)_updateRemoteAccessibilityRegistration:(BOOL)registerProcess
2857 {
2858     // When the tree is connected/disconnected, the remote accessibility registration
2859     // needs to be updated with the pid of the remote process. If the process is going
2860     // away, that information is not present in WebProcess
2861     pid_t pid = 0;
2862     if (registerProcess)
2863         pid = _data->_page->process().processIdentifier();
2864     else if (!registerProcess) {
2865         pid = WKAXRemoteProcessIdentifier(_data->_remoteAccessibilityChild.get());
2866         _data->_remoteAccessibilityChild = nil;
2867     }
2868     if (pid)
2869         WKAXRegisterRemoteProcess(registerProcess, pid); 
2870 }
2871
2872 - (void)enableAccessibilityIfNecessary
2873 {
2874     if (WebCore::AXObjectCache::accessibilityEnabled())
2875         return;
2876
2877     // After enabling accessibility update the window frame on the web process so that the
2878     // correct accessibility position is transmitted (when AX is off, that position is not calculated).
2879     WebCore::AXObjectCache::enableAccessibility();
2880     [self _updateWindowAndViewFrames];
2881 }
2882
2883 - (id)accessibilityFocusedUIElement
2884 {
2885     [self enableAccessibilityIfNecessary];
2886     return _data->_remoteAccessibilityChild.get();
2887 }
2888
2889 - (BOOL)accessibilityIsIgnored
2890 {
2891     return NO;
2892 }
2893
2894 - (id)accessibilityHitTest:(NSPoint)point
2895 {
2896     [self enableAccessibilityIfNecessary];
2897     return _data->_remoteAccessibilityChild.get();
2898 }
2899
2900 - (id)accessibilityAttributeValue:(NSString*)attribute
2901 {
2902     [self enableAccessibilityIfNecessary];
2903
2904     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
2905
2906         id child = nil;
2907         if (_data->_remoteAccessibilityChild)
2908             child = _data->_remoteAccessibilityChild.get();
2909         
2910         if (!child)
2911             return nil;
2912         return [NSArray arrayWithObject:child];
2913     }
2914     if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
2915         return NSAccessibilityGroupRole;
2916     if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
2917         return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil);
2918     if ([attribute isEqualToString:NSAccessibilityParentAttribute])
2919         return NSAccessibilityUnignoredAncestor([self superview]);
2920     if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
2921         return [NSNumber numberWithBool:YES];
2922     
2923     return [super accessibilityAttributeValue:attribute];
2924 }
2925
2926 - (NSView *)hitTest:(NSPoint)point
2927 {
2928     NSView *hitView = [super hitTest:point];
2929     if (hitView && _data && hitView == _data->_layerHostingView)
2930         hitView = self;
2931
2932     return hitView;
2933 }
2934
2935 - (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent
2936 {
2937     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved location:[[flagsChangedEvent window] mouseLocationOutsideOfEventStream]
2938         modifierFlags:[flagsChangedEvent modifierFlags] timestamp:[flagsChangedEvent timestamp] windowNumber:[flagsChangedEvent windowNumber]
2939         context:[flagsChangedEvent context] eventNumber:0 clickCount:0 pressure:0];
2940     NativeWebMouseEvent webEvent(fakeEvent, self);
2941     _data->_page->handleMouseEvent(webEvent);
2942 }
2943
2944 - (NSInteger)conversationIdentifier
2945 {
2946     return (NSInteger)self;
2947 }
2948
2949 - (float)_intrinsicDeviceScaleFactor
2950 {
2951     if (_data->_overrideDeviceScaleFactor)
2952         return _data->_overrideDeviceScaleFactor;
2953     if (_data->_targetWindowForMovePreparation)
2954         return [_data->_targetWindowForMovePreparation backingScaleFactor];
2955     if (NSWindow *window = [self window])
2956         return [window backingScaleFactor];
2957     return [[NSScreen mainScreen] backingScaleFactor];
2958 }
2959
2960 - (void)_setDrawingAreaSize:(NSSize)size
2961 {
2962     if (!_data->_page->drawingArea())
2963         return;
2964     
2965     _data->_page->drawingArea()->setSize(IntSize(size), IntSize(0, 0), IntSize(_data->_resizeScrollOffset));
2966     _data->_resizeScrollOffset = NSZeroSize;
2967 }
2968
2969 - (void)quickLookWithEvent:(NSEvent *)event
2970 {
2971     if (_data->_ignoresNonWheelEvents)
2972         return;
2973
2974 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2975     if (_data->_immediateActionGestureRecognizer) {
2976         [super quickLookWithEvent:event];
2977         return;
2978     }
2979 #endif
2980
2981     NSPoint locationInViewCoordinates = [self convertPoint:[event locationInWindow] fromView:nil];
2982     _data->_page->performDictionaryLookupAtLocation(FloatPoint(locationInViewCoordinates.x, locationInViewCoordinates.y));
2983 }
2984
2985 - (std::unique_ptr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy
2986 {
2987     if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"WebKit2UseRemoteLayerTreeDrawingArea"] boolValue])
2988         return std::make_unique<RemoteLayerTreeDrawingAreaProxy>(*_data->_page);
2989
2990     return std::make_unique<TiledCoreAnimationDrawingAreaProxy>(*_data->_page);
2991 }
2992
2993 - (BOOL)_isFocused
2994 {
2995     if (_data->_inBecomeFirstResponder)
2996         return YES;
2997     if (_data->_inResignFirstResponder)
2998         return NO;
2999     return [[self window] firstResponder] == self;
3000 }
3001
3002 - (WebKit::ColorSpaceData)_colorSpace
3003 {
3004     if (!_data->_colorSpace) {
3005         if (_data->_targetWindowForMovePreparation)
3006             _data->_colorSpace = [_data->_targetWindowForMovePreparation colorSpace];
3007         else if (NSWindow *window = [self window])
3008             _data->_colorSpace = [window colorSpace];
3009         else
3010             _data->_colorSpace = [[NSScreen mainScreen] colorSpace];
3011     }
3012         
3013     ColorSpaceData colorSpaceData;
3014     colorSpaceData.cgColorSpace = [_data->_colorSpace CGColorSpace];
3015
3016     return colorSpaceData;    
3017 }
3018
3019 - (void)_processDidExit
3020 {
3021     [self _notifyInputContextAboutDiscardedComposition];
3022
3023     if (_data->_layerHostingView)
3024         [self _setAcceleratedCompositingModeRootLayer:nil];
3025
3026     [self _updateRemoteAccessibilityRegistration:NO];
3027
3028     _data->_gestureController = nullptr;
3029 }
3030
3031 - (void)_pageClosed
3032 {
3033     [self _updateRemoteAccessibilityRegistration:NO];
3034 }
3035
3036 - (void)_didRelaunchProcess
3037 {
3038     [self _accessibilityRegisterUIProcessTokens];
3039 }
3040
3041 - (void)_preferencesDidChange
3042 {
3043     BOOL needsViewFrameInWindowCoordinates = _data->_page->preferences().pluginsEnabled();
3044
3045     if (!!needsViewFrameInWindowCoordinates == !!_data->_needsViewFrameInWindowCoordinates)
3046         return;
3047
3048     _data->_needsViewFrameInWindowCoordinates = needsViewFrameInWindowCoordinates;
3049     if ([self window])
3050         [self _updateWindowAndViewFrames];
3051 }
3052
3053 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
3054 {
3055     ValidationVector items = _data->_validationMap.take(commandName);
3056     size_t size = items.size();
3057     for (size_t i = 0; i < size; ++i) {
3058         ValidationItem item = items[i].get();
3059         [menuItem(item) setState:newState];
3060         [menuItem(item) setEnabled:isEnabled];
3061         [toolbarItem(item) setEnabled:isEnabled];
3062         // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
3063     }
3064 }
3065
3066 - (BOOL)_tryPostProcessPluginComplexTextInputKeyDown:(NSEvent *)event
3067 {
3068     if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
3069         return NO;
3070
3071     // In the legacy text input model, the event has already been sent to the input method.
3072     if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
3073         return NO;
3074
3075     return [self _handlePluginComplexTextInputKeyDown:event];
3076 }
3077
3078 - (void)_doneWithKeyEvent:(NSEvent *)event eventWasHandled:(BOOL)eventWasHandled
3079 {
3080     if ([event type] != NSKeyDown)
3081         return;
3082
3083     if ([self _tryPostProcessPluginComplexTextInputKeyDown:event])
3084         return;
3085     
3086     if (eventWasHandled) {
3087         [NSCursor setHiddenUntilMouseMoves:YES];
3088         return;
3089     }
3090
3091     // resending the event may destroy this WKView
3092     RetainPtr<WKView> protector(self);
3093
3094     ASSERT(!_data->_keyDownEventBeingResent);
3095     _data->_keyDownEventBeingResent = event;
3096     [NSApp _setCurrentEvent:event];
3097     [NSApp sendEvent:event];
3098
3099     _data->_keyDownEventBeingResent = nullptr;
3100 }
3101
3102 - (NSRect)_convertToDeviceSpace:(NSRect)rect
3103 {
3104     return toDeviceSpace(rect, [self window]);
3105 }
3106
3107 - (NSRect)_convertToUserSpace:(NSRect)rect
3108 {
3109     return toUserSpace(rect, [self window]);
3110 }
3111
3112 // Any non-zero value will do, but using something recognizable might help us debug some day.
3113 #define TRACKING_RECT_TAG 0xBADFACE
3114
3115 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
3116 {
3117     ASSERT(_data->_trackingRectOwner == nil);
3118     _data->_trackingRectOwner = owner;
3119     _data->_trackingRectUserData = data;
3120     return TRACKING_RECT_TAG;
3121 }
3122
3123 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
3124 {
3125     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
3126     ASSERT(_data->_trackingRectOwner == nil);
3127     _data->_trackingRectOwner = owner;
3128     _data->_trackingRectUserData = data;
3129     return TRACKING_RECT_TAG;
3130 }
3131
3132 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
3133 {
3134     ASSERT(count == 1);
3135     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
3136     ASSERT(_data->_trackingRectOwner == nil);
3137     _data->_trackingRectOwner = owner;
3138     _data->_trackingRectUserData = userDataList[0];
3139     trackingNums[0] = TRACKING_RECT_TAG;
3140 }
3141
3142 - (void)removeTrackingRect:(NSTrackingRectTag)tag
3143 {
3144     if (!_data)
3145         return;
3146
3147     if (tag == 0)
3148         return;
3149     
3150     if (tag == TRACKING_RECT_TAG) {
3151         _data->_trackingRectOwner = nil;
3152         return;
3153     }
3154     
3155     if (tag == _data->_lastToolTipTag) {
3156         [super removeTrackingRect:tag];
3157         _data->_lastToolTipTag = 0;
3158         return;
3159     }
3160
3161     // If any other tracking rect is being removed, we don't know how it was created
3162     // and it's possible there's a leak involved (see 3500217)
3163     ASSERT_NOT_REACHED();
3164 }
3165
3166 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
3167 {
3168     int i;
3169     for (i = 0; i < count; ++i) {
3170         int tag = tags[i];
3171         if (tag == 0)
3172             continue;
3173         ASSERT(tag == TRACKING_RECT_TAG);
3174         if (_data != nil) {
3175             _data->_trackingRectOwner = nil;
3176         }
3177     }
3178 }
3179
3180 - (void)_sendToolTipMouseExited
3181 {
3182     // Nothing matters except window, trackingNumber, and userData.
3183     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
3184         location:NSMakePoint(0, 0)
3185         modifierFlags:0
3186         timestamp:0
3187         windowNumber:[[self window] windowNumber]
3188         context:NULL
3189         eventNumber:0
3190         trackingNumber:TRACKING_RECT_TAG
3191         userData:_data->_trackingRectUserData];
3192     [_data->_trackingRectOwner mouseExited:fakeEvent];
3193 }
3194
3195 - (void)_sendToolTipMouseEntered
3196 {
3197     // Nothing matters except window, trackingNumber, and userData.
3198     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
3199         location:NSMakePoint(0, 0)
3200         modifierFlags:0
3201         timestamp:0
3202         windowNumber:[[self window] windowNumber]
3203         context:NULL
3204         eventNumber:0
3205         trackingNumber:TRACKING_RECT_TAG
3206         userData:_data->_trackingRectUserData];
3207     [_data->_trackingRectOwner mouseEntered:fakeEvent];
3208 }
3209
3210 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
3211 {
3212     return nsStringFromWebCoreString(_data->_page->toolTip());
3213 }
3214
3215 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
3216 {
3217     if (oldToolTip)
3218         [self _sendToolTipMouseExited];
3219
3220     if (newToolTip && [newToolTip length] > 0) {
3221         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
3222         [self removeAllToolTips];
3223         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
3224         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
3225         [self _sendToolTipMouseEntered];
3226     }
3227 }
3228
3229 - (void)_setTextIndicator:(PassRefPtr<TextIndicator>)textIndicator fadeOut:(BOOL)fadeOut
3230 {
3231     if (!textIndicator) {
3232         _data->_textIndicatorWindow = nullptr;
3233         return;
3234     }
3235
3236     if (!_data->_textIndicatorWindow)
3237         _data->_textIndicatorWindow = std::make_unique<TextIndicatorWindow>(self);
3238
3239     NSRect textBoundingRectInScreenCoordinates = [self.window convertRectToScreen:[self convertRect:textIndicator->textBoundingRectInRootViewCoordinates() toView:nil]];
3240     _data->_textIndicatorWindow->setTextIndicator(textIndicator, NSRectToCGRect(textBoundingRectInScreenCoordinates), fadeOut);
3241 }
3242
3243 - (void)_setTextIndicatorAnimationProgress:(float)progress
3244 {
3245     if (_data->_textIndicatorWindow)
3246         _data->_textIndicatorWindow->setAnimationProgress(progress);
3247 }
3248
3249 - (CALayer *)_rootLayer
3250 {
3251     return [_data->_layerHostingView layer];
3252 }
3253
3254 - (void)_setAcceleratedCompositingModeRootLayer:(CALayer *)rootLayer
3255 {
3256     [rootLayer web_disableAllActions];
3257
3258     _data->_rootLayer = rootLayer;
3259
3260 #if WK_API_ENABLED
3261     if (_data->_thumbnailView) {
3262         [self _updateThumbnailViewLayer];
3263         return;
3264     }
3265 #endif
3266
3267     [CATransaction begin];
3268     [CATransaction setDisableActions:YES];
3269
3270     if (rootLayer) {
3271         if (!_data->_layerHostingView) {
3272             // Create an NSView that will host our layer tree.
3273             _data->_layerHostingView = adoptNS([[WKFlippedView alloc] initWithFrame:[self bounds]]);
3274             [_data->_layerHostingView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
3275
3276
3277             [self addSubview:_data->_layerHostingView.get() positioned:NSWindowBelow relativeTo:nil];
3278
3279             // Create a root layer that will back the NSView.
3280             RetainPtr<CALayer> layer = adoptNS([[CALayer alloc] init]);
3281             [layer setDelegate:[WebActionDisablingCALayerDelegate shared]];
3282 #ifndef NDEBUG
3283             [layer setName:@"Hosting root layer"];
3284 #endif
3285
3286             [_data->_layerHostingView setLayer:layer.get()];
3287             [_data->_layerHostingView setWantsLayer:YES];
3288         }
3289
3290         [_data->_layerHostingView layer].sublayers = [NSArray arrayWithObject:rootLayer];
3291     } else {
3292         if (_data->_layerHostingView) {
3293             [_data->_layerHostingView removeFromSuperview];
3294             [_data->_layerHostingView setLayer:nil];
3295             [_data->_layerHostingView setWantsLayer:NO];
3296
3297             _data->_layerHostingView = nullptr;
3298         }
3299     }
3300
3301     [CATransaction commit];
3302 }
3303
3304 - (CALayer *)_acceleratedCompositingModeRootLayer
3305 {
3306     return _data->_rootLayer.get();
3307 }
3308
3309 - (PassRefPtr<ViewSnapshot>)_takeViewSnapshot
3310 {
3311     NSWindow *window = self.window;
3312
3313     CGSWindowID windowID = (CGSWindowID)[window windowNumber];
3314     if (!windowID || ![window isVisible])
3315         return nullptr;
3316
3317     RetainPtr<CGImageRef> windowSnapshotImage = adoptCF(CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, windowID, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageShouldBeOpaque));
3318
3319     // Work around <rdar://problem/17084993>; re-request the snapshot at kCGWindowImageNominalResolution if it was captured at the wrong scale.
3320     CGFloat desiredSnapshotWidth = window.frame.size.width * window.screen.backingScaleFactor;
3321     if (CGImageGetWidth(windowSnapshotImage.get()) != desiredSnapshotWidth)
3322         windowSnapshotImage = adoptCF(CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, windowID, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageShouldBeOpaque | kCGWindowImageNominalResolution));
3323
3324     [self _ensureGestureController];
3325
3326     NSRect windowCaptureRect;
3327     FloatRect boundsForCustomSwipeViews = _data->_gestureController->windowRelativeBoundsForCustomSwipeViews();
3328     if (!boundsForCustomSwipeViews.isEmpty())
3329         windowCaptureRect = boundsForCustomSwipeViews;
3330     else {
3331         NSRect unobscuredBounds = self.bounds;
3332         float topContentInset = _data->_page->topContentInset();
3333         unobscuredBounds.origin.y += topContentInset;
3334         unobscuredBounds.size.height -= topContentInset;
3335         windowCaptureRect = [self convertRect:unobscuredBounds toView:nil];
3336     }
3337
3338     NSRect windowCaptureScreenRect = [window convertRectToScreen:windowCaptureRect];
3339     CGRect windowScreenRect;
3340     CGSGetScreenRectForWindow(CGSMainConnectionID(), (CGSWindowID)[window windowNumber], &windowScreenRect);
3341
3342     NSRect croppedImageRect = windowCaptureRect;
3343     croppedImageRect.origin.y = windowScreenRect.size.height - windowCaptureScreenRect.size.height - NSMinY(windowCaptureRect);
3344
3345     auto croppedSnapshotImage = adoptCF(CGImageCreateWithImageInRect(windowSnapshotImage.get(), NSRectToCGRect([window convertRectToBacking:croppedImageRect])));
3346
3347     auto surface = IOSurface::createFromImage(croppedSnapshotImage.get());
3348     if (!surface)
3349         return nullptr;
3350     surface->setIsVolatile(true);
3351
3352     return ViewSnapshot::create(WTF::move(surface));
3353 }
3354
3355 - (void)_wheelEventWasNotHandledByWebCore:(NSEvent *)event
3356 {
3357     if (_data->_gestureController)
3358         _data->_gestureController->wheelEventWasNotHandledByWebCore(event);
3359 }
3360
3361 - (void)_setAccessibilityWebProcessToken:(NSData *)data
3362 {
3363     _data->_remoteAccessibilityChild = WKAXRemoteElementForToken(data);
3364     [self _updateRemoteAccessibilityRegistration:YES];
3365 }
3366
3367 - (void)_pluginFocusOrWindowFocusChanged:(BOOL)pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
3368 {
3369     BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
3370
3371     if (pluginHasFocusAndWindowHasFocus) {
3372         // Check if we're already allowing text input for this plug-in.
3373         if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
3374             return;
3375
3376         _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
3377
3378     } else {
3379         // Check if we got a request to unfocus a plug-in that isn't focused.
3380         if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
3381             return;
3382
3383         _data->_pluginComplexTextInputIdentifier = 0;
3384     }
3385
3386     if (inputSourceChanged) {
3387         // The input source changed, go ahead and discard any entered text.
3388         [[WKTextInputWindowController sharedTextInputWindowController] unmarkText];
3389     }
3390
3391     // This will force the current input context to be updated to its correct value.
3392     [NSApp updateWindows];
3393 }
3394
3395 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
3396 {
3397     if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier) {
3398         // We're asked to update the state for a plug-in that doesn't have focus.
3399         return;
3400     }
3401
3402     [self _setPluginComplexTextInputState:pluginComplexTextInputState];
3403 }
3404
3405 - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag
3406 {
3407     IntSize size([image size]);
3408     size.scale(1.0 / _data->_page->deviceScaleFactor());
3409     [image setSize:size];
3410     
3411     // The call below could release this WKView.
3412     RetainPtr<WKView> protector(self);
3413     
3414 #pragma clang diagnostic push
3415 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3416     [self dragImage:image
3417                  at:clientPoint
3418              offset:NSZeroSize
3419               event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent
3420          pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
3421              source:self
3422           slideBack:YES];
3423 #pragma clang diagnostic pop
3424 }
3425
3426 static bool matchesExtensionOrEquivalent(NSString *filename, NSString *extension)
3427 {
3428     NSString *extensionAsSuffix = [@"." stringByAppendingString:extension];
3429     return hasCaseInsensitiveSuffix(filename, extensionAsSuffix) || (stringIsCaseInsensitiveEqualToString(extension, @"jpeg")
3430                                                                      && hasCaseInsensitiveSuffix(filename, @".jpg"));
3431 }
3432
3433 - (void)_setFileAndURLTypes:(NSString *)filename withExtension:(NSString *)extension withTitle:(NSString *)title withURL:(NSString *)url withVisibleURL:(NSString *)visibleUrl forPasteboard:(NSPasteboard *)pasteboard
3434 {
3435     if (!matchesExtensionOrEquivalent(filename, extension))
3436         filename = [[filename stringByAppendingString:@"."] stringByAppendingString:extension];
3437     
3438     [pasteboard setString:visibleUrl forType:NSStringPboardType];
3439     [pasteboard setString:visibleUrl forType:PasteboardTypes::WebURLPboardType];
3440     [pasteboard setString:title forType:PasteboardTypes::WebURLNamePboardType];
3441     [pasteboard setPropertyList:[NSArray arrayWithObjects:[NSArray arrayWithObject:visibleUrl], [NSArray arrayWithObject:title], nil] forType:PasteboardTypes::WebURLsWithTitlesPboardType];
3442     [pasteboard setPropertyList:[NSArray arrayWithObject:extension] forType:NSFilesPromisePboardType];
3443     _data->_promisedFilename = filename;
3444     _data->_promisedURL = url;
3445 }
3446
3447 - (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
3448
3449 {
3450     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName];
3451     RetainPtr<NSMutableArray> types = adoptNS([[NSMutableArray alloc] initWithObjects:NSFilesPromisePboardType, nil]);
3452     
3453     [types addObjectsFromArray:archiveBuffer ? PasteboardTypes::forImagesWithArchive() : PasteboardTypes::forImages()];
3454     [pasteboard declareTypes:types.get() owner:self];
3455     [self _setFileAndURLTypes:filename withExtension:extension withTitle:title withURL:url withVisibleURL:visibleUrl forPasteboard:pasteboard];
3456
3457     if (archiveBuffer)
3458         [pasteboard setData:archiveBuffer->createNSData().get() forType:PasteboardTypes::WebArchivePboardType];
3459
3460     _data->_promisedImage = image;
3461 }
3462
3463 #if ENABLE(ATTACHMENT_ELEMENT)
3464 - (void)_setPromisedDataForAttachment:(NSString *)filename withExtension:(NSString *)extension withTitle:(NSString *)title withURL:(NSString *)url withVisibleURL:(NSString *)visibleUrl forPasteboard:(NSString *)pasteboardName
3465
3466 {
3467     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName];
3468     RetainPtr<NSMutableArray> types = adoptNS([[NSMutableArray alloc] initWithObjects:NSFilesPromisePboardType, nil]);
3469     [types addObjectsFromArray:PasteboardTypes::forURL()];
3470     [pasteboard declareTypes:types.get() owner:self];
3471     [self _setFileAndURLTypes:filename withExtension:extension withTitle:title withURL:url withVisibleURL:visibleUrl forPasteboard:pasteboard];
3472
3473     RetainPtr<NSMutableArray> paths = adoptNS([[NSMutableArray alloc] init]);
3474     [paths addObject:title];
3475     [pasteboard setPropertyList:paths.get() forType:NSFilenamesPboardType];
3476
3477     _data->_promisedImage = nullptr;
3478 }
3479 #endif
3480
3481 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
3482 {