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