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