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