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