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