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