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