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