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