ff08d1fbf3a53a77c8cfb9435af81528dc3e61aa
[WebKit-https.git] / Source / WebKit2 / UIProcess / API / mac / WKView.mm
1 /*
2  * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "WKView.h"
28
29 #if PLATFORM(MAC)
30
31 #if USE(DICTATION_ALTERNATIVES)
32 #import <AppKit/NSTextAlternatives.h>
33 #import <AppKit/NSAttributedString.h>
34 #endif
35
36 #import "APILegacyContextHistoryClient.h"
37 #import "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 "WebEventFactory.h"
70 #import "WebKit2Initialize.h"
71 #import "WebPage.h"
72 #import "WebPageGroup.h"
73 #import "WebPageProxy.h"
74 #import "WebPreferences.h"
75 #import "WebProcessPool.h"
76 #import "WebProcessProxy.h"
77 #import "WebSystemInterface.h"
78 #import "_WKThumbnailViewInternal.h"
79 #import <QuartzCore/QuartzCore.h>
80 #import <WebCore/AXObjectCache.h>
81 #import <WebCore/ColorMac.h>
82 #import <WebCore/DataDetectorsSPI.h>
83 #import <WebCore/DragController.h>
84 #import <WebCore/DragData.h>
85 #import <WebCore/FloatRect.h>
86 #import <WebCore/Image.h>
87 #import <WebCore/IntRect.h>
88 #import <WebCore/FileSystem.h>
89 #import <WebCore/KeyboardEvent.h>
90 #import <WebCore/LocalizedStrings.h>
91 #import <WebCore/LookupSPI.h>
92 #import <WebCore/NSImmediateActionGestureRecognizerSPI.h>
93 #import <WebCore/NSViewSPI.h>
94 #import <WebCore/PlatformEventFactoryMac.h>
95 #import <WebCore/PlatformScreen.h>
96 #import <WebCore/Region.h>
97 #import <WebCore/SharedBuffer.h>
98 #import <WebCore/SoftLinking.h>
99 #import <WebCore/TextAlternativeWithRange.h>
100 #import <WebCore/TextIndicator.h>
101 #import <WebCore/TextIndicatorWindow.h>
102 #import <WebCore/TextUndoInsertionMarkupMac.h>
103 #import <WebCore/WebActionDisablingCALayerDelegate.h>
104 #import <WebCore/WebCoreCALayerExtras.h>
105 #import <WebCore/WebCoreFullScreenPlaceholderView.h>
106 #import <WebCore/WebCoreFullScreenWindow.h>
107 #import <WebCore/WebCoreNSStringExtras.h>
108 #import <WebKitSystemInterface.h>
109 #import <sys/stat.h>
110 #import <wtf/RefPtr.h>
111 #import <wtf/RetainPtr.h>
112 #import <wtf/RunLoop.h>
113
114 /* API internals. */
115 #import "WKBrowsingContextControllerInternal.h"
116 #import "WKBrowsingContextGroupPrivate.h"
117 #import "WKProcessGroupPrivate.h"
118
119 @interface NSApplication (WKNSApplicationDetails)
120 - (void)speakString:(NSString *)string;
121 - (void)_setCurrentEvent:(NSEvent *)event;
122 @end
123
124 @interface NSWindow (WKNSWindowDetails)
125 - (NSRect)_intersectBottomCornersWithRect:(NSRect)viewRect;
126 - (void)_maskRoundedBottomCorners:(NSRect)clipRect;
127 @end
128
129 #if USE(ASYNC_NSTEXTINPUTCLIENT)
130 @interface NSTextInputContext (WKNSTextInputContextDetails)
131 - (void)handleEvent:(NSEvent *)theEvent completionHandler:(void(^)(BOOL handled))completionHandler;
132 - (void)handleEventByInputMethod:(NSEvent *)theEvent completionHandler:(void(^)(BOOL handled))completionHandler;
133 - (BOOL)handleEventByKeyboardLayout:(NSEvent *)theEvent;
134 @end
135 #endif
136
137 #if defined(__has_include) && __has_include(<CoreGraphics/CoreGraphicsPrivate.h>)
138 #import <CoreGraphics/CoreGraphicsPrivate.h>
139 #endif
140
141 extern "C" {
142 typedef uint32_t CGSConnectionID;
143 typedef uint32_t CGSWindowID;
144 CGSConnectionID CGSMainConnectionID(void);
145 CGError CGSGetScreenRectForWindow(CGSConnectionID cid, CGSWindowID wid, CGRect *rect);
146 };
147
148 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUNotificationPopoverWillClose, NSString *)
149
150 using namespace WebKit;
151 using namespace WebCore;
152
153 namespace WebKit {
154
155 typedef id <NSValidatedUserInterfaceItem> ValidationItem;
156 typedef Vector<RetainPtr<ValidationItem>> ValidationVector;
157 typedef HashMap<String, ValidationVector> ValidationMap;
158
159 }
160
161 #if !USE(ASYNC_NSTEXTINPUTCLIENT)
162 struct WKViewInterpretKeyEventsParameters {
163     bool eventInterpretationHadSideEffects;
164     bool consumedByIM;
165     bool executingSavedKeypressCommands;
166     Vector<KeypressCommand>* commands;
167 };
168 #endif
169
170 @interface WKViewData : NSObject {
171 @public
172     std::unique_ptr<PageClientImpl> _pageClient;
173     RefPtr<WebPageProxy> _page;
174
175 #if WK_API_ENABLED
176     RetainPtr<WKBrowsingContextController> _browsingContextController;
177 #endif
178
179     RetainPtr<NSTrackingArea> _primaryTrackingArea;
180
181     // For ToolTips.
182     NSToolTipTag _lastToolTipTag;
183     id _trackingRectOwner;
184     void* _trackingRectUserData;
185
186     RetainPtr<NSView> _layerHostingView;
187
188     RetainPtr<id> _remoteAccessibilityChild;
189     
190     // For asynchronous validation.
191     ValidationMap _validationMap;
192
193     std::unique_ptr<TextIndicatorWindow> _textIndicatorWindow;
194
195     // We keep here the event when resending it to
196     // the application to distinguish the case of a new event from one 
197     // that has been already sent to WebCore.
198     RetainPtr<NSEvent> _keyDownEventBeingResent;
199 #if USE(ASYNC_NSTEXTINPUTCLIENT)
200     Vector<KeypressCommand>* _collectedKeypressCommands;
201 #else
202     WKViewInterpretKeyEventsParameters* _interpretKeyEventsParameters;
203 #endif
204
205     NSSize _resizeScrollOffset;
206
207     // The identifier of the plug-in we want to send complex text input to, or 0 if there is none.
208     uint64_t _pluginComplexTextInputIdentifier;
209
210     // The state of complex text input for the plug-in.
211     PluginComplexTextInputState _pluginComplexTextInputState;
212
213     bool _inBecomeFirstResponder;
214     bool _inResignFirstResponder;
215     NSEvent *_mouseDownEvent;
216     BOOL _ignoringMouseDraggedEvents;
217
218     id _flagsChangedEventMonitor;
219
220 #if ENABLE(FULLSCREEN_API)
221     RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
222 #endif
223
224     BOOL _hasSpellCheckerDocumentTag;
225     NSInteger _spellCheckerDocumentTag;
226
227     BOOL _inSecureInputState;
228
229     NSRect _windowBottomCornerIntersectionRect;
230     
231     unsigned _frameSizeUpdatesDisabledCount;
232     BOOL _shouldDeferViewInWindowChanges;
233     NSWindow *_targetWindowForMovePreparation;
234
235     BOOL _viewInWindowChangeWasDeferred;
236
237     BOOL _needsViewFrameInWindowCoordinates;
238     BOOL _didScheduleWindowAndViewFrameUpdate;
239
240     RetainPtr<NSColorSpace> _colorSpace;
241
242     RefPtr<WebCore::Image> _promisedImage;
243     String _promisedFilename;
244     String _promisedURL;
245     
246     NSSize _intrinsicContentSize;
247     BOOL _clipsToVisibleRect;
248     NSRect _contentPreparationRect;
249     BOOL _useContentPreparationRectForVisibleRect;
250     BOOL _windowOcclusionDetectionEnabled;
251
252     std::unique_ptr<ViewGestureController> _gestureController;
253     BOOL _allowsMagnification;
254     BOOL _ignoresNonWheelEvents;
255     BOOL _ignoresAllEvents;
256     BOOL _allowsBackForwardNavigationGestures;
257
258     RetainPtr<CALayer> _rootLayer;
259
260     BOOL _didScheduleSetTopContentInset;
261     CGFloat _topContentInset;
262     CGFloat _totalHeightOfBanners;
263
264 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
265     BOOL _automaticallyAdjustsContentInsets;
266     RetainPtr<WKActionMenuController> _actionMenuController;
267     RetainPtr<WKImmediateActionController> _immediateActionController;
268     RetainPtr<NSImmediateActionGestureRecognizer> _immediateActionGestureRecognizer;
269 #endif
270
271 #if WK_API_ENABLED
272     _WKThumbnailView *_thumbnailView;
273 #endif
274 }
275
276 @end
277
278 @implementation WKViewData
279 @end
280
281 @interface WKResponderChainSink : NSResponder {
282     NSResponder *_lastResponderInChain;
283     bool _didReceiveUnhandledCommand;
284 }
285 - (id)initWithResponderChain:(NSResponder *)chain;
286 - (void)detach;
287 - (bool)didReceiveUnhandledCommand;
288 @end
289
290 @interface WKFlippedView : NSView
291 @end
292
293 @implementation WKFlippedView
294
295 - (BOOL)isFlipped
296 {
297     return YES;
298 }
299
300 @end
301
302 @implementation WKView
303
304 #if WK_API_ENABLED
305
306 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup
307 {
308     return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:nil];
309 }
310
311 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup relatedToView:(WKView *)relatedView
312 {
313     return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:relatedView ? toAPI(relatedView->_data->_page.get()) : nil];
314 }
315
316 #endif // WK_API_ENABLED
317
318 - (void)dealloc
319 {
320 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
321     [_data->_actionMenuController willDestroyView:self];
322     [_data->_immediateActionController willDestroyView:self];
323 #endif
324
325     _data->_page->close();
326
327 #if WK_API_ENABLED
328     ASSERT(!_data->_thumbnailView);
329 #endif
330     ASSERT(!_data->_inSecureInputState);
331
332     [_data release];
333     _data = nil;
334
335     NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
336     [workspaceNotificationCenter removeObserver:self name:NSWorkspaceActiveSpaceDidChangeNotification object:nil];
337
338     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillTerminateNotification object:NSApp];
339
340     if (canLoadLUNotificationPopoverWillClose())
341         [[NSNotificationCenter defaultCenter] removeObserver:self name:getLUNotificationPopoverWillClose() object:nil];
342
343     WebProcessPool::statistics().wkViewCount--;
344
345     [super dealloc];
346 }
347
348 #if WK_API_ENABLED
349
350 - (WKBrowsingContextController *)browsingContextController
351 {
352     if (!_data->_browsingContextController)
353         _data->_browsingContextController = adoptNS([[WKBrowsingContextController alloc] _initWithPageRef:toAPI(_data->_page.get())]);
354
355     return _data->_browsingContextController.get();
356 }
357
358 #endif // WK_API_ENABLED
359
360 - (void)setDrawsBackground:(BOOL)drawsBackground
361 {
362     _data->_page->setDrawsBackground(drawsBackground);
363 }
364
365 - (BOOL)drawsBackground
366 {
367     return _data->_page->drawsBackground();
368 }
369
370 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
371 {
372     _data->_page->setDrawsTransparentBackground(drawsTransparentBackground);
373 }
374
375 - (BOOL)drawsTransparentBackground
376 {
377     return _data->_page->drawsTransparentBackground();
378 }
379
380 - (BOOL)acceptsFirstResponder
381 {
382     return YES;
383 }
384
385 - (BOOL)becomeFirstResponder
386 {
387     NSSelectionDirection direction = [[self window] keyViewSelectionDirection];
388
389     _data->_inBecomeFirstResponder = true;
390     
391     [self _updateSecureInputState];
392     _data->_page->viewStateDidChange(ViewState::IsFocused);
393
394     _data->_inBecomeFirstResponder = false;
395     
396     if (direction != NSDirectSelection) {
397         NSEvent *event = [NSApp currentEvent];
398         NSEvent *keyboardEvent = nil;
399         if ([event type] == NSKeyDown || [event type] == NSKeyUp)
400             keyboardEvent = event;
401         _data->_page->setInitialFocus(direction == NSSelectingNext, keyboardEvent != nil, NativeWebKeyboardEvent(keyboardEvent, false, Vector<KeypressCommand>()));
402     }
403     return YES;
404 }
405
406 - (BOOL)resignFirstResponder
407 {
408     _data->_inResignFirstResponder = true;
409
410 #if USE(ASYNC_NSTEXTINPUTCLIENT)
411     _data->_page->confirmCompositionAsync();
412 #else
413     if (_data->_page->editorState().hasComposition && !_data->_page->editorState().shouldIgnoreCompositionSelectionChange)
414         _data->_page->cancelComposition();
415 #endif
416
417     [self _notifyInputContextAboutDiscardedComposition];
418
419     [self _resetSecureInputState];
420
421     if (!_data->_page->maintainsInactiveSelection())
422         _data->_page->clearSelection();
423     
424     _data->_page->viewStateDidChange(ViewState::IsFocused);
425
426     _data->_inResignFirstResponder = false;
427
428     return YES;
429 }
430
431 - (void)viewWillStartLiveResize
432 {
433     _data->_page->viewWillStartLiveResize();
434 }
435
436 - (void)viewDidEndLiveResize
437 {
438     _data->_page->viewWillEndLiveResize();
439 }
440
441 - (BOOL)isFlipped
442 {
443     return YES;
444 }
445
446 - (NSSize)intrinsicContentSize
447 {
448     return _data->_intrinsicContentSize;
449 }
450
451 - (void)prepareContentInRect:(NSRect)rect
452 {
453     _data->_contentPreparationRect = rect;
454     _data->_useContentPreparationRectForVisibleRect = YES;
455
456     [self _updateViewExposedRect];
457 }
458
459 - (void)_updateViewExposedRect
460 {
461     NSRect exposedRect = [self visibleRect];
462
463     if (_data->_useContentPreparationRectForVisibleRect)
464         exposedRect = NSUnionRect(_data->_contentPreparationRect, exposedRect);
465
466     if (auto drawingArea = _data->_page->drawingArea())
467         drawingArea->setExposedRect(_data->_clipsToVisibleRect ? FloatRect(exposedRect) : FloatRect::infiniteRect());
468 }
469
470 - (void)setFrameSize:(NSSize)size
471 {
472     [super setFrameSize:size];
473
474     if (![self frameSizeUpdatesDisabled]) {
475         if (_data->_clipsToVisibleRect)
476             [self _updateViewExposedRect];
477         [self _setDrawingAreaSize:size];
478     }
479 }
480
481 - (void)_updateWindowAndViewFrames
482 {
483     if (_data->_clipsToVisibleRect)
484         [self _updateViewExposedRect];
485
486     if (_data->_didScheduleWindowAndViewFrameUpdate)
487         return;
488
489     _data->_didScheduleWindowAndViewFrameUpdate = YES;
490
491     dispatch_async(dispatch_get_main_queue(), ^{
492         _data->_didScheduleWindowAndViewFrameUpdate = NO;
493
494         NSRect viewFrameInWindowCoordinates = NSZeroRect;
495         NSPoint accessibilityPosition = NSZeroPoint;
496
497         if (_data->_needsViewFrameInWindowCoordinates)
498             viewFrameInWindowCoordinates = [self convertRect:self.frame toView:nil];
499
500 #pragma clang diagnostic push
501 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
502         if (WebCore::AXObjectCache::accessibilityEnabled())
503             accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue];
504 #pragma clang diagnostic pop
505
506         _data->_page->windowAndViewFramesChanged(viewFrameInWindowCoordinates, accessibilityPosition);
507     });
508 }
509
510 - (void)renewGState
511 {
512     // Hide the find indicator.
513     _data->_textIndicatorWindow = nullptr;
514
515     // Update the view frame.
516     if ([self window])
517         [self _updateWindowAndViewFrames];
518
519 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
520     [self _updateContentInsetsIfAutomatic];
521 #endif
522
523     [super renewGState];
524 }
525
526 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState
527 {
528     _data->_pluginComplexTextInputState = pluginComplexTextInputState;
529     
530     if (_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled)
531         return;
532
533     // Send back an empty string to the plug-in. This will disable text input.
534     _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, String());
535 }
536
537 typedef HashMap<SEL, String> SelectorNameMap;
538
539 // Map selectors into Editor command names.
540 // This is not needed for any selectors that have the same name as the Editor command.
541 static const SelectorNameMap* createSelectorExceptionMap()
542 {
543     SelectorNameMap* map = new HashMap<SEL, String>;
544     
545     map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
546     map->add(@selector(insertParagraphSeparator:), "InsertNewline");
547     map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
548     map->add(@selector(pageDown:), "MovePageDown");
549     map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
550     map->add(@selector(pageUp:), "MovePageUp");
551     map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
552     map->add(@selector(scrollPageDown:), "ScrollPageForward");
553     map->add(@selector(scrollPageUp:), "ScrollPageBackward");
554     
555     return map;
556 }
557
558 static String commandNameForSelector(SEL selector)
559 {
560     // Check the exception map first.
561     static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
562     SelectorNameMap::const_iterator it = exceptionMap->find(selector);
563     if (it != exceptionMap->end())
564         return it->value;
565     
566     // Remove the trailing colon.
567     // No need to capitalize the command name since Editor command names are
568     // not case sensitive.
569     const char* selectorName = sel_getName(selector);
570     size_t selectorNameLength = strlen(selectorName);
571     if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
572         return String();
573     return String(selectorName, selectorNameLength - 1);
574 }
575
576 // Editing commands
577
578 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
579
580 WEBCORE_COMMAND(alignCenter)
581 WEBCORE_COMMAND(alignJustified)
582 WEBCORE_COMMAND(alignLeft)
583 WEBCORE_COMMAND(alignRight)
584 WEBCORE_COMMAND(copy)
585 WEBCORE_COMMAND(cut)
586 WEBCORE_COMMAND(delete)
587 WEBCORE_COMMAND(deleteBackward)
588 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
589 WEBCORE_COMMAND(deleteForward)
590 WEBCORE_COMMAND(deleteToBeginningOfLine)
591 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
592 WEBCORE_COMMAND(deleteToEndOfLine)
593 WEBCORE_COMMAND(deleteToEndOfParagraph)
594 WEBCORE_COMMAND(deleteToMark)
595 WEBCORE_COMMAND(deleteWordBackward)
596 WEBCORE_COMMAND(deleteWordForward)
597 WEBCORE_COMMAND(ignoreSpelling)
598 WEBCORE_COMMAND(indent)
599 WEBCORE_COMMAND(insertBacktab)
600 WEBCORE_COMMAND(insertLineBreak)
601 WEBCORE_COMMAND(insertNewline)
602 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
603 WEBCORE_COMMAND(insertParagraphSeparator)
604 WEBCORE_COMMAND(insertTab)
605 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
606 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
607 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
608 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
609 WEBCORE_COMMAND(moveBackward)
610 WEBCORE_COMMAND(moveBackwardAndModifySelection)
611 WEBCORE_COMMAND(moveDown)
612 WEBCORE_COMMAND(moveDownAndModifySelection)
613 WEBCORE_COMMAND(moveForward)
614 WEBCORE_COMMAND(moveForwardAndModifySelection)
615 WEBCORE_COMMAND(moveLeft)
616 WEBCORE_COMMAND(moveLeftAndModifySelection)
617 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
618 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
619 WEBCORE_COMMAND(moveRight)
620 WEBCORE_COMMAND(moveRightAndModifySelection)
621 WEBCORE_COMMAND(moveToBeginningOfDocument)
622 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
623 WEBCORE_COMMAND(moveToBeginningOfLine)
624 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
625 WEBCORE_COMMAND(moveToBeginningOfParagraph)
626 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
627 WEBCORE_COMMAND(moveToBeginningOfSentence)
628 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
629 WEBCORE_COMMAND(moveToEndOfDocument)
630 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
631 WEBCORE_COMMAND(moveToEndOfLine)
632 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
633 WEBCORE_COMMAND(moveToEndOfParagraph)
634 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
635 WEBCORE_COMMAND(moveToEndOfSentence)
636 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
637 WEBCORE_COMMAND(moveToLeftEndOfLine)
638 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
639 WEBCORE_COMMAND(moveToRightEndOfLine)
640 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
641 WEBCORE_COMMAND(moveUp)
642 WEBCORE_COMMAND(moveUpAndModifySelection)
643 WEBCORE_COMMAND(moveWordBackward)
644 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
645 WEBCORE_COMMAND(moveWordForward)
646 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
647 WEBCORE_COMMAND(moveWordLeft)
648 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
649 WEBCORE_COMMAND(moveWordRight)
650 WEBCORE_COMMAND(moveWordRightAndModifySelection)
651 WEBCORE_COMMAND(outdent)
652 WEBCORE_COMMAND(pageDown)
653 WEBCORE_COMMAND(pageDownAndModifySelection)
654 WEBCORE_COMMAND(pageUp)
655 WEBCORE_COMMAND(pageUpAndModifySelection)
656 WEBCORE_COMMAND(paste)
657 WEBCORE_COMMAND(pasteAsPlainText)
658 WEBCORE_COMMAND(scrollPageDown)
659 WEBCORE_COMMAND(scrollPageUp)
660 WEBCORE_COMMAND(scrollLineDown)
661 WEBCORE_COMMAND(scrollLineUp)
662 WEBCORE_COMMAND(scrollToBeginningOfDocument)
663 WEBCORE_COMMAND(scrollToEndOfDocument)
664 WEBCORE_COMMAND(selectAll)
665 WEBCORE_COMMAND(selectLine)
666 WEBCORE_COMMAND(selectParagraph)
667 WEBCORE_COMMAND(selectSentence)
668 WEBCORE_COMMAND(selectToMark)
669 WEBCORE_COMMAND(selectWord)
670 WEBCORE_COMMAND(setMark)
671 WEBCORE_COMMAND(subscript)
672 WEBCORE_COMMAND(superscript)
673 WEBCORE_COMMAND(swapWithMark)
674 WEBCORE_COMMAND(takeFindStringFromSelection)
675 WEBCORE_COMMAND(transpose)
676 WEBCORE_COMMAND(underline)
677 WEBCORE_COMMAND(unscript)
678 WEBCORE_COMMAND(yank)
679 WEBCORE_COMMAND(yankAndSelect)
680
681 #undef WEBCORE_COMMAND
682
683 // This method is needed to support Mac OS X services.
684
685 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
686 {
687     size_t numTypes = [types count];
688     [pasteboard declareTypes:types owner:nil];
689     for (size_t i = 0; i < numTypes; ++i) {
690         if ([[types objectAtIndex:i] isEqualTo:NSStringPboardType])
691             [pasteboard setString:_data->_page->stringSelectionForPasteboard() forType:NSStringPboardType];
692         else {
693             RefPtr<SharedBuffer> buffer = _data->_page->dataSelectionForPasteboard([types objectAtIndex:i]);
694             [pasteboard setData:buffer ? buffer->createNSData().get() : nil forType:[types objectAtIndex:i]];
695        }
696     }
697     return YES;
698 }
699
700 - (void)centerSelectionInVisibleArea:(id)sender 
701
702     _data->_page->centerSelectionInVisibleArea();
703 }
704
705 // This method is needed to support Mac OS X services.
706
707 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
708 {
709     EditorState editorState = _data->_page->editorState();
710     BOOL isValidSendType = NO;
711
712     if (sendType && !editorState.selectionIsNone) {
713         if (editorState.isInPlugin)
714             isValidSendType = [sendType isEqualToString:NSStringPboardType];
715         else
716             isValidSendType = [PasteboardTypes::forSelection() containsObject:sendType];
717     }
718
719     BOOL isValidReturnType = NO;
720     if (!returnType)
721         isValidReturnType = YES;
722     else if ([PasteboardTypes::forEditing() containsObject:returnType] && editorState.isContentEditable) {
723         // We can insert strings in any editable context.  We can insert other types, like images, only in rich edit contexts.
724         isValidReturnType = editorState.isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType];
725     }
726     if (isValidSendType && isValidReturnType)
727         return self;
728     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
729 }
730
731 // This method is needed to support Mac OS X services.
732
733 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard 
734 {
735     return _data->_page->readSelectionFromPasteboard([pasteboard name]);
736 }
737
738 /*
739
740 When possible, editing-related methods should be implemented in WebCore with the
741 EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing
742 individual methods here with Mac-specific code.
743
744 Editing-related methods still unimplemented that are implemented in WebKit1:
745
746 - (void)capitalizeWord:(id)sender;
747 - (void)changeFont:(id)sender;
748 - (void)complete:(id)sender;
749 - (void)copyFont:(id)sender;
750 - (void)lowercaseWord:(id)sender;
751 - (void)makeBaseWritingDirectionLeftToRight:(id)sender;
752 - (void)makeBaseWritingDirectionNatural:(id)sender;
753 - (void)makeBaseWritingDirectionRightToLeft:(id)sender;
754 - (void)pasteFont:(id)sender;
755 - (void)scrollLineDown:(id)sender;
756 - (void)scrollLineUp:(id)sender;
757 - (void)showGuessPanel:(id)sender;
758 - (void)uppercaseWord:(id)sender;
759
760 Some other editing-related methods still unimplemented:
761
762 - (void)changeCaseOfLetter:(id)sender;
763 - (void)copyRuler:(id)sender;
764 - (void)insertContainerBreak:(id)sender;
765 - (void)insertDoubleQuoteIgnoringSubstitution:(id)sender;
766 - (void)insertSingleQuoteIgnoringSubstitution:(id)sender;
767 - (void)pasteRuler:(id)sender;
768 - (void)toggleRuler:(id)sender;
769 - (void)transposeWords:(id)sender;
770
771 */
772
773 // Menu items validation
774
775 static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item)
776 {
777     if (![(NSObject *)item isKindOfClass:[NSMenuItem class]])
778         return nil;
779     return (NSMenuItem *)item;
780 }
781
782 static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item)
783 {
784     if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]])
785         return nil;
786     return (NSToolbarItem *)item;
787 }
788
789 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
790 {
791     SEL action = [item action];
792
793     if (action == @selector(showGuessPanel:)) {
794         if (NSMenuItem *menuItem = ::menuItem(item))
795             [menuItem setTitle:contextMenuItemTagShowSpellingPanel(![[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible])];
796         return _data->_page->editorState().isContentEditable;
797     }
798
799     if (action == @selector(checkSpelling:) || action == @selector(changeSpelling:))
800         return _data->_page->editorState().isContentEditable;
801
802     if (action == @selector(toggleContinuousSpellChecking:)) {
803         bool enabled = TextChecker::isContinuousSpellCheckingAllowed();
804         bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled;
805         [menuItem(item) setState:checked ? NSOnState : NSOffState];
806         return enabled;
807     }
808
809     if (action == @selector(toggleGrammarChecking:)) {
810         bool checked = TextChecker::state().isGrammarCheckingEnabled;
811         [menuItem(item) setState:checked ? NSOnState : NSOffState];
812         return YES;
813     }
814
815     if (action == @selector(toggleAutomaticSpellingCorrection:)) {
816         bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled;
817         [menuItem(item) setState:checked ? NSOnState : NSOffState];
818         return _data->_page->editorState().isContentEditable;
819     }
820
821     if (action == @selector(orderFrontSubstitutionsPanel:)) {
822         if (NSMenuItem *menuItem = ::menuItem(item))
823             [menuItem setTitle:contextMenuItemTagShowSubstitutions(![[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible])];
824         return _data->_page->editorState().isContentEditable;
825     }
826
827     if (action == @selector(toggleSmartInsertDelete:)) {
828         bool checked = _data->_page->isSmartInsertDeleteEnabled();
829         [menuItem(item) setState:checked ? NSOnState : NSOffState];
830         return _data->_page->editorState().isContentEditable;
831     }
832
833     if (action == @selector(toggleAutomaticQuoteSubstitution:)) {
834         bool checked = TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
835         [menuItem(item) setState:checked ? NSOnState : NSOffState];
836         return _data->_page->editorState().isContentEditable;
837     }
838
839     if (action == @selector(toggleAutomaticDashSubstitution:)) {
840         bool checked = TextChecker::state().isAutomaticDashSubstitutionEnabled;
841         [menuItem(item) setState:checked ? NSOnState : NSOffState];
842         return _data->_page->editorState().isContentEditable;
843     }
844
845     if (action == @selector(toggleAutomaticLinkDetection:)) {
846         bool checked = TextChecker::state().isAutomaticLinkDetectionEnabled;
847         [menuItem(item) setState:checked ? NSOnState : NSOffState];
848         return _data->_page->editorState().isContentEditable;
849     }
850
851     if (action == @selector(toggleAutomaticTextReplacement:)) {
852         bool checked = TextChecker::state().isAutomaticTextReplacementEnabled;
853         [menuItem(item) setState:checked ? NSOnState : NSOffState];
854         return _data->_page->editorState().isContentEditable;
855     }
856
857     if (action == @selector(uppercaseWord:) || action == @selector(lowercaseWord:) || action == @selector(capitalizeWord:))
858         return _data->_page->editorState().selectionIsRange && _data->_page->editorState().isContentEditable;
859     
860     if (action == @selector(stopSpeaking:))
861         return [NSApp isSpeaking];
862     
863     // The centerSelectionInVisibleArea: selector is enabled if there's a selection range or if there's an insertion point in an editable area.
864     if (action == @selector(centerSelectionInVisibleArea:))
865         return _data->_page->editorState().selectionIsRange || (_data->_page->editorState().isContentEditable && !_data->_page->editorState().selectionIsNone);
866
867     // Next, handle editor commands. Start by returning YES for anything that is not an editor command.
868     // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized.
869     String commandName = commandNameForSelector([item action]);
870     if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName))
871         return YES;
872
873     // Add this item to the vector of items for a given command that are awaiting validation.
874     ValidationMap::AddResult addResult = _data->_validationMap.add(commandName, ValidationVector());
875     addResult.iterator->value.append(item);
876     if (addResult.isNewEntry) {
877         // If we are not already awaiting validation for this command, start the asynchronous validation process.
878         // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
879         // we asked for the same command; there is no guarantee the answer is still valid.
880         _data->_page->validateCommand(commandName, [self](const String& commandName, bool isEnabled, int32_t state, CallbackBase::Error error) {
881             // If the process exits before the command can be validated, we'll be called back with an error.
882             if (error != CallbackBase::Error::None)
883                 return;
884             
885             [self _setUserInterfaceItemState:commandName enabled:isEnabled state:state];
886         });
887     }
888
889     // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called.
890     // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment.
891     // But returning NO here would be worse; that would make keyboard commands such as command-C fail.
892     return YES;
893 }
894
895 - (IBAction)startSpeaking:(id)sender
896 {
897     _data->_page->getSelectionOrContentsAsString([self](const String& string, CallbackBase::Error error) {
898         if (error != CallbackBase::Error::None)
899             return;
900         if (!string)
901             return;
902
903         [NSApp speakString:string];
904     });
905 }
906
907 - (IBAction)stopSpeaking:(id)sender
908 {
909     [NSApp stopSpeaking:sender];
910 }
911
912 - (IBAction)showGuessPanel:(id)sender
913 {
914     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
915     if (!checker) {
916         LOG_ERROR("No NSSpellChecker");
917         return;
918     }
919     
920     NSPanel *spellingPanel = [checker spellingPanel];
921     if ([spellingPanel isVisible]) {
922         [spellingPanel orderOut:sender];
923         return;
924     }
925     
926     _data->_page->advanceToNextMisspelling(true);
927     [spellingPanel orderFront:sender];
928 }
929
930 - (IBAction)checkSpelling:(id)sender
931 {
932     _data->_page->advanceToNextMisspelling(false);
933 }
934
935 - (void)changeSpelling:(id)sender
936 {
937     NSString *word = [[sender selectedCell] stringValue];
938
939     _data->_page->changeSpellingToWord(word);
940 }
941
942 - (IBAction)toggleContinuousSpellChecking:(id)sender
943 {
944     bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled;
945     TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled);
946
947     _data->_page->process().updateTextCheckerState();
948 }
949
950 - (BOOL)isGrammarCheckingEnabled
951 {
952     return TextChecker::state().isGrammarCheckingEnabled;
953 }
954
955 - (void)setGrammarCheckingEnabled:(BOOL)flag
956 {
957     if (static_cast<bool>(flag) == TextChecker::state().isGrammarCheckingEnabled)
958         return;
959     
960     TextChecker::setGrammarCheckingEnabled(flag);
961     _data->_page->process().updateTextCheckerState();
962 }
963
964 - (IBAction)toggleGrammarChecking:(id)sender
965 {
966     bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled;
967     TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled);
968
969     _data->_page->process().updateTextCheckerState();
970 }
971
972 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
973 {
974     TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
975
976     _data->_page->process().updateTextCheckerState();
977 }
978
979 - (void)orderFrontSubstitutionsPanel:(id)sender
980 {
981     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
982     if (!checker) {
983         LOG_ERROR("No NSSpellChecker");
984         return;
985     }
986     
987     NSPanel *substitutionsPanel = [checker substitutionsPanel];
988     if ([substitutionsPanel isVisible]) {
989         [substitutionsPanel orderOut:sender];
990         return;
991     }
992     [substitutionsPanel orderFront:sender];
993 }
994
995 - (IBAction)toggleSmartInsertDelete:(id)sender
996 {
997     _data->_page->setSmartInsertDeleteEnabled(!_data->_page->isSmartInsertDeleteEnabled());
998 }
999
1000 - (BOOL)isAutomaticQuoteSubstitutionEnabled
1001 {
1002     return TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
1003 }
1004
1005 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
1006 {
1007     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticQuoteSubstitutionEnabled)
1008         return;
1009
1010     TextChecker::setAutomaticQuoteSubstitutionEnabled(flag);
1011     _data->_page->process().updateTextCheckerState();
1012 }
1013
1014 - (void)toggleAutomaticQuoteSubstitution:(id)sender
1015 {
1016     TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled);
1017     _data->_page->process().updateTextCheckerState();
1018 }
1019
1020 - (BOOL)isAutomaticDashSubstitutionEnabled
1021 {
1022     return TextChecker::state().isAutomaticDashSubstitutionEnabled;
1023 }
1024
1025 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
1026 {
1027     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticDashSubstitutionEnabled)
1028         return;
1029
1030     TextChecker::setAutomaticDashSubstitutionEnabled(flag);
1031     _data->_page->process().updateTextCheckerState();
1032 }
1033
1034 - (void)toggleAutomaticDashSubstitution:(id)sender
1035 {
1036     TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled);
1037     _data->_page->process().updateTextCheckerState();
1038 }
1039
1040 - (BOOL)isAutomaticLinkDetectionEnabled
1041 {
1042     return TextChecker::state().isAutomaticLinkDetectionEnabled;
1043 }
1044
1045 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
1046 {
1047     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticLinkDetectionEnabled)
1048         return;
1049
1050     TextChecker::setAutomaticLinkDetectionEnabled(flag);
1051     _data->_page->process().updateTextCheckerState();
1052 }
1053
1054 - (void)toggleAutomaticLinkDetection:(id)sender
1055 {
1056     TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled);
1057     _data->_page->process().updateTextCheckerState();
1058 }
1059
1060 - (BOOL)isAutomaticTextReplacementEnabled
1061 {
1062     return TextChecker::state().isAutomaticTextReplacementEnabled;
1063 }
1064
1065 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
1066 {
1067     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticTextReplacementEnabled)
1068         return;
1069
1070     TextChecker::setAutomaticTextReplacementEnabled(flag);
1071     _data->_page->process().updateTextCheckerState();
1072 }
1073
1074 - (void)toggleAutomaticTextReplacement:(id)sender
1075 {
1076     TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled);
1077     _data->_page->process().updateTextCheckerState();
1078 }
1079
1080 - (void)uppercaseWord:(id)sender
1081 {
1082     _data->_page->uppercaseWord();
1083 }
1084
1085 - (void)lowercaseWord:(id)sender
1086 {
1087     _data->_page->lowercaseWord();
1088 }
1089
1090 - (void)capitalizeWord:(id)sender
1091 {
1092     _data->_page->capitalizeWord();
1093 }
1094
1095 - (void)displayIfNeeded
1096 {
1097     // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. In the meantime,
1098     // it is necessary to disable scren updates so we get a chance to redraw the corners before this 
1099     // display is visible.
1100     NSWindow *window = [self window];
1101     BOOL shouldMaskWindow = window && !NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect);
1102     if (shouldMaskWindow)
1103         NSDisableScreenUpdates();
1104
1105     [super displayIfNeeded];
1106
1107     if (shouldMaskWindow) {
1108         [window _maskRoundedBottomCorners:_data->_windowBottomCornerIntersectionRect];
1109         NSEnableScreenUpdates();
1110         _data->_windowBottomCornerIntersectionRect = NSZeroRect;
1111     }
1112 }
1113
1114 // Events
1115
1116 // Override this so that AppKit will send us arrow keys as key down events so we can
1117 // support them via the key bindings mechanism.
1118 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
1119 {
1120     return YES;
1121 }
1122
1123 - (void)_setMouseDownEvent:(NSEvent *)event
1124 {
1125     ASSERT(!event || [event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
1126     
1127     if (event == _data->_mouseDownEvent)
1128         return;
1129     
1130     [_data->_mouseDownEvent release];
1131     _data->_mouseDownEvent = [event retain];
1132 }
1133
1134 #if USE(ASYNC_NSTEXTINPUTCLIENT)
1135 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
1136     - (void)Selector:(NSEvent *)theEvent \
1137     { \
1138         if (_data->_ignoresNonWheelEvents) \
1139             return; \
1140         if (NSTextInputContext *context = [self inputContext]) { \
1141             [context handleEvent:theEvent completionHandler:^(BOOL handled) { \
1142                 if (handled) \
1143                     LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
1144                 else { \
1145                     NativeWebMouseEvent webEvent(theEvent, self); \
1146                     _data->_page->handleMouseEvent(webEvent); \
1147                 } \
1148             }]; \
1149             return; \
1150         } \
1151         NativeWebMouseEvent webEvent(theEvent, self); \
1152         _data->_page->handleMouseEvent(webEvent); \
1153     }
1154 #else
1155 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
1156     - (void)Selector:(NSEvent *)theEvent \
1157     { \
1158         if (_data->_ignoresNonWheelEvents) \
1159             return; \
1160         if ([[self inputContext] handleEvent:theEvent]) { \
1161             LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
1162             return; \
1163         } \
1164         NativeWebMouseEvent webEvent(theEvent, self); \
1165         _data->_page->handleMouseEvent(webEvent); \
1166     }
1167 #endif
1168
1169 NATIVE_MOUSE_EVENT_HANDLER(mouseEntered)
1170 NATIVE_MOUSE_EVENT_HANDLER(mouseExited)
1171 NATIVE_MOUSE_EVENT_HANDLER(mouseMovedInternal)
1172 NATIVE_MOUSE_EVENT_HANDLER(mouseDownInternal)
1173 NATIVE_MOUSE_EVENT_HANDLER(mouseUpInternal)
1174 NATIVE_MOUSE_EVENT_HANDLER(mouseDraggedInternal)
1175 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDown)
1176 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDragged)
1177 NATIVE_MOUSE_EVENT_HANDLER(otherMouseMoved)
1178 NATIVE_MOUSE_EVENT_HANDLER(otherMouseUp)
1179 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDown)
1180 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDragged)
1181 NATIVE_MOUSE_EVENT_HANDLER(rightMouseUp)
1182
1183 #undef NATIVE_MOUSE_EVENT_HANDLER
1184
1185 - (void)_ensureGestureController
1186 {
1187     if (_data->_gestureController)
1188         return;
1189
1190     _data->_gestureController = std::make_unique<ViewGestureController>(*_data->_page);
1191 }
1192
1193 - (void)scrollWheel:(NSEvent *)event
1194 {
1195     if (_data->_ignoresAllEvents)
1196         return;
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     [self _dismissContentRelativeChildWindows];
1247 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
1248     [_data->_actionMenuController wkView:self willHandleMouseDown:event];
1249     [_data->_immediateActionController 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         [self _dismissContentRelativeChildWindows];
2584     }
2585
2586     _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]);
2587 }
2588
2589 - (void)doWindowDidChangeScreen
2590 {
2591     NSWindow *window = _data->_targetWindowForMovePreparation ? _data->_targetWindowForMovePreparation : self.window;
2592     _data->_page->windowScreenDidChange((PlatformDisplayID)[[[[window screen] deviceDescription] objectForKey:@"NSScreenNumber"] intValue]);
2593 }
2594
2595 - (void)_windowDidBecomeKey:(NSNotification *)notification
2596 {
2597     NSWindow *keyWindow = [notification object];
2598     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet]) {
2599         [self _updateSecureInputState];
2600         _data->_page->viewStateDidChange(ViewState::WindowIsActive);
2601     }
2602 }
2603
2604 - (void)_windowDidChangeScreen:(NSNotification *)notification
2605 {
2606     [self doWindowDidChangeScreen];
2607 }
2608
2609 - (void)_windowDidChangeLayerHosting:(NSNotification *)notification
2610 {
2611     _data->_page->layerHostingModeDidChange();
2612 }
2613
2614 - (void)_windowDidResignKey:(NSNotification *)notification
2615 {
2616     NSWindow *formerKeyWindow = [notification object];
2617     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) {
2618         [self _updateSecureInputState];
2619         _data->_page->viewStateDidChange(ViewState::WindowIsActive);
2620     }
2621 }
2622
2623 - (void)_windowDidMiniaturize:(NSNotification *)notification
2624 {
2625     _data->_page->viewStateDidChange(ViewState::IsVisible);
2626 }
2627
2628 - (void)_windowDidDeminiaturize:(NSNotification *)notification
2629 {
2630     _data->_page->viewStateDidChange(ViewState::IsVisible);
2631 }
2632
2633 - (void)_windowDidMove:(NSNotification *)notification
2634 {
2635     [self _updateWindowAndViewFrames];    
2636 }
2637
2638 - (void)_windowDidResize:(NSNotification *)notification
2639 {
2640     [self _updateWindowAndViewFrames];
2641 }
2642
2643 - (void)_windowDidOrderOffScreen:(NSNotification *)notification
2644 {
2645     _data->_page->viewStateDidChange(ViewState::IsVisible | ViewState::WindowIsActive);
2646 }
2647
2648 - (void)_windowDidOrderOnScreen:(NSNotification *)notification
2649 {
2650     _data->_page->viewStateDidChange(ViewState::IsVisible | ViewState::WindowIsActive);
2651 }
2652
2653 - (void)_windowDidChangeBackingProperties:(NSNotification *)notification
2654 {
2655     CGFloat oldBackingScaleFactor = [[notification.userInfo objectForKey:NSBackingPropertyOldScaleFactorKey] doubleValue];
2656     CGFloat newBackingScaleFactor = [self _intrinsicDeviceScaleFactor]; 
2657     if (oldBackingScaleFactor == newBackingScaleFactor)
2658         return; 
2659
2660     _data->_page->setIntrinsicDeviceScaleFactor(newBackingScaleFactor);
2661 }
2662
2663 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2664 - (void)_windowDidChangeOcclusionState:(NSNotification *)notification
2665 {
2666     _data->_page->viewStateDidChange(ViewState::IsVisible);
2667 }
2668 #endif
2669
2670 - (void)drawRect:(NSRect)rect
2671 {
2672     LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
2673     _data->_page->endPrinting();
2674 }
2675
2676 - (BOOL)isOpaque
2677 {
2678     return _data->_page->drawsBackground();
2679 }
2680
2681 - (BOOL)mouseDownCanMoveWindow
2682 {
2683     // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent,
2684     // but we don't want a drag in the NSView to move the window, even if it's transparent.
2685     return NO;
2686 }
2687
2688 - (void)viewDidHide
2689 {
2690     _data->_page->viewStateDidChange(ViewState::IsVisible);
2691 }
2692
2693 - (void)viewDidUnhide
2694 {
2695     _data->_page->viewStateDidChange(ViewState::IsVisible);
2696 }
2697
2698 - (void)viewDidChangeBackingProperties
2699 {
2700     NSColorSpace *colorSpace = [[self window] colorSpace];
2701     if ([colorSpace isEqualTo:_data->_colorSpace.get()])
2702         return;
2703
2704     _data->_colorSpace = nullptr;
2705     if (DrawingAreaProxy *drawingArea = _data->_page->drawingArea())
2706         drawingArea->colorSpaceDidChange();
2707 }
2708
2709 - (void)_activeSpaceDidChange:(NSNotification *)notification
2710 {
2711     _data->_page->viewStateDidChange(ViewState::IsVisible);
2712 }
2713
2714 - (void)_applicationWillTerminate:(NSNotification *)notification
2715 {
2716     _data->_page->process().processPool().applicationWillTerminate();
2717 }
2718
2719 - (void)_dictionaryLookupPopoverWillClose:(NSNotification *)notification
2720 {
2721     [self _setTextIndicator:nil fadeOut:NO];
2722 }
2723
2724 - (void)_accessibilityRegisterUIProcessTokens
2725 {
2726     // Initialize remote accessibility when the window connection has been established.
2727     NSData *remoteElementToken = WKAXRemoteTokenForElement(self);
2728     NSData *remoteWindowToken = WKAXRemoteTokenForElement([self window]);
2729     IPC::DataReference elementToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteElementToken bytes]), [remoteElementToken length]);
2730     IPC::DataReference windowToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteWindowToken bytes]), [remoteWindowToken length]);
2731     _data->_page->registerUIProcessAccessibilityTokens(elementToken, windowToken);
2732 }
2733
2734 - (void)_updateRemoteAccessibilityRegistration:(BOOL)registerProcess
2735 {
2736     // When the tree is connected/disconnected, the remote accessibility registration
2737     // needs to be updated with the pid of the remote process. If the process is going
2738     // away, that information is not present in WebProcess
2739     pid_t pid = 0;
2740     if (registerProcess)
2741         pid = _data->_page->process().processIdentifier();
2742     else if (!registerProcess) {
2743         pid = WKAXRemoteProcessIdentifier(_data->_remoteAccessibilityChild.get());
2744         _data->_remoteAccessibilityChild = nil;
2745     }
2746     if (pid)
2747         WKAXRegisterRemoteProcess(registerProcess, pid); 
2748 }
2749
2750 - (void)enableAccessibilityIfNecessary
2751 {
2752     if (WebCore::AXObjectCache::accessibilityEnabled())
2753         return;
2754
2755     // After enabling accessibility update the window frame on the web process so that the
2756     // correct accessibility position is transmitted (when AX is off, that position is not calculated).
2757     WebCore::AXObjectCache::enableAccessibility();
2758     [self _updateWindowAndViewFrames];
2759 }
2760
2761 - (id)accessibilityFocusedUIElement
2762 {
2763     [self enableAccessibilityIfNecessary];
2764     return _data->_remoteAccessibilityChild.get();
2765 }
2766
2767 - (BOOL)accessibilityIsIgnored
2768 {
2769     return NO;
2770 }
2771
2772 - (id)accessibilityHitTest:(NSPoint)point
2773 {
2774     [self enableAccessibilityIfNecessary];
2775     return _data->_remoteAccessibilityChild.get();
2776 }
2777
2778 - (id)accessibilityAttributeValue:(NSString*)attribute
2779 {
2780     [self enableAccessibilityIfNecessary];
2781
2782     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
2783
2784         id child = nil;
2785         if (_data->_remoteAccessibilityChild)
2786             child = _data->_remoteAccessibilityChild.get();
2787         
2788         if (!child)
2789             return nil;
2790         return [NSArray arrayWithObject:child];
2791     }
2792     if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
2793         return NSAccessibilityGroupRole;
2794     if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
2795         return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil);
2796     if ([attribute isEqualToString:NSAccessibilityParentAttribute])
2797         return NSAccessibilityUnignoredAncestor([self superview]);
2798     if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
2799         return [NSNumber numberWithBool:YES];
2800     
2801     return [super accessibilityAttributeValue:attribute];
2802 }
2803
2804 - (NSView *)hitTest:(NSPoint)point
2805 {
2806     NSView *hitView = [super hitTest:point];
2807     if (hitView && _data && hitView == _data->_layerHostingView)
2808         hitView = self;
2809
2810     return hitView;
2811 }
2812
2813 - (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent
2814 {
2815     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved location:[[flagsChangedEvent window] mouseLocationOutsideOfEventStream]
2816         modifierFlags:[flagsChangedEvent modifierFlags] timestamp:[flagsChangedEvent timestamp] windowNumber:[flagsChangedEvent windowNumber]
2817         context:[flagsChangedEvent context] eventNumber:0 clickCount:0 pressure:0];
2818     NativeWebMouseEvent webEvent(fakeEvent, self);
2819     _data->_page->handleMouseEvent(webEvent);
2820 }
2821
2822 - (NSInteger)conversationIdentifier
2823 {
2824     return (NSInteger)self;
2825 }
2826
2827 - (float)_intrinsicDeviceScaleFactor
2828 {
2829     if (_data->_targetWindowForMovePreparation)
2830         return [_data->_targetWindowForMovePreparation backingScaleFactor];
2831     if (NSWindow *window = [self window])
2832         return [window backingScaleFactor];
2833     return [[NSScreen mainScreen] backingScaleFactor];
2834 }
2835
2836 - (void)_setDrawingAreaSize:(NSSize)size
2837 {
2838     if (!_data->_page->drawingArea())
2839         return;
2840     
2841     _data->_page->drawingArea()->setSize(IntSize(size), IntSize(0, 0), IntSize(_data->_resizeScrollOffset));
2842     _data->_resizeScrollOffset = NSZeroSize;
2843 }
2844
2845 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
2846 - (void)quickLookWithEvent:(NSEvent *)event
2847 {
2848     if (_data->_ignoresNonWheelEvents)
2849         return;
2850
2851     NSPoint locationInViewCoordinates = [self convertPoint:[event locationInWindow] fromView:nil];
2852     _data->_page->performDictionaryLookupAtLocation(FloatPoint(locationInViewCoordinates.x, locationInViewCoordinates.y));
2853 }
2854 #endif
2855
2856 - (std::unique_ptr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy
2857 {
2858     if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"WebKit2UseRemoteLayerTreeDrawingArea"] boolValue])
2859         return std::make_unique<RemoteLayerTreeDrawingAreaProxy>(*_data->_page);
2860
2861     return std::make_unique<TiledCoreAnimationDrawingAreaProxy>(*_data->_page);
2862 }
2863
2864 - (BOOL)_isFocused
2865 {
2866     if (_data->_inBecomeFirstResponder)
2867         return YES;
2868     if (_data->_inResignFirstResponder)
2869         return NO;
2870     return [[self window] firstResponder] == self;
2871 }
2872
2873 - (WebKit::ColorSpaceData)_colorSpace
2874 {
2875     if (!_data->_colorSpace) {
2876         if (_data->_targetWindowForMovePreparation)
2877             _data->_colorSpace = [_data->_targetWindowForMovePreparation colorSpace];
2878         else if (NSWindow *window = [self window])
2879             _data->_colorSpace = [window colorSpace];
2880         else
2881             _data->_colorSpace = [[NSScreen mainScreen] colorSpace];
2882     }
2883         
2884     ColorSpaceData colorSpaceData;
2885     colorSpaceData.cgColorSpace = [_data->_colorSpace CGColorSpace];
2886
2887     return colorSpaceData;    
2888 }
2889
2890 - (void)_processDidExit
2891 {
2892     [self _notifyInputContextAboutDiscardedComposition];
2893
2894     if (_data->_layerHostingView)
2895         [self _setAcceleratedCompositingModeRootLayer:nil];
2896
2897     [self _updateRemoteAccessibilityRegistration:NO];
2898
2899     _data->_gestureController = nullptr;
2900 }
2901
2902 - (void)_pageClosed
2903 {
2904     [self _updateRemoteAccessibilityRegistration:NO];
2905 }
2906
2907 - (void)_didRelaunchProcess
2908 {
2909     [self _accessibilityRegisterUIProcessTokens];
2910 }
2911
2912 - (void)_preferencesDidChange
2913 {
2914     BOOL needsViewFrameInWindowCoordinates = _data->_page->preferences().pluginsEnabled();
2915
2916     if (!!needsViewFrameInWindowCoordinates == !!_data->_needsViewFrameInWindowCoordinates)
2917         return;
2918
2919     _data->_needsViewFrameInWindowCoordinates = needsViewFrameInWindowCoordinates;
2920     if ([self window])
2921         [self _updateWindowAndViewFrames];
2922 }
2923
2924 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
2925 {
2926     ValidationVector items = _data->_validationMap.take(commandName);
2927     size_t size = items.size();
2928     for (size_t i = 0; i < size; ++i) {
2929         ValidationItem item = items[i].get();
2930         [menuItem(item) setState:newState];
2931         [menuItem(item) setEnabled:isEnabled];
2932         [toolbarItem(item) setEnabled:isEnabled];
2933         // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
2934     }
2935 }
2936
2937 - (BOOL)_tryPostProcessPluginComplexTextInputKeyDown:(NSEvent *)event
2938 {
2939     if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
2940         return NO;
2941
2942     // In the legacy text input model, the event has already been sent to the input method.
2943     if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
2944         return NO;
2945
2946     return [self _handlePluginComplexTextInputKeyDown:event];
2947 }
2948
2949 - (void)_doneWithKeyEvent:(NSEvent *)event eventWasHandled:(BOOL)eventWasHandled
2950 {
2951     if ([event type] != NSKeyDown)
2952         return;
2953
2954     if ([self _tryPostProcessPluginComplexTextInputKeyDown:event])
2955         return;
2956     
2957     if (eventWasHandled) {
2958         [NSCursor setHiddenUntilMouseMoves:YES];
2959         return;
2960     }
2961
2962     // resending the event may destroy this WKView
2963     RetainPtr<WKView> protector(self);
2964
2965     ASSERT(!_data->_keyDownEventBeingResent);
2966     _data->_keyDownEventBeingResent = event;
2967     [NSApp _setCurrentEvent:event];
2968     [NSApp sendEvent:event];
2969
2970     _data->_keyDownEventBeingResent = nullptr;
2971 }
2972
2973 - (NSRect)_convertToDeviceSpace:(NSRect)rect
2974 {
2975     return toDeviceSpace(rect, [self window]);
2976 }
2977
2978 - (NSRect)_convertToUserSpace:(NSRect)rect
2979 {
2980     return toUserSpace(rect, [self window]);
2981 }
2982
2983 // Any non-zero value will do, but using something recognizable might help us debug some day.
2984 #define TRACKING_RECT_TAG 0xBADFACE
2985
2986 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2987 {
2988     ASSERT(_data->_trackingRectOwner == nil);
2989     _data->_trackingRectOwner = owner;
2990     _data->_trackingRectUserData = data;
2991     return TRACKING_RECT_TAG;
2992 }
2993
2994 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2995 {
2996     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
2997     ASSERT(_data->_trackingRectOwner == nil);
2998     _data->_trackingRectOwner = owner;
2999     _data->_trackingRectUserData = data;
3000     return TRACKING_RECT_TAG;
3001 }
3002
3003 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
3004 {
3005     ASSERT(count == 1);
3006     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
3007     ASSERT(_data->_trackingRectOwner == nil);
3008     _data->_trackingRectOwner = owner;
3009     _data->_trackingRectUserData = userDataList[0];
3010     trackingNums[0] = TRACKING_RECT_TAG;
3011 }
3012
3013 - (void)removeTrackingRect:(NSTrackingRectTag)tag
3014 {
3015     if (!_data)
3016         return;
3017
3018     if (tag == 0)
3019         return;
3020     
3021     if (tag == TRACKING_RECT_TAG) {
3022         _data->_trackingRectOwner = nil;
3023         return;
3024     }
3025     
3026     if (tag == _data->_lastToolTipTag) {
3027         [super removeTrackingRect:tag];
3028         _data->_lastToolTipTag = 0;
3029         return;
3030     }
3031
3032     // If any other tracking rect is being removed, we don't know how it was created
3033     // and it's possible there's a leak involved (see 3500217)
3034     ASSERT_NOT_REACHED();
3035 }
3036
3037 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
3038 {
3039     int i;
3040     for (i = 0; i < count; ++i) {
3041         int tag = tags[i];
3042         if (tag == 0)
3043             continue;
3044         ASSERT(tag == TRACKING_RECT_TAG);
3045         if (_data != nil) {
3046             _data->_trackingRectOwner = nil;
3047         }
3048     }
3049 }
3050
3051 - (void)_sendToolTipMouseExited
3052 {
3053     // Nothing matters except window, trackingNumber, and userData.
3054     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
3055         location:NSMakePoint(0, 0)
3056         modifierFlags:0
3057         timestamp:0
3058         windowNumber:[[self window] windowNumber]
3059         context:NULL
3060         eventNumber:0
3061         trackingNumber:TRACKING_RECT_TAG
3062         userData:_data->_trackingRectUserData];
3063     [_data->_trackingRectOwner mouseExited:fakeEvent];
3064 }
3065
3066 - (void)_sendToolTipMouseEntered
3067 {
3068     // Nothing matters except window, trackingNumber, and userData.
3069     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
3070         location:NSMakePoint(0, 0)
3071         modifierFlags:0
3072         timestamp:0
3073         windowNumber:[[self window] windowNumber]
3074         context:NULL
3075         eventNumber:0
3076         trackingNumber:TRACKING_RECT_TAG
3077         userData:_data->_trackingRectUserData];
3078     [_data->_trackingRectOwner mouseEntered:fakeEvent];
3079 }
3080
3081 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
3082 {
3083     return nsStringFromWebCoreString(_data->_page->toolTip());
3084 }
3085
3086 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
3087 {
3088     if (oldToolTip)
3089         [self _sendToolTipMouseExited];
3090
3091     if (newToolTip && [newToolTip length] > 0) {
3092         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
3093         [self removeAllToolTips];
3094         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
3095         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
3096         [self _sendToolTipMouseEntered];
3097     }
3098 }
3099
3100 - (void)_setTextIndicator:(PassRefPtr<TextIndicator>)textIndicator fadeOut:(BOOL)fadeOut
3101 {
3102     if (!textIndicator) {
3103         _data->_textIndicatorWindow = nullptr;
3104         return;
3105     }
3106
3107     if (!_data->_textIndicatorWindow)
3108         _data->_textIndicatorWindow = std::make_unique<TextIndicatorWindow>(self);
3109
3110     NSRect contentRect = [self.window convertRectToScreen:[self convertRect:textIndicator->textBoundingRectInWindowCoordinates() toView:nil]];
3111     _data->_textIndicatorWindow->setTextIndicator(textIndicator, NSRectToCGRect(contentRect), fadeOut);
3112 }
3113
3114 - (void)_setTextIndicatorAnimationProgress:(float)progress
3115 {
3116     if (_data->_textIndicatorWindow)
3117         _data->_textIndicatorWindow->setAnimationProgress(progress);
3118 }
3119
3120 - (CALayer *)_rootLayer
3121 {
3122     return [_data->_layerHostingView layer];
3123 }
3124
3125 - (void)_setAcceleratedCompositingModeRootLayer:(CALayer *)rootLayer
3126 {
3127     [rootLayer web_disableAllActions];
3128
3129     _data->_rootLayer = rootLayer;
3130
3131 #if WK_API_ENABLED
3132     if (_data->_thumbnailView) {
3133         [self _updateThumbnailViewLayer];
3134         return;
3135     }
3136 #endif
3137
3138     [CATransaction begin];
3139     [CATransaction setDisableActions:YES];
3140
3141     if (rootLayer) {
3142         if (!_data->_layerHostingView) {
3143             // Create an NSView that will host our layer tree.
3144             _data->_layerHostingView = adoptNS([[WKFlippedView alloc] initWithFrame:[self bounds]]);
3145             [_data->_layerHostingView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
3146
3147
3148             [self addSubview:_data->_layerHostingView.get() positioned:NSWindowBelow relativeTo:nil];
3149
3150             // Create a root layer that will back the NSView.
3151             RetainPtr<CALayer> layer = adoptNS([[CALayer alloc] init]);
3152             [layer setDelegate:[WebActionDisablingCALayerDelegate shared]];
3153 #ifndef NDEBUG
3154             [layer setName:@"Hosting root layer"];
3155 #endif
3156
3157             [_data->_layerHostingView setLayer:layer.get()];
3158             [_data->_layerHostingView setWantsLayer:YES];
3159         }
3160
3161         [_data->_layerHostingView layer].sublayers = [NSArray arrayWithObject:rootLayer];
3162     } else {
3163         if (_data->_layerHostingView) {
3164             [_data->_layerHostingView removeFromSuperview];
3165             [_data->_layerHostingView setLayer:nil];
3166             [_data->_layerHostingView setWantsLayer:NO];
3167
3168             _data->_layerHostingView = nullptr;
3169         }
3170     }
3171
3172     [CATransaction commit];
3173 }
3174
3175 - (CALayer *)_acceleratedCompositingModeRootLayer
3176 {
3177     return _data->_rootLayer.get();
3178 }
3179
3180 - (PassRefPtr<ViewSnapshot>)_takeViewSnapshot
3181 {
3182     NSWindow *window = self.window;
3183
3184     CGSWindowID windowID = (CGSWindowID)[window windowNumber];
3185     if (!windowID || ![window isVisible])
3186         return nullptr;
3187
3188     RetainPtr<CGImageRef> windowSnapshotImage = adoptCF(CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, windowID, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageShouldBeOpaque));
3189
3190     // Work around <rdar://problem/17084993>; re-request the snapshot at kCGWindowImageNominalResolution if it was captured at the wrong scale.
3191     CGFloat desiredSnapshotWidth = window.frame.size.width * window.screen.backingScaleFactor;
3192     if (CGImageGetWidth(windowSnapshotImage.get()) != desiredSnapshotWidth)
3193         windowSnapshotImage = adoptCF(CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, windowID, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageShouldBeOpaque | kCGWindowImageNominalResolution));
3194
3195     [self _ensureGestureController];
3196
3197     NSRect windowCaptureRect;
3198     FloatRect boundsForCustomSwipeViews = _data->_gestureController->windowRelativeBoundsForCustomSwipeViews();
3199     if (!boundsForCustomSwipeViews.isEmpty())
3200         windowCaptureRect = boundsForCustomSwipeViews;
3201     else {
3202         NSRect unobscuredBounds = self.bounds;
3203         float topContentInset = _data->_page->topContentInset();
3204         unobscuredBounds.origin.y += topContentInset;
3205         unobscuredBounds.size.height -= topContentInset;
3206         windowCaptureRect = [self convertRect:unobscuredBounds toView:nil];
3207     }
3208
3209     NSRect windowCaptureScreenRect = [window convertRectToScreen:windowCaptureRect];
3210     CGRect windowScreenRect;
3211     CGSGetScreenRectForWindow(CGSMainConnectionID(), (CGSWindowID)[window windowNumber], &windowScreenRect);
3212
3213     NSRect croppedImageRect = windowCaptureRect;
3214     croppedImageRect.origin.y = windowScreenRect.size.height - windowCaptureScreenRect.size.height - NSMinY(windowCaptureRect);
3215
3216     auto croppedSnapshotImage = adoptCF(CGImageCreateWithImageInRect(windowSnapshotImage.get(), NSRectToCGRect([window convertRectToBacking:croppedImageRect])));
3217
3218     auto surface = IOSurface::createFromImage(croppedSnapshotImage.get());
3219     if (!surface)
3220         return nullptr;
3221     surface->setIsVolatile(true);
3222
3223     return ViewSnapshot::create(surface.get(), surface->size(), surface->totalBytes());
3224 }
3225
3226 - (void)_wheelEventWasNotHandledByWebCore:(NSEvent *)event
3227 {
3228     if (_data->_gestureController)
3229         _data->_gestureController->wheelEventWasNotHandledByWebCore(event);
3230 }
3231
3232 - (void)_setAccessibilityWebProcessToken:(NSData *)data
3233 {
3234     _data->_remoteAccessibilityChild = WKAXRemoteElementForToken(data);
3235     [self _updateRemoteAccessibilityRegistration:YES];
3236 }
3237
3238 - (void)_pluginFocusOrWindowFocusChanged:(BOOL)pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
3239 {
3240     BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
3241
3242     if (pluginHasFocusAndWindowHasFocus) {
3243         // Check if we're already allowing text input for this plug-in.
3244         if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
3245             return;
3246
3247         _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
3248
3249     } else {
3250         // Check if we got a request to unfocus a plug-in that isn't focused.
3251         if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
3252             return;
3253
3254         _data->_pluginComplexTextInputIdentifier = 0;
3255     }
3256
3257     if (inputSourceChanged) {
3258         // The input source changed, go ahead and discard any entered text.
3259         [[WKTextInputWindowController sharedTextInputWindowController] unmarkText];
3260     }
3261
3262     // This will force the current input context to be updated to its correct value.
3263     [NSApp updateWindows];
3264 }
3265
3266 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
3267 {
3268     if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier) {
3269         // We're asked to update the state for a plug-in that doesn't have focus.
3270         return;
3271     }
3272
3273     [self _setPluginComplexTextInputState:pluginComplexTextInputState];
3274 }
3275
3276 - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag
3277 {
3278     IntSize size([image size]);
3279     size.scale(1.0 / _data->_page->deviceScaleFactor());
3280     [image setSize:size];
3281     
3282     // The call below could release this WKView.
3283     RetainPtr<WKView> protector(self);
3284     
3285 #pragma clang diagnostic push
3286 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3287     [self dragImage:image
3288                  at:clientPoint
3289              offset:NSZeroSize
3290               event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent
3291          pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
3292              source:self
3293           slideBack:YES];
3294 #pragma clang diagnostic pop
3295 }
3296
3297 static bool matchesExtensionOrEquivalent(NSString *filename, NSString *extension)
3298 {
3299     NSString *extensionAsSuffix = [@"." stringByAppendingString:extension];
3300     return hasCaseInsensitiveSuffix(filename, extensionAsSuffix) || (stringIsCaseInsensitiveEqualToString(extension, @"jpeg")
3301                                                                      && hasCaseInsensitiveSuffix(filename, @".jpg"));
3302 }
3303
3304 - (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
3305
3306 {
3307     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName];
3308     RetainPtr<NSMutableArray> types = adoptNS([[NSMutableArray alloc] initWithObjects:NSFilesPromisePboardType, nil]);
3309     
3310     [types addObjectsFromArray:archiveBuffer ? PasteboardTypes::forImagesWithArchive() : PasteboardTypes::forImages()];
3311     [pasteboard declareTypes:types.get() owner:self];
3312     if (!matchesExtensionOrEquivalent(filename, extension))
3313         filename = [[filename stringByAppendingString:@"."] stringByAppendingString:extension];
3314
3315     [pasteboard setString:visibleUrl forType:NSStringPboardType];
3316     [pasteboard setString:visibleUrl forType:PasteboardTypes::WebURLPboardType];
3317     [pasteboard setString:title forType:PasteboardTypes::WebURLNamePboardType];
3318     [pasteboard setPropertyList:[NSArray arrayWithObjects:[NSArray arrayWithObject:visibleUrl], [NSArray arrayWithObject:title], nil] forType:PasteboardTypes::WebURLsWithTitlesPboardType];
3319     [pasteboard setPropertyList:[NSArray arrayWithObject:extension] forType:NSFilesPromisePboardType];
3320
3321     if (archiveBuffer)
3322         [pasteboard setData:archiveBuffer->createNSData().get() forType:PasteboardTypes::WebArchivePboardType];
3323
3324     _data->_promisedImage = image;
3325     _data->_promisedFilename = filename;
3326     _data->_promisedURL = url;
3327 }
3328
3329 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
3330 {
3331     _data->_promisedImage = 0;
3332     _data->_promisedFilename = "";
3333     _data->_promisedURL = "";
3334 }
3335
3336 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
3337 {
3338     // FIXME: need to support NSRTFDPboardType
3339
3340     if ([type isEqual:NSTIFFPboardType] && _data->_promisedImage) {
3341         [pasteboard setData:(NSData *)_data->_promisedImage->getTIFFRepresentation() forType:NSTIFFPboardType];
3342         _data->_promisedImage = 0;
3343     }
3344 }
3345
3346 static BOOL fileExists(NSString *path)
3347 {
3348     struct stat statBuffer;
3349     return !lstat([path fileSystemRepresentation], &statBuffer);
3350 }
3351
3352 static NSString *pathWithUniqueFilenameForPath(NSString *path)
3353 {
3354     // "Fix" the filename of the path.
3355     NSString *filename = filenameByFixingIllegalCharacters([path lastPathComponent]);
3356     path = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:filename];
3357     
3358     if (fileExists(path)) {
3359         // Don't overwrite existing file by appending "-n", "-n.ext" or "-n.ext.ext" to the filename.
3360         NSString *extensions = nil;
3361         NSString *pathWithoutExtensions;
3362         NSString *lastPathComponent = [path lastPathComponent];
3363         NSRange periodRange = [lastPathComponent rangeOfString:@"."];
3364         
3365         if (periodRange.location == NSNotFound) {
3366             pathWithoutExtensions = path;
3367         } else {
3368             extensions = [lastPathComponent substringFromIndex:periodRange.location + 1];
3369             lastPathComponent = [lastPathComponent substringToIndex:periodRange.location];
3370             pathWithoutExtensions = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:lastPathComponent];
3371         }
3372         
3373         for (unsigned i = 1; ; i++) {
3374             NSString *pathWithAppendedNumber = [NSString stringWithFormat:@"%@-%d", pathWithoutExtensions, i];
3375             path = [extensions length] ? [pathWithAppendedNumber stringByAppendingPathExtension:extensions] : pathWithAppendedNumber;
3376             if (!fileExists(path))
3377                 break;
3378         }
3379     }
3380     
3381     return path;
3382 }
3383
3384 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
3385 {
3386     RetainPtr<NSFileWrapper> wrapper;
3387     RetainPtr<NSData> data;
3388     
3389     if (_data->_promisedImage) {
3390         data = _data->_promisedImage->data()->createNSData();
3391         wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:data.get()]);
3392         [wrapper setPreferredFilename:_data->_promisedFilename];
3393     }
3394     
3395     if (!wrapper) {
3396         LOG_ERROR("Failed to create image file.");
3397         return nil;
3398     }
3399     
3400     // FIXME: Report an error if we fail to create a file.
3401     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
3402     path = pathWithUniqueFilenameForPath(path);
3403     if (![wrapper writeToURL:[NSURL fileURLWithPath:path] options:NSFileWrapperWritingWithNameUpdating originalContentsURL:nil error:nullptr])
3404         LOG_ERROR("Failed to create image file via -[NSFileWrapper writeToURL:options:originalContentsURL:error:]");
3405
3406     if (!_data->_promisedURL.isEmpty())
3407         WebCore::setMetadataURL(_data->_promisedURL, "", String(path));
3408     
3409     return [NSArray arrayWithObject:[path lastPathComponent]];
3410 }
3411
3412 - (void)_updateSecureInputState
3413 {
3414     if (![[self window] isKeyWindow] || ![self _isFocused]) {
3415         if (_data->_inSecureInputState) {
3416             DisableSecureEventInput();
3417             _data->_inSecureInputState = NO;
3418         }
3419         return;
3420     }
3421     // WKView has a single input context for all editable areas (except for plug-ins).
3422     NSTextInputContext *context = [super inputContext];
3423     bool isInPasswordField = _data->_page->editorState().isInPasswordField;
3424
3425     if (isInPasswordField) {
3426         if (!_data->_inSecureInputState)
3427             EnableSecureEventInput();
3428         static NSArray *romanInputSources = [[NSArray alloc] initWithObjects:&NSAllRomanInputSourcesLocaleIdentifier count:1];
3429         LOG(TextInput, "-> setAllowedInputSourceLocales:romanInputSources");
3430         [context setAllowedInputSourceLocales:romanInputSources];
3431     } else {
3432         if (_data->_inSecureInputState)
3433             DisableSecureEventInput();
3434         LOG(TextInput, "-> setAllowedInputSourceLocales:nil");
3435         [context setAllowedInputSourceLocales:nil];
3436     }
3437     _data->_inSecureInputState = isInPasswordField;
3438 }
3439
3440 - (void)_resetSecureInputState
3441 {
3442     if (_data->_inSecureInputState) {
3443         DisableSecureEventInput();
3444         _data->_inSecureInputState = NO;
3445     }
3446 }
3447
3448 - (void)_notifyInputContextAboutDiscardedComposition
3449 {
3450     // <rdar://problem/9359055>: -discardMarkedText can only be called for active contexts.
3451     // FIXME: We fail to ever notify the input context if something (e.g. a navigation) happens while the window is not key.
3452     // This is not a problem when the window is key, because we discard marked text on resigning first responder.
3453     if (![[self window] isKeyWindow] || self != [[self window] firstResponder])
3454         return;
3455
3456     LOG(TextInput, "-> discardMarkedText");
3457     [[super inputContext] discardMarkedText]; // Inform the input method that we won't have an inline input area despite having been asked to.
3458 }
3459
3460 - (NSWindow *)_targetWindowForMovePreparation
3461 {
3462     return _data->_targetWindowForMovePreparation;
3463 }
3464
3465 #if ENABLE(FULLSCREEN_API)
3466 - (BOOL)_hasFullScreenWindowController
3467 {
3468     return (bool)_data->_fullScreenWindowController;
3469 }
3470
3471 - (WKFullScreenWindowController *)_fullScreenWindowController
3472 {
3473     if (!_data->_fullScreenWindowController)
3474         _data->_fullScreenWindowController = adoptNS([[WKFullScreenWindowController alloc] initWithWindow:[self createFullScreenWindow] webView:self]);
3475
3476     return _data->_fullScreenWindowController.get();
3477 }
3478
3479 - (void)_closeFullScreenWindowController
3480 {
3481     if (!_data->_fullScreenWindowController)
3482         return;
3483
3484     [_data->_fullScreenWindowController close];
3485     _data->_fullScreenWindowController = nullptr;
3486 }
3487 #endif
3488
3489 - (bool)_executeSavedCommandBySelector:(SEL)selector
3490 {
3491     LOG(TextInput, "Executing previously saved command %s", sel_getName(selector));
3492     // The sink does two things: 1) Tells us if the responder went unhandled, and
3493     // 2) prevents any NSBeep; we don't ever want to beep here.
3494     RetainPtr<WKResponderChainSink> sink = adoptNS([[WKResponderChainSink alloc] initWithResponderChain:self]);
3495     [super doCommandBySelector:selector];
3496     [sink detach];
3497     return ![sink didReceiveUnhandledCommand];
3498 }
3499
3500 - (void)_setIntrinsicContentSize:(NSSize)intrinsicContentSize
3501 {
3502     // If the intrinsic content size is less than the minimum layout width, the content flowed to fit,
3503     // so we can report that that dimension is flexible. If not, we need to report our intrinsic width
3504     // so that autolayout will know to provide space for us.
3505
3506     NSSize intrinsicContentSizeAcknowledgingFlexibleWidth = intrinsicContentSize;
3507     if (intrinsicContentSize.width < _data->_page->minimumLayoutSize().width())
3508         intrinsicContentSizeAcknowledgingFlexibleWidth.width = NSViewNoInstrinsicMetric;
3509
3510     _data->_intrinsicContentSize = intrinsicContentSizeAcknowledgingFlexibleWidth;
3511     [self invalidateIntrinsicContentSize];
3512 }
3513
3514 - (void)_cacheWindowBottomCornerRect
3515 {
3516     // FIXME: We should remove this code when <rdar://problem/9362085> is resolved.
3517     NSWindow *window = [self window];
3518     if (!window)
3519         return;
3520
3521     _data->_windowBottomCornerIntersectionRect = [window _intersectBottomCornersWithRect:[self convertRect:[self visibleRect] toView:nil]];
3522     if (!NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect))
3523         [self setNeedsDisplayInRect:[self convertRect:_data->_windowBottomCornerIntersectionRect fromView:nil]];
3524 }
3525
3526 - (NSInteger)spellCheckerDocumentTag
3527 {
3528     if (!_data->_hasSpellCheckerDocumentTag) {
3529         _data->_spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
3530         _data->_hasSpellCheckerDocumentTag = YES;
3531     }
3532     return _data->_spellCheckerDocumentTag;
3533 }
3534
3535 - (void)handleAcceptedAlternativeText:(NSString*)text
3536 {
3537     _data->_page->handleAlternativeTextUIResult(text);
3538 }
3539
3540 - (void)_setSuppressVisibilityUpdates:(BOOL)suppressVisibilityUpdates
3541 {
3542     _data->_page->setSuppressVisibilityUpdates(suppressVisibilityUpdates);
3543 }
3544
3545 - (BOOL)_suppressVisibilityUpdates
3546 {
3547     return _data->_page->suppressVisibilityUpdates();
3548 }
3549
3550 - (NSTrackingArea *)_primaryTrackingArea
3551 {
3552     return _data->_primaryTrackingArea.get();
3553 }
3554
3555 - (void)_setPrimaryTrackingArea:(NSTrackingArea *)trackingArea
3556 {
3557     [self removeTrackingArea:_data->_primaryTrackingArea.get()];
3558     _data->_primaryTrackingArea = trackingArea;
3559     [self addTrackingArea:trackingArea];
3560 }
3561
3562 - (instancetype)initWithFrame:(NSRect)frame processPool:(WebProcessPool&)processPool configuration:(WebPageConfiguration)webPageConfiguration webView:(WKWebView *)webView
3563 {
3564     self = [super initWithFrame:frame];
3565     if (!self)
3566         return nil;
3567
3568     [NSApp registerServicesMenuSendTypes:PasteboardTypes::forSelection() returnTypes:PasteboardTypes::forEditing()];
3569
3570     InitializeWebKit2();
3571
3572     // Legacy style scrollbars have design details that rely on tracking the mouse all the time.
3573     NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect;
3574     if (WKRecommendedScrollerStyle() == NSScrollerStyleLegacy)
3575         options |= NSTrackingActiveAlways;
3576     else
3577         options |= NSTrackingActiveInKeyWindow;
3578
3579     _data = [[WKViewData alloc] init];
3580     _data->_primaryTrackingArea = adoptNS([[NSTrackingArea alloc] initWithRect:frame options:options owner:self userInfo:nil]);
3581     [self addTrackingArea:_data->_primaryTrackingArea.get()];
3582
3583     _data->_pageClient = std::make_unique<PageClientImpl>(self, webView);
3584     _data->_page = processPool.createWebPage(*_data->_pageClient, WTF::move(webPageConfiguration));
3585     _data->_page->setAddsVisitedLinks(processPool.historyClient().addsVisitedLinks());
3586
3587     _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]);
3588     _data->_page->initializeWebPage();
3589
3590     _data->_mouseDownEvent = nil;
3591     _data->_ignoringMouseDraggedEvents = NO;
3592     _data->_clipsToVisibleRect = NO;
3593     _data->_useContentPreparationRectForVisibleRect = NO;
3594     _data->_windowOcclusionDetectionEnabled = YES;
3595
3596     _data->_intrinsicContentSize = NSMakeSize(NSViewNoInstrinsicMetric, NSViewNoInstrinsicMetric);
3597
3598     _data->_needsViewFrameInWindowCoordinates = _data->_page->preferences().pluginsEnabled();
3599     
3600     [self _registerDraggedTypes];
3601
3602     self.wantsLayer = YES;
3603
3604     // Explicitly set the layer contents placement so AppKit will make sure that our layer has masksToBounds set to YES.
3605     self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft;
3606
3607     WebProcessPool::statistics().wkViewCount++;
3608
3609     NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
3610     [workspaceNotificationCenter addObserver:self selector:@selector(_activeSpaceDidChange:) name:NSWorkspaceActiveSpaceDidChangeNotification object:nil];
3611
3612     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:NSApp];
3613
3614     if (canLoadLUNotificationPopoverWillClose())
3615         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_dictionaryLookupPopoverWillClose:) name:getLUNotificationPopoverWillClose() object:nil];
3616
3617 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
3618     if ([self respondsToSelector:@selector(setActionMenu:)]) {
3619         RetainPtr<NSMenu> menu = adoptNS([[NSMenu alloc] init]);
3620         self.actionMenu = menu.get();
3621         _data->_actionMenuController = adoptNS([[WKActionMenuController alloc] initWithPage:*_data->_page view:self]);
3622         self.actionMenu.delegate = _data->_actionMenuController.get();
3623         self.actionMenu.autoenablesItems = NO;
3624     }
3625
3626     if (Class gestureClass = NSClassFromString(@"NSImmediateActionGestureRecognizer")) {
3627         _data->_immediateActionGestureRecognizer = adoptNS([(NSImmediateActionGestureRecognizer *)[gestureClass alloc] initWithTarget:nil action:NULL]);
3628         _data->_immediateActionController = adoptNS([[WKImmediateActionController alloc] initWithPage:*_data->_page view:self recognizer:_data->_immediateActionGestureRecognizer.get()]);
3629         [_data->_immediateActionGestureRecognizer setDelegate:_data->_immediateActionController.get()];
3630         [self addGestureRecognizer:_data->_immediateActionGestureRecognizer.get()];
3631     }
3632 #endif
3633
3634     return self;
3635 }
3636
3637 - (void)_registerDraggedTypes
3638 {
3639     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:PasteboardTypes::forEditing()];
3640     [types addObjectsFromArray:PasteboardTypes::forURL()];
3641     [self registerForDraggedTypes:[types allObjects]];
3642     [types release];
3643 }
3644
3645 #if WK_API_ENABLED
3646 - (void)_setThumbnailView:(_WKThumbnailView *)thumbnailView
3647 {
3648     ASSERT(!_data->_thumbnailView || !thumbnailView);
3649
3650     _data->_thumbnailView = thumbnailView;
3651
3652     if (thumbnailView)
3653         [self _updateThumbnailViewLayer];
3654     else
3655         [self _setAcceleratedCompositingModeRootLayer:_data->_rootLayer.get()];
3656 }
3657
3658 - (_WKThumbnailView *)_thumbnailView
3659 {
3660     return _data->_thumbnailView;
3661 }
3662
3663 - (void)_updateThumbnailViewLayer
3664 {
3665     _WKThumbnailView *thumbnailView = _data->_thumbnailView;
3666     ASSERT(thumbnailView);
3667
3668     if (thumbnailView._waitingForSnapshot && self.window)
3669         [self _reparentLayerTreeInThumbnailView];
3670 }
3671
3672 - (void)_reparentLayerTreeInThumbnailView
3673 {
3674     _data->_thumbnailView._thumbnailLayer = _data->_rootLayer.get();
3675 }
3676 #endif // WK_API_ENABLED
3677
3678 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
3679
3680 - (void)_updateContentInsetsIfAutomatic
3681 {
3682     if (!self._automaticallyAdjustsContentInsets)
3683         return;
3684
3685     if ((self.window.styleMask & NSFullSizeContentViewWindowMask) && !self.window.titlebarAppearsTransparent && ![self enclosingScrollView]) {
3686         NSRect contentLayoutRect = [self convertRect:self.window.contentLayoutRect fromView:nil];
3687         CGFloat newTopContentInset = NSMaxY(contentLayoutRect) - NSHeight(contentLayoutRect);
3688         if (self._topContentInset != newTopContentInset)
3689             self._topContentInset = newTopContentInset;
3690     } else
3691         self._topContentInset = 0;
3692 }
3693
3694 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
3695 {
3696     if (context == keyValueObservingContext) {
3697         if ([keyPath isEqualToString:@"contentLayoutRect"] || [keyPath isEqualToString:@"titlebarAppearsTransparent"])
3698             [self _updateContentInsetsIfAutomatic];
3699         return;
3700     }
3701
3702     [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
3703 }
3704
3705 #endif
3706
3707 - (void)_didFirstVisuallyNonEmptyLayoutForMainFrame
3708 {
3709     if (_data->_gestureController)
3710         _data->_gestureController->didFirstVisuallyNonEmptyLayoutForMainFrame();
3711 }
3712
3713 - (void)_didFinishLoadForMainFrame
3714 {
3715     if (_data->_gestureController)
3716         _data->_gestureController->didFinishLoadForMainFrame();
3717 }
3718
3719 - (void)_didSameDocumentNavigationForMainFrame:(SameDocumentNavigationType)type
3720 {
3721     if (_data->_gestureController)
3722         _data->_gestureController->didSameDocumentNavigationForMainFrame(type);
3723 }
3724
3725 - (void)_removeNavigationGestureSnapshot
3726 {
3727     if (_data->_gestureController)
3728         _data->_gestureController->removeSwipeSnapshot();
3729 }
3730
3731 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
3732
3733 - (void)prepareForMenu:(NSMenu *)menu withEvent:(NSEvent *)event
3734 {
3735     if (_data->_ignoresNonWheelEvents) {
3736         [menu cancelTracking];
3737         return;
3738     }
3739
3740     [_data->_actionMenuController prepareForMenu:menu withEvent:event];
3741 }
3742
3743 - (void)willOpenMenu:(NSMenu *)menu withEvent:(NSEvent *)event
3744 {
3745     if (_data->_ignoresNonWheelEvents) {
3746         [menu cancelTracking];
3747         return;
3748     }
3749
3750     [_data->_actionMenuController willOpenMenu:menu withEvent:event];
3751 }
3752
3753 - (void)didCloseMenu:(NSMenu *)menu withEvent:(NSEvent *)event
3754 {
3755     if (_data->_ignoresNonWheelEvents) {
3756         [menu cancelTracking];
3757         return;
3758     }
3759
3760     [_data->_actionMenuController didCloseMenu:menu withEvent:event];
3761 }
3762
3763 - (void)_didPerformActionMenuHitTest:(const ActionMenuHitTestResult&)hitTestResult forImmediateAction:(BOOL)forImmediateAction userData:(API::Object*)userData
3764 {
3765     if (forImmediateAction)
3766         [_data->_immediateActionController didPerformActionMenuHitTest:hitTestResult userData:userData];
3767     else
3768         [_data->_actionMenuController didPerformActionMenuHitTest:hitTestResult userData:userData];
3769 }
3770
3771 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
3772
3773 @end
3774
3775 @implementation WKView (Private)
3776
3777 - (void)saveBackForwardSnapshotForCurrentItem
3778 {
3779     _data->_page->recordNavigationSnapshot();
3780 }
3781
3782 - (void)saveBackForwardSnapshotForItem:(WKBackForwardListItemRef)item
3783 {
3784     _data->_page->recordNavigationSnapshot(*toImpl(item));
3785 }
3786
3787 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef
3788 {
3789     return [self initWithFrame:frame contextRef:contextRef pageGroupRef:pageGroupRef relatedToPage:nil];
3790 }
3791
3792 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef relatedToPage:(WKPageRef)relatedPage
3793 {
3794     WebPageConfiguration webPageConfiguration;
3795     webPageConfiguration.pageGroup = toImpl(pageGroupRef);
3796     webPageConfiguration.relatedPage = toImpl(relatedPage);
3797
3798     return [self initWithFrame:frame processPool:*toImpl(contextRef) configuration:webPageConfiguration webView:nil];
3799 }
3800
3801 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
3802 - (BOOL)wantsUpdateLayer
3803 {
3804     return YES;
3805 }
3806
3807 - (void)updateLayer
3808 {
3809     if ([self drawsBackground] && ![self drawsTransparentBackground])
3810         self.layer.backgroundColor = CGColorGetConstantColor(kCGColorWhite);
3811     else
3812         self.layer.backgroundColor = CGColorGetConstantColor(kCGColorClear);
3813
3814     // If asynchronous geometry updates have been sent by forceAsyncDrawingAreaSizeUpdate,
3815     // then subsequent calls to setFrameSize should not result in us waiting for the did
3816     // udpate response if setFrameSize is called.
3817     if ([self frameSizeUpdatesDisabled])
3818         return;
3819
3820     if (DrawingAreaProxy* drawingArea = _data->_page->drawingArea())
3821         drawingArea->waitForPossibleGeometryUpdate();
3822 }
3823 #endif
3824
3825 - (WKPageRef)pageRef
3826 {
3827     return toAPI(_data->_page.get());
3828 }
3829
3830 - (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef
3831 {
3832     // PDF documents are already paginated, so we can't change them to add headers and footers.
3833     return !toImpl(frameRef)->isDisplayingPDFDocument();
3834 }
3835
3836 - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef
3837 {
3838     LOG(View, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data());
3839
3840     // FIXME: If the frame cannot be printed (e.g. if it contains an encrypted PDF that disallows
3841     // printing), this function should return nil.
3842     RetainPtr<WKPrintingView> printingView = adoptNS([[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef) view:self]);
3843     // NSPrintOperation takes ownership of the view.
3844     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get() printInfo:printInfo];
3845     [printOperation setCanSpawnSeparateThread:YES];
3846     [printOperation setJobTitle:toImpl(frameRef)->title()];
3847     printingView->_printOperation = printOperation;
3848     return printOperation;
3849 }
3850
3851 - (void)setFrame:(NSRect)rect andScrollBy:(NSSize)offset
3852 {
3853     ASSERT(NSEqualSizes(_data->_resizeScrollOffset, NSZeroSize));
3854
3855     _data->_resizeScrollOffset = offset;
3856     [self setFrame:rect];
3857 }
3858
3859 - (void)disableFrameSizeUpdates
3860 {
3861     _data->_frameSizeUpdatesDisabledCount++;
3862 }
3863
3864 - (void)enableFrameSizeUpdates
3865 {
3866     if (!_data->_frameSizeUpdatesDisabledCount)
3867         return;
3868     
3869     if (!(--_data->_frameSizeUpdatesDisabledCount)) {
3870         if (_data->_clipsToVisibleRect)
3871             [self _updateViewExposedRect];
3872         [self _setDrawingAreaSize:[self frame].size];
3873     }
3874 }
3875
3876 - (BOOL)frameSizeUpdatesDisabled
3877 {
3878     return _data->_frameSizeUpdatesDisabledCount > 0;
3879 }
3880
3881 + (void)hideWordDefinitionWindow
3882 {
3883     if (!getLULookupDefinitionModuleClass())
3884         return;
3885     [getLULookupDefinitionModuleClass() hideDefinition];
3886 }
3887
3888 - (CGFloat)minimumLayoutWidth
3889 {
3890     static BOOL loggedDeprecationWarning = NO;
3891
3892     if (!loggedDeprecationWarning) {
3893         NSLog(@"Please use minimumSizeForAutoLayout instead of minimumLayoutWidth.");
3894         loggedDeprecationWarning = YES;
3895     }
3896
3897     return self.minimumSizeForAutoLayout.width;
3898 }
3899
3900 - (void)setMinimumLayoutWidth:(CGFloat)minimumLayoutWidth
3901 {
3902     static BOOL loggedDeprecationWarning = NO;
3903
3904     if (!loggedDeprecationWarning) {
3905         NSLog(@"Please use setMinimumSizeForAutoLayout: instead of setMinimumLayoutWidth:.");
3906         loggedDeprecationWarning = YES;
3907     }
3908
3909     [self setMinimumWidthForAutoLayout:minimumLayoutWidth];
3910 }
3911
3912 - (CGFloat)minimumWidthForAutoLayout
3913 {
3914     return self.minimumSizeForAutoLayout.width;
3915 }
3916
3917 - (void)setMinimumWidthForAutoLayout:(CGFloat)minimumLayoutWidth
3918 {
3919     self.minimumSizeForAutoLayout = NSMakeSize(minimumLayoutWidth, self.minimumSizeForAutoLayout.height);
3920 }
3921
3922 - (NSSize)minimumSizeForAutoLayout
3923 {
3924     return _data->_page->minimumLayoutSize();
3925 }
3926
3927 - (void)setMinimumSizeForAutoLayout:(NSSize)minimumSizeForAutoLayout
3928 {
3929     BOOL expandsToFit = minimumSizeForAutoLayout.width > 0;
3930
3931     _data->_page->setMinimumLayoutSize(IntSize(minimumSizeForAutoLayout.width, minimumSizeForAutoLayout.height));
3932     _data->_page->setMainFrameIsScrollable(!expandsToFit);
3933
3934     [self setShouldClipToVisibleRect:expandsToFit];
3935 }
3936
3937 - (BOOL)shouldExpandToViewHeightForAutoLayout
3938 {
3939     return _data->_page->autoSizingShouldExpandToViewHeight();
3940 }
3941
3942 - (void)setShouldExpandToViewHeightForAutoLayout:(BOOL)shouldExpand
3943 {
3944     return _data->_page->setAutoSizingShouldExpandToViewHeight(shouldExpand);
3945 }
3946
3947 - (BOOL)shouldClipToVisibleRect
3948 {
3949     return _data->_clipsToVisibleRect;
3950 }
3951
3952 - (void)setShouldClipToVisibleRect:(BOOL)clipsToVisibleRect
3953 {
3954     _data->_clipsToVisibleRect = clipsToVisibleRect;
3955     [self _updateViewExposedRect];
3956 }
3957
3958 - (NSColor *)underlayColor
3959 {
3960     Color webColor = _data->_page->underlayColor();
3961     if (!webColor.isValid())
3962         return nil;
3963
3964     return nsColor(webColor);
3965 }
3966
3967 - (void)setUnderlayColor:(NSColor *)underlayColor
3968 {
3969     _data->_page->setUnderlayColor(colorFromNSColor(underlayColor));
3970 }
3971
3972 - (NSView *)fullScreenPlaceholderView
3973 {
3974 #if ENABLE(FULLSCREEN_API)
3975     if (_data->_fullScreenWindowController && [_data->_fullScreenWindowController isFullScreen])
3976         return [_data->_fullScreenWindowController webViewPlaceholder];
3977 #endif
3978     return nil;
3979 }
3980
3981 - (NSWindow *)createFullScreenWindow
3982 {
3983 #if ENABLE(FULLSCREEN_API)
3984 #if __MAC_OS_X_VERSION_MIN_REQUIRED <= 1080
3985     NSRect contentRect = NSZeroRect;
3986 #else
3987     NSRect contentRect = [[NSScreen mainScreen] frame];
3988 #endif
3989     return [[[WebCoreFullScreenWindow alloc] initWithContentRect:contentRect styleMask:(NSBorderlessWindowMask | NSResizableWindowMask) backing:NSBackingStoreBuffered defer:NO] autorelease];
3990 #else
3991     return nil;
3992 #endif
3993 }
3994
3995 // FIXME: All of these "DeferringViewInWindowChanges" methods should be able to be removed once clients are weaned off of them.
3996 - (void)beginDeferringViewInWindowChanges
3997 {
3998     if (_data->_shouldDeferViewInWindowChanges) {
3999         NSLog(@"beginDeferringViewInWindowChanges was called while already deferring view-in-window changes!");
4000         return;
4001     }
4002
4003     _data->_shouldDeferViewInWindowChanges = YES;
4004 }
4005
4006 - (void)endDeferringViewInWindowChanges
4007 {
4008     if (!_data->_shouldDeferViewInWindowChanges) {
4009         NSLog(@"endDeferringViewInWindowChanges was called without beginDeferringViewInWindowChanges!");
4010         return;
4011     }
4012
4013     _data->_shouldDeferViewInWindowChanges = NO;
4014
4015     if (_data->_viewInWindowChangeWasDeferred) {
4016         [self _dispatchSetTopContentInset];
4017         _data->_page->viewStateDidChange(ViewState::IsInWindow);
4018         _data->_viewInWindowChangeWasDeferred = NO;
4019     }
4020 }
4021
4022 - (void)endDeferringViewInWindowChangesSync
4023 {
4024     if (!_data->_shouldDeferViewInWindowChanges) {
4025         NSLog(@"endDeferringViewInWindowChangesSync was called without beginDeferringViewInWindowChanges!");
4026         return;
4027     }
4028
4029     _data->_shouldDeferViewInWindowChanges = NO;
4030
4031     if (_data->_viewInWindowChangeWasDeferred) {
4032         [self _dispatchSetTopContentInset];
4033         _data->_page->viewStateDidChange(ViewState::IsInWindow);
4034         _data->_viewInWindowChangeWasDeferred = NO;
4035     }
4036 }
4037
4038 - (void)_prepareForMoveToWindow:(NSWindow *)targetWindow withCompletionHandler:(void(^)(void))completionHandler
4039 {
4040     _data->_shouldDeferViewInWindowChanges = YES;
4041     [self viewWillMoveToWindow:targetWindow];
4042     _data->_targetWindowForMovePreparation = targetWindow;
4043     [self viewDidMoveToWindow];
4044
4045     _data->_shouldDeferViewInWindowChanges = NO;
4046
4047     _data->_page->installViewStateChangeCompletionHandler(^() {
4048         completionHandler();
4049         ASSERT(self.window == _data->_targetWindowForMovePreparation);
4050         _data->_targetWindowForMovePreparation = nil;
4051     });
4052
4053     [self _dispatchSetTopContentInset];
4054     _data->_page->viewStateDidChange(ViewState::IsInWindow, false, WebPageProxy::ViewStateChangeDispatchMode::Immediate);
4055     _data->_viewInWindowChangeWasDeferred = NO;
4056 }
4057
4058 - (BOOL)isDeferringViewInWindowChanges
4059 {
4060     return _data->_shouldDeferViewInWindowChanges;
4061 }
4062
4063 - (BOOL)windowOcclusionDetectionEnabled
4064 {
4065     return _data->_windowOcclusionDetectionEnabled;
4066 }
4067
4068 - (void)setWindowOcclusionDetectionEnabled:(BOOL)flag
4069 {
4070     _data->_windowOcclusionDetectionEnabled = flag;
4071 }
4072
4073 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
4074 {
4075     _data->_allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
4076     _data->_page->setShouldRecordNavigationSnapshots(allowsBackForwardNavigationGestures);
4077     _data->_page->setShouldUseImplicitRubberBandControl(allowsBackForwardNavigationGestures);
4078 }
4079
4080 - (BOOL)allowsBackForwardNavigationGestures
4081 {
4082     return _data->_allowsBackForwardNavigationGestures;
4083 }
4084
4085 - (void)_setIgnoresAllEvents:(BOOL)ignoresAllEvents
4086 {
4087     _data->_ignoresAllEvents = ignoresAllEvents;
4088     [self _setIgnoresNonWheelEvents:ignoresAllEvents];
4089 }
4090
4091 // Forward _setIgnoresNonWheelMouseEvents to _setIgnoresNonWheelEvents to avoid breaking existing clients.
4092 - (void)_setIgnoresNonWheelMouseEvents:(BOOL)ignoresNonWheelMouseEvents
4093 {
4094     [self _setIgnoresNonWheelEvents:ignoresNonWheelMouseEvents];
4095 }
4096
4097 - (void)_setIgnoresNonWheelEvents:(BOOL)ignoresNonWheelEvents
4098 {
4099     if (_data->_ignoresNonWheelEvents == ignoresNonWheelEvents)
4100         return;
4101
4102     _data->_ignoresNonWheelEvents = ignoresNonWheelEvents;
4103     _data->_page->setShouldDispatchFakeMouseMoveEvents(!ignoresNonWheelEvents);
4104
4105 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
4106     if (ignoresNonWheelEvents)
4107         [self removeGestureRecognizer:_data->_immediateActionGestureRecognizer.get()];
4108     else if (NSGestureRecognizer *immediateActionRecognizer = _data->_immediateActionGestureRecognizer.get())
4109         [self addGestureRecognizer:immediateActionRecognizer];
4110 #endif
4111 }
4112
4113 - (BOOL)_ignoresNonWheelEvents
4114 {
4115     return _data->_ignoresNonWheelEvents;
4116 }
4117
4118 - (BOOL)_ignoresAllEvents
4119 {
4120     return _data->_ignoresAllEvents;
4121 }
4122