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