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