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