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