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