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