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