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