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