2 * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
31 #if USE(DICTATION_ALTERNATIVES)
32 #import <AppKit/NSTextAlternatives.h>
33 #import <AppKit/NSAttributedString.h>
36 #import "APIHistoryClient.h"
37 #import "AttributedString.h"
38 #import "ColorSpaceData.h"
39 #import "DataReference.h"
40 #import "EditingRange.h"
41 #import "EditorState.h"
42 #import "FindIndicator.h"
43 #import "FindIndicatorWindow.h"
44 #import "LayerTreeContext.h"
46 #import "NativeWebKeyboardEvent.h"
47 #import "NativeWebMouseEvent.h"
48 #import "NativeWebWheelEvent.h"
49 #import "PageClientImpl.h"
50 #import "PasteboardTypes.h"
51 #import "RemoteLayerTreeDrawingAreaProxy.h"
52 #import "StringUtilities.h"
53 #import "TextChecker.h"
54 #import "TextCheckerState.h"
55 #import "TiledCoreAnimationDrawingAreaProxy.h"
56 #import "ViewGestureController.h"
57 #import "ViewSnapshotStore.h"
59 #import "WKFullScreenWindowController.h"
60 #import "WKPrintingView.h"
61 #import "WKProcessPoolInternal.h"
62 #import "WKStringCF.h"
63 #import "WKTextInputWindowController.h"
64 #import "WKViewInternal.h"
65 #import "WKViewPrivate.h"
66 #import "WebBackForwardList.h"
67 #import "WebContext.h"
68 #import "WebEventFactory.h"
69 #import "WebKit2Initialize.h"
71 #import "WebPageGroup.h"
72 #import "WebPageProxy.h"
73 #import "WebPreferences.h"
74 #import "WebProcessProxy.h"
75 #import "WebSystemInterface.h"
76 #import "_WKThumbnailViewInternal.h"
77 #import <QuartzCore/QuartzCore.h>
78 #import <WebCore/AXObjectCache.h>
79 #import <WebCore/ColorMac.h>
80 #import <WebCore/DragController.h>
81 #import <WebCore/DragData.h>
82 #import <WebCore/FloatRect.h>
83 #import <WebCore/Image.h>
84 #import <WebCore/IntRect.h>
85 #import <WebCore/FileSystem.h>
86 #import <WebCore/KeyboardEvent.h>
87 #import <WebCore/LocalizedStrings.h>
88 #import <WebCore/PlatformEventFactoryMac.h>
89 #import <WebCore/PlatformScreen.h>
90 #import <WebCore/Region.h>
91 #import <WebCore/SharedBuffer.h>
92 #import <WebCore/TextAlternativeWithRange.h>
93 #import <WebCore/TextUndoInsertionMarkupMac.h>
94 #import <WebCore/WebActionDisablingCALayerDelegate.h>
95 #import <WebCore/WebCoreCALayerExtras.h>
96 #import <WebCore/WebCoreFullScreenPlaceholderView.h>
97 #import <WebCore/WebCoreFullScreenWindow.h>
98 #import <WebCore/WebCoreNSStringExtras.h>
99 #import <WebKitSystemInterface.h>
101 #import <wtf/RefPtr.h>
102 #import <wtf/RetainPtr.h>
103 #import <wtf/RunLoop.h>
106 #import "WKBrowsingContextControllerInternal.h"
107 #import "WKBrowsingContextGroupPrivate.h"
108 #import "WKProcessGroupPrivate.h"
110 @interface NSApplication (WKNSApplicationDetails)
111 - (void)speakString:(NSString *)string;
112 - (void)_setCurrentEvent:(NSEvent *)event;
115 @interface NSWindow (WKNSWindowDetails)
116 - (NSRect)_intersectBottomCornersWithRect:(NSRect)viewRect;
117 - (void)_maskRoundedBottomCorners:(NSRect)clipRect;
120 #if USE(ASYNC_NSTEXTINPUTCLIENT)
121 @interface NSTextInputContext (WKNSTextInputContextDetails)
122 - (void)handleEvent:(NSEvent *)theEvent completionHandler:(void(^)(BOOL handled))completionHandler;
123 - (void)handleEventByInputMethod:(NSEvent *)theEvent completionHandler:(void(^)(BOOL handled))completionHandler;
124 - (BOOL)handleEventByKeyboardLayout:(NSEvent *)theEvent;
128 #if defined(__has_include) && __has_include(<CoreGraphics/CoreGraphicsPrivate.h>)
129 #import <CoreGraphics/CoreGraphicsPrivate.h>
133 typedef uint32_t CGSConnectionID;
134 typedef uint32_t CGSWindowID;
135 CGSConnectionID CGSMainConnectionID(void);
136 CGError CGSGetScreenRectForWindow(CGSConnectionID cid, CGSWindowID wid, CGRect *rect);
139 using namespace WebKit;
140 using namespace WebCore;
144 typedef id <NSValidatedUserInterfaceItem> ValidationItem;
145 typedef Vector<RetainPtr<ValidationItem>> ValidationVector;
146 typedef HashMap<String, ValidationVector> ValidationMap;
150 #if !USE(ASYNC_NSTEXTINPUTCLIENT)
151 struct WKViewInterpretKeyEventsParameters {
152 bool eventInterpretationHadSideEffects;
154 bool executingSavedKeypressCommands;
155 Vector<KeypressCommand>* commands;
159 @interface WKViewData : NSObject {
161 std::unique_ptr<PageClientImpl> _pageClient;
162 RefPtr<WebPageProxy> _page;
165 RetainPtr<WKBrowsingContextController> _browsingContextController;
169 NSToolTipTag _lastToolTipTag;
170 id _trackingRectOwner;
171 void* _trackingRectUserData;
173 RetainPtr<NSView> _layerHostingView;
175 RetainPtr<id> _remoteAccessibilityChild;
177 // For asynchronous validation.
178 ValidationMap _validationMap;
180 std::unique_ptr<FindIndicatorWindow> _findIndicatorWindow;
182 // We keep here the event when resending it to
183 // the application to distinguish the case of a new event from one
184 // that has been already sent to WebCore.
185 RetainPtr<NSEvent> _keyDownEventBeingResent;
186 #if USE(ASYNC_NSTEXTINPUTCLIENT)
187 Vector<KeypressCommand>* _collectedKeypressCommands;
189 WKViewInterpretKeyEventsParameters* _interpretKeyEventsParameters;
192 NSSize _resizeScrollOffset;
194 // The identifier of the plug-in we want to send complex text input to, or 0 if there is none.
195 uint64_t _pluginComplexTextInputIdentifier;
197 // The state of complex text input for the plug-in.
198 PluginComplexTextInputState _pluginComplexTextInputState;
200 bool _inBecomeFirstResponder;
201 bool _inResignFirstResponder;
202 NSEvent *_mouseDownEvent;
203 BOOL _ignoringMouseDraggedEvents;
205 id _flagsChangedEventMonitor;
207 #if ENABLE(FULLSCREEN_API)
208 RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
211 BOOL _hasSpellCheckerDocumentTag;
212 NSInteger _spellCheckerDocumentTag;
214 BOOL _inSecureInputState;
216 NSRect _windowBottomCornerIntersectionRect;
218 unsigned _frameSizeUpdatesDisabledCount;
219 BOOL _shouldDeferViewInWindowChanges;
221 BOOL _viewInWindowChangeWasDeferred;
223 BOOL _needsViewFrameInWindowCoordinates;
224 BOOL _didScheduleWindowAndViewFrameUpdate;
226 RetainPtr<NSColorSpace> _colorSpace;
228 RefPtr<WebCore::Image> _promisedImage;
229 String _promisedFilename;
232 NSSize _intrinsicContentSize;
233 BOOL _clipsToVisibleRect;
234 NSRect _contentPreparationRect;
235 BOOL _useContentPreparationRectForVisibleRect;
236 BOOL _windowOcclusionDetectionEnabled;
238 std::unique_ptr<ViewGestureController> _gestureController;
239 BOOL _allowsMagnification;
240 BOOL _allowsBackForwardNavigationGestures;
242 RetainPtr<CALayer> _rootLayer;
244 BOOL _didScheduleSetTopContentInset;
245 CGFloat _topContentInset;
247 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
248 BOOL _automaticallyAdjustsContentInsets;
252 _WKThumbnailView *_thumbnailView;
258 @implementation WKViewData
261 @interface WKResponderChainSink : NSResponder {
262 NSResponder *_lastResponderInChain;
263 bool _didReceiveUnhandledCommand;
265 - (id)initWithResponderChain:(NSResponder *)chain;
267 - (bool)didReceiveUnhandledCommand;
270 @interface WKFlippedView : NSView
273 @implementation WKFlippedView
282 @implementation WKView
286 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup
288 return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:nil];
291 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup relatedToView:(WKView *)relatedView
293 return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:relatedView ? toAPI(relatedView->_data->_page.get()) : nil];
296 #endif // WK_API_ENABLED
300 _data->_page->close();
303 ASSERT(!_data->_thumbnailView);
305 ASSERT(!_data->_inSecureInputState);
310 NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
311 [workspaceNotificationCenter removeObserver:self name:NSWorkspaceActiveSpaceDidChangeNotification object:nil];
313 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillTerminateNotification object:NSApp];
315 WebContext::statistics().wkViewCount--;
322 - (WKBrowsingContextController *)browsingContextController
324 if (!_data->_browsingContextController)
325 _data->_browsingContextController = adoptNS([[WKBrowsingContextController alloc] _initWithPageRef:toAPI(_data->_page.get())]);
327 return _data->_browsingContextController.get();
330 #endif // WK_API_ENABLED
332 - (void)setDrawsBackground:(BOOL)drawsBackground
334 _data->_page->setDrawsBackground(drawsBackground);
337 - (BOOL)drawsBackground
339 return _data->_page->drawsBackground();
342 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
344 _data->_page->setDrawsTransparentBackground(drawsTransparentBackground);
347 - (BOOL)drawsTransparentBackground
349 return _data->_page->drawsTransparentBackground();
352 - (BOOL)acceptsFirstResponder
357 - (BOOL)becomeFirstResponder
359 NSSelectionDirection direction = [[self window] keyViewSelectionDirection];
361 _data->_inBecomeFirstResponder = true;
363 [self _updateSecureInputState];
364 _data->_page->viewStateDidChange(ViewState::IsFocused);
366 _data->_inBecomeFirstResponder = false;
368 if (direction != NSDirectSelection) {
369 NSEvent *event = [NSApp currentEvent];
370 NSEvent *keyboardEvent = nil;
371 if ([event type] == NSKeyDown || [event type] == NSKeyUp)
372 keyboardEvent = event;
373 _data->_page->setInitialFocus(direction == NSSelectingNext, keyboardEvent != nil, NativeWebKeyboardEvent(keyboardEvent, false, Vector<KeypressCommand>()));
378 - (BOOL)resignFirstResponder
380 _data->_inResignFirstResponder = true;
382 #if USE(ASYNC_NSTEXTINPUTCLIENT)
383 _data->_page->confirmCompositionAsync();
385 if (_data->_page->editorState().hasComposition && !_data->_page->editorState().shouldIgnoreCompositionSelectionChange)
386 _data->_page->cancelComposition();
389 [self _notifyInputContextAboutDiscardedComposition];
391 [self _resetSecureInputState];
393 if (!_data->_page->maintainsInactiveSelection())
394 _data->_page->clearSelection();
396 _data->_page->viewStateDidChange(ViewState::IsFocused);
398 _data->_inResignFirstResponder = false;
403 - (void)viewWillStartLiveResize
405 _data->_page->viewWillStartLiveResize();
408 - (void)viewDidEndLiveResize
410 _data->_page->viewWillEndLiveResize();
418 - (NSSize)intrinsicContentSize
420 return _data->_intrinsicContentSize;
423 - (void)prepareContentInRect:(NSRect)rect
425 _data->_contentPreparationRect = rect;
426 _data->_useContentPreparationRectForVisibleRect = YES;
428 [self _updateViewExposedRect];
431 - (void)_updateViewExposedRect
433 NSRect exposedRect = [self visibleRect];
435 if (_data->_useContentPreparationRectForVisibleRect)
436 exposedRect = NSUnionRect(_data->_contentPreparationRect, exposedRect);
438 if (auto drawingArea = _data->_page->drawingArea())
439 drawingArea->setExposedRect(_data->_clipsToVisibleRect ? FloatRect(exposedRect) : FloatRect::infiniteRect());
442 - (void)setFrameSize:(NSSize)size
444 [super setFrameSize:size];
446 if (![self frameSizeUpdatesDisabled]) {
447 if (_data->_clipsToVisibleRect)
448 [self _updateViewExposedRect];
449 [self _setDrawingAreaSize:size];
453 - (void)_updateWindowAndViewFrames
455 if (_data->_clipsToVisibleRect)
456 [self _updateViewExposedRect];
458 if (_data->_didScheduleWindowAndViewFrameUpdate)
461 _data->_didScheduleWindowAndViewFrameUpdate = YES;
463 dispatch_async(dispatch_get_main_queue(), ^{
464 _data->_didScheduleWindowAndViewFrameUpdate = NO;
466 NSRect viewFrameInWindowCoordinates = NSZeroRect;
467 NSPoint accessibilityPosition = NSZeroPoint;
469 if (_data->_needsViewFrameInWindowCoordinates)
470 viewFrameInWindowCoordinates = [self convertRect:self.frame toView:nil];
472 #pragma clang diagnostic push
473 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
474 if (WebCore::AXObjectCache::accessibilityEnabled())
475 accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue];
476 #pragma clang diagnostic pop
478 _data->_page->windowAndViewFramesChanged(viewFrameInWindowCoordinates, accessibilityPosition);
484 // Hide the find indicator.
485 _data->_findIndicatorWindow = nullptr;
487 // Update the view frame.
489 [self _updateWindowAndViewFrames];
491 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
492 [self _updateContentInsetsIfAutomatic];
498 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState
500 _data->_pluginComplexTextInputState = pluginComplexTextInputState;
502 if (_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled)
505 // Send back an empty string to the plug-in. This will disable text input.
506 _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, String());
509 typedef HashMap<SEL, String> SelectorNameMap;
511 // Map selectors into Editor command names.
512 // This is not needed for any selectors that have the same name as the Editor command.
513 static const SelectorNameMap* createSelectorExceptionMap()
515 SelectorNameMap* map = new HashMap<SEL, String>;
517 map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
518 map->add(@selector(insertParagraphSeparator:), "InsertNewline");
519 map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
520 map->add(@selector(pageDown:), "MovePageDown");
521 map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
522 map->add(@selector(pageUp:), "MovePageUp");
523 map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
524 map->add(@selector(scrollPageDown:), "ScrollPageForward");
525 map->add(@selector(scrollPageUp:), "ScrollPageBackward");
530 static String commandNameForSelector(SEL selector)
532 // Check the exception map first.
533 static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
534 SelectorNameMap::const_iterator it = exceptionMap->find(selector);
535 if (it != exceptionMap->end())
538 // Remove the trailing colon.
539 // No need to capitalize the command name since Editor command names are
540 // not case sensitive.
541 const char* selectorName = sel_getName(selector);
542 size_t selectorNameLength = strlen(selectorName);
543 if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
545 return String(selectorName, selectorNameLength - 1);
550 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
552 WEBCORE_COMMAND(alignCenter)
553 WEBCORE_COMMAND(alignJustified)
554 WEBCORE_COMMAND(alignLeft)
555 WEBCORE_COMMAND(alignRight)
556 WEBCORE_COMMAND(copy)
558 WEBCORE_COMMAND(delete)
559 WEBCORE_COMMAND(deleteBackward)
560 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
561 WEBCORE_COMMAND(deleteForward)
562 WEBCORE_COMMAND(deleteToBeginningOfLine)
563 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
564 WEBCORE_COMMAND(deleteToEndOfLine)
565 WEBCORE_COMMAND(deleteToEndOfParagraph)
566 WEBCORE_COMMAND(deleteToMark)
567 WEBCORE_COMMAND(deleteWordBackward)
568 WEBCORE_COMMAND(deleteWordForward)
569 WEBCORE_COMMAND(ignoreSpelling)
570 WEBCORE_COMMAND(indent)
571 WEBCORE_COMMAND(insertBacktab)
572 WEBCORE_COMMAND(insertLineBreak)
573 WEBCORE_COMMAND(insertNewline)
574 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
575 WEBCORE_COMMAND(insertParagraphSeparator)
576 WEBCORE_COMMAND(insertTab)
577 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
578 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
579 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
580 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
581 WEBCORE_COMMAND(moveBackward)
582 WEBCORE_COMMAND(moveBackwardAndModifySelection)
583 WEBCORE_COMMAND(moveDown)
584 WEBCORE_COMMAND(moveDownAndModifySelection)
585 WEBCORE_COMMAND(moveForward)
586 WEBCORE_COMMAND(moveForwardAndModifySelection)
587 WEBCORE_COMMAND(moveLeft)
588 WEBCORE_COMMAND(moveLeftAndModifySelection)
589 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
590 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
591 WEBCORE_COMMAND(moveRight)
592 WEBCORE_COMMAND(moveRightAndModifySelection)
593 WEBCORE_COMMAND(moveToBeginningOfDocument)
594 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
595 WEBCORE_COMMAND(moveToBeginningOfLine)
596 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
597 WEBCORE_COMMAND(moveToBeginningOfParagraph)
598 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
599 WEBCORE_COMMAND(moveToBeginningOfSentence)
600 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
601 WEBCORE_COMMAND(moveToEndOfDocument)
602 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
603 WEBCORE_COMMAND(moveToEndOfLine)
604 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
605 WEBCORE_COMMAND(moveToEndOfParagraph)
606 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
607 WEBCORE_COMMAND(moveToEndOfSentence)
608 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
609 WEBCORE_COMMAND(moveToLeftEndOfLine)
610 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
611 WEBCORE_COMMAND(moveToRightEndOfLine)
612 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
613 WEBCORE_COMMAND(moveUp)
614 WEBCORE_COMMAND(moveUpAndModifySelection)
615 WEBCORE_COMMAND(moveWordBackward)
616 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
617 WEBCORE_COMMAND(moveWordForward)
618 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
619 WEBCORE_COMMAND(moveWordLeft)
620 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
621 WEBCORE_COMMAND(moveWordRight)
622 WEBCORE_COMMAND(moveWordRightAndModifySelection)
623 WEBCORE_COMMAND(outdent)
624 WEBCORE_COMMAND(pageDown)
625 WEBCORE_COMMAND(pageDownAndModifySelection)
626 WEBCORE_COMMAND(pageUp)
627 WEBCORE_COMMAND(pageUpAndModifySelection)
628 WEBCORE_COMMAND(paste)
629 WEBCORE_COMMAND(pasteAsPlainText)
630 WEBCORE_COMMAND(scrollPageDown)
631 WEBCORE_COMMAND(scrollPageUp)
632 WEBCORE_COMMAND(scrollLineDown)
633 WEBCORE_COMMAND(scrollLineUp)
634 WEBCORE_COMMAND(scrollToBeginningOfDocument)
635 WEBCORE_COMMAND(scrollToEndOfDocument)
636 WEBCORE_COMMAND(selectAll)
637 WEBCORE_COMMAND(selectLine)
638 WEBCORE_COMMAND(selectParagraph)
639 WEBCORE_COMMAND(selectSentence)
640 WEBCORE_COMMAND(selectToMark)
641 WEBCORE_COMMAND(selectWord)
642 WEBCORE_COMMAND(setMark)
643 WEBCORE_COMMAND(subscript)
644 WEBCORE_COMMAND(superscript)
645 WEBCORE_COMMAND(swapWithMark)
646 WEBCORE_COMMAND(takeFindStringFromSelection)
647 WEBCORE_COMMAND(transpose)
648 WEBCORE_COMMAND(underline)
649 WEBCORE_COMMAND(unscript)
650 WEBCORE_COMMAND(yank)
651 WEBCORE_COMMAND(yankAndSelect)
653 #undef WEBCORE_COMMAND
655 // This method is needed to support Mac OS X services.
657 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
659 size_t numTypes = [types count];
660 [pasteboard declareTypes:types owner:nil];
661 for (size_t i = 0; i < numTypes; ++i) {
662 if ([[types objectAtIndex:i] isEqualTo:NSStringPboardType])
663 [pasteboard setString:_data->_page->stringSelectionForPasteboard() forType:NSStringPboardType];
665 RefPtr<SharedBuffer> buffer = _data->_page->dataSelectionForPasteboard([types objectAtIndex:i]);
666 [pasteboard setData:buffer ? buffer->createNSData().get() : nil forType:[types objectAtIndex:i]];
672 - (void)centerSelectionInVisibleArea:(id)sender
674 _data->_page->centerSelectionInVisibleArea();
677 // This method is needed to support Mac OS X services.
679 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
681 EditorState editorState = _data->_page->editorState();
682 BOOL isValidSendType = NO;
684 if (sendType && !editorState.selectionIsNone) {
685 if (editorState.isInPlugin)
686 isValidSendType = [sendType isEqualToString:NSStringPboardType];
688 isValidSendType = [PasteboardTypes::forSelection() containsObject:sendType];
691 BOOL isValidReturnType = NO;
693 isValidReturnType = YES;
694 else if ([PasteboardTypes::forEditing() containsObject:returnType] && editorState.isContentEditable) {
695 // We can insert strings in any editable context. We can insert other types, like images, only in rich edit contexts.
696 isValidReturnType = editorState.isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType];
698 if (isValidSendType && isValidReturnType)
700 return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
703 // This method is needed to support Mac OS X services.
705 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
707 return _data->_page->readSelectionFromPasteboard([pasteboard name]);
712 When possible, editing-related methods should be implemented in WebCore with the
713 EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing
714 individual methods here with Mac-specific code.
716 Editing-related methods still unimplemented that are implemented in WebKit1:
718 - (void)capitalizeWord:(id)sender;
719 - (void)changeFont:(id)sender;
720 - (void)complete:(id)sender;
721 - (void)copyFont:(id)sender;
722 - (void)lowercaseWord:(id)sender;
723 - (void)makeBaseWritingDirectionLeftToRight:(id)sender;
724 - (void)makeBaseWritingDirectionNatural:(id)sender;
725 - (void)makeBaseWritingDirectionRightToLeft:(id)sender;
726 - (void)pasteFont:(id)sender;
727 - (void)scrollLineDown:(id)sender;
728 - (void)scrollLineUp:(id)sender;
729 - (void)showGuessPanel:(id)sender;
730 - (void)uppercaseWord:(id)sender;
732 Some other editing-related methods still unimplemented:
734 - (void)changeCaseOfLetter:(id)sender;
735 - (void)copyRuler:(id)sender;
736 - (void)insertContainerBreak:(id)sender;
737 - (void)insertDoubleQuoteIgnoringSubstitution:(id)sender;
738 - (void)insertSingleQuoteIgnoringSubstitution:(id)sender;
739 - (void)pasteRuler:(id)sender;
740 - (void)toggleRuler:(id)sender;
741 - (void)transposeWords:(id)sender;
745 // Menu items validation
747 static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item)
749 if (![(NSObject *)item isKindOfClass:[NSMenuItem class]])
751 return (NSMenuItem *)item;
754 static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item)
756 if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]])
758 return (NSToolbarItem *)item;
761 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
763 SEL action = [item action];
765 if (action == @selector(showGuessPanel:)) {
766 if (NSMenuItem *menuItem = ::menuItem(item))
767 [menuItem setTitle:contextMenuItemTagShowSpellingPanel(![[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible])];
768 return _data->_page->editorState().isContentEditable;
771 if (action == @selector(checkSpelling:) || action == @selector(changeSpelling:))
772 return _data->_page->editorState().isContentEditable;
774 if (action == @selector(toggleContinuousSpellChecking:)) {
775 bool enabled = TextChecker::isContinuousSpellCheckingAllowed();
776 bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled;
777 [menuItem(item) setState:checked ? NSOnState : NSOffState];
781 if (action == @selector(toggleGrammarChecking:)) {
782 bool checked = TextChecker::state().isGrammarCheckingEnabled;
783 [menuItem(item) setState:checked ? NSOnState : NSOffState];
787 if (action == @selector(toggleAutomaticSpellingCorrection:)) {
788 bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled;
789 [menuItem(item) setState:checked ? NSOnState : NSOffState];
790 return _data->_page->editorState().isContentEditable;
793 if (action == @selector(orderFrontSubstitutionsPanel:)) {
794 if (NSMenuItem *menuItem = ::menuItem(item))
795 [menuItem setTitle:contextMenuItemTagShowSubstitutions(![[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible])];
796 return _data->_page->editorState().isContentEditable;
799 if (action == @selector(toggleSmartInsertDelete:)) {
800 bool checked = _data->_page->isSmartInsertDeleteEnabled();
801 [menuItem(item) setState:checked ? NSOnState : NSOffState];
802 return _data->_page->editorState().isContentEditable;
805 if (action == @selector(toggleAutomaticQuoteSubstitution:)) {
806 bool checked = TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
807 [menuItem(item) setState:checked ? NSOnState : NSOffState];
808 return _data->_page->editorState().isContentEditable;
811 if (action == @selector(toggleAutomaticDashSubstitution:)) {
812 bool checked = TextChecker::state().isAutomaticDashSubstitutionEnabled;
813 [menuItem(item) setState:checked ? NSOnState : NSOffState];
814 return _data->_page->editorState().isContentEditable;
817 if (action == @selector(toggleAutomaticLinkDetection:)) {
818 bool checked = TextChecker::state().isAutomaticLinkDetectionEnabled;
819 [menuItem(item) setState:checked ? NSOnState : NSOffState];
820 return _data->_page->editorState().isContentEditable;
823 if (action == @selector(toggleAutomaticTextReplacement:)) {
824 bool checked = TextChecker::state().isAutomaticTextReplacementEnabled;
825 [menuItem(item) setState:checked ? NSOnState : NSOffState];
826 return _data->_page->editorState().isContentEditable;
829 if (action == @selector(uppercaseWord:) || action == @selector(lowercaseWord:) || action == @selector(capitalizeWord:))
830 return _data->_page->editorState().selectionIsRange && _data->_page->editorState().isContentEditable;
832 if (action == @selector(stopSpeaking:))
833 return [NSApp isSpeaking];
835 // The centerSelectionInVisibleArea: selector is enabled if there's a selection range or if there's an insertion point in an editable area.
836 if (action == @selector(centerSelectionInVisibleArea:))
837 return _data->_page->editorState().selectionIsRange || (_data->_page->editorState().isContentEditable && !_data->_page->editorState().selectionIsNone);
839 // Next, handle editor commands. Start by returning YES for anything that is not an editor command.
840 // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized.
841 String commandName = commandNameForSelector([item action]);
842 if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName))
845 // Add this item to the vector of items for a given command that are awaiting validation.
846 ValidationMap::AddResult addResult = _data->_validationMap.add(commandName, ValidationVector());
847 addResult.iterator->value.append(item);
848 if (addResult.isNewEntry) {
849 // If we are not already awaiting validation for this command, start the asynchronous validation process.
850 // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
851 // we asked for the same command; there is no guarantee the answer is still valid.
852 _data->_page->validateCommand(commandName, [self](const String& commandName, bool isEnabled, int32_t state, CallbackBase::Error error) {
853 // If the process exits before the command can be validated, we'll be called back with an error.
854 if (error != CallbackBase::Error::None)
857 [self _setUserInterfaceItemState:commandName enabled:isEnabled state:state];
861 // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called.
862 // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment.
863 // But returning NO here would be worse; that would make keyboard commands such as command-C fail.
867 - (IBAction)startSpeaking:(id)sender
869 _data->_page->getSelectionOrContentsAsString([self](const String& string, CallbackBase::Error error) {
870 if (error != CallbackBase::Error::None)
875 [NSApp speakString:string];
879 - (IBAction)stopSpeaking:(id)sender
881 [NSApp stopSpeaking:sender];
884 - (IBAction)showGuessPanel:(id)sender
886 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
888 LOG_ERROR("No NSSpellChecker");
892 NSPanel *spellingPanel = [checker spellingPanel];
893 if ([spellingPanel isVisible]) {
894 [spellingPanel orderOut:sender];
898 _data->_page->advanceToNextMisspelling(true);
899 [spellingPanel orderFront:sender];
902 - (IBAction)checkSpelling:(id)sender
904 _data->_page->advanceToNextMisspelling(false);
907 - (void)changeSpelling:(id)sender
909 NSString *word = [[sender selectedCell] stringValue];
911 _data->_page->changeSpellingToWord(word);
914 - (IBAction)toggleContinuousSpellChecking:(id)sender
916 bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled;
917 TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled);
919 _data->_page->process().updateTextCheckerState();
922 - (BOOL)isGrammarCheckingEnabled
924 return TextChecker::state().isGrammarCheckingEnabled;
927 - (void)setGrammarCheckingEnabled:(BOOL)flag
929 if (static_cast<bool>(flag) == TextChecker::state().isGrammarCheckingEnabled)
932 TextChecker::setGrammarCheckingEnabled(flag);
933 _data->_page->process().updateTextCheckerState();
936 - (IBAction)toggleGrammarChecking:(id)sender
938 bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled;
939 TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled);
941 _data->_page->process().updateTextCheckerState();
944 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
946 TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
948 _data->_page->process().updateTextCheckerState();
951 - (void)orderFrontSubstitutionsPanel:(id)sender
953 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
955 LOG_ERROR("No NSSpellChecker");
959 NSPanel *substitutionsPanel = [checker substitutionsPanel];
960 if ([substitutionsPanel isVisible]) {
961 [substitutionsPanel orderOut:sender];
964 [substitutionsPanel orderFront:sender];
967 - (IBAction)toggleSmartInsertDelete:(id)sender
969 _data->_page->setSmartInsertDeleteEnabled(!_data->_page->isSmartInsertDeleteEnabled());
972 - (BOOL)isAutomaticQuoteSubstitutionEnabled
974 return TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
977 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
979 if (static_cast<bool>(flag) == TextChecker::state().isAutomaticQuoteSubstitutionEnabled)
982 TextChecker::setAutomaticQuoteSubstitutionEnabled(flag);
983 _data->_page->process().updateTextCheckerState();
986 - (void)toggleAutomaticQuoteSubstitution:(id)sender
988 TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled);
989 _data->_page->process().updateTextCheckerState();
992 - (BOOL)isAutomaticDashSubstitutionEnabled
994 return TextChecker::state().isAutomaticDashSubstitutionEnabled;
997 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
999 if (static_cast<bool>(flag) == TextChecker::state().isAutomaticDashSubstitutionEnabled)
1002 TextChecker::setAutomaticDashSubstitutionEnabled(flag);
1003 _data->_page->process().updateTextCheckerState();
1006 - (void)toggleAutomaticDashSubstitution:(id)sender
1008 TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled);
1009 _data->_page->process().updateTextCheckerState();
1012 - (BOOL)isAutomaticLinkDetectionEnabled
1014 return TextChecker::state().isAutomaticLinkDetectionEnabled;
1017 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
1019 if (static_cast<bool>(flag) == TextChecker::state().isAutomaticLinkDetectionEnabled)
1022 TextChecker::setAutomaticLinkDetectionEnabled(flag);
1023 _data->_page->process().updateTextCheckerState();
1026 - (void)toggleAutomaticLinkDetection:(id)sender
1028 TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled);
1029 _data->_page->process().updateTextCheckerState();
1032 - (BOOL)isAutomaticTextReplacementEnabled
1034 return TextChecker::state().isAutomaticTextReplacementEnabled;
1037 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
1039 if (static_cast<bool>(flag) == TextChecker::state().isAutomaticTextReplacementEnabled)
1042 TextChecker::setAutomaticTextReplacementEnabled(flag);
1043 _data->_page->process().updateTextCheckerState();
1046 - (void)toggleAutomaticTextReplacement:(id)sender
1048 TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled);
1049 _data->_page->process().updateTextCheckerState();
1052 - (void)uppercaseWord:(id)sender
1054 _data->_page->uppercaseWord();
1057 - (void)lowercaseWord:(id)sender
1059 _data->_page->lowercaseWord();
1062 - (void)capitalizeWord:(id)sender
1064 _data->_page->capitalizeWord();
1067 - (void)displayIfNeeded
1069 // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. In the meantime,
1070 // it is necessary to disable scren updates so we get a chance to redraw the corners before this
1071 // display is visible.
1072 NSWindow *window = [self window];
1073 BOOL shouldMaskWindow = window && !NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect);
1074 if (shouldMaskWindow)
1075 NSDisableScreenUpdates();
1077 [super displayIfNeeded];
1079 if (shouldMaskWindow) {
1080 [window _maskRoundedBottomCorners:_data->_windowBottomCornerIntersectionRect];
1081 NSEnableScreenUpdates();
1082 _data->_windowBottomCornerIntersectionRect = NSZeroRect;
1088 -(BOOL)shouldIgnoreMouseEvents
1090 // FIXME: This check is surprisingly specific. Are there any other cases where we need to block mouse events?
1091 // Do we actually need to in thumbnail view? And if we do, what about non-mouse events?
1093 if (_data->_thumbnailView)
1099 // Override this so that AppKit will send us arrow keys as key down events so we can
1100 // support them via the key bindings mechanism.
1101 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
1106 - (void)_setMouseDownEvent:(NSEvent *)event
1108 ASSERT(!event || [event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
1110 if (event == _data->_mouseDownEvent)
1113 [_data->_mouseDownEvent release];
1114 _data->_mouseDownEvent = [event retain];
1117 #if USE(ASYNC_NSTEXTINPUTCLIENT)
1118 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
1119 - (void)Selector:(NSEvent *)theEvent \
1121 if ([self shouldIgnoreMouseEvents]) \
1123 if (NSTextInputContext *context = [self inputContext]) { \
1124 [context handleEvent:theEvent completionHandler:^(BOOL handled) { \
1126 LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
1128 NativeWebMouseEvent webEvent(theEvent, self); \
1129 _data->_page->handleMouseEvent(webEvent); \
1134 NativeWebMouseEvent webEvent(theEvent, self); \
1135 _data->_page->handleMouseEvent(webEvent); \
1138 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
1139 - (void)Selector:(NSEvent *)theEvent \
1141 if ([self shouldIgnoreMouseEvents]) \
1143 if ([[self inputContext] handleEvent:theEvent]) { \
1144 LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
1147 NativeWebMouseEvent webEvent(theEvent, self); \
1148 _data->_page->handleMouseEvent(webEvent); \
1152 NATIVE_MOUSE_EVENT_HANDLER(mouseEntered)
1153 NATIVE_MOUSE_EVENT_HANDLER(mouseExited)
1154 NATIVE_MOUSE_EVENT_HANDLER(mouseMovedInternal)
1155 NATIVE_MOUSE_EVENT_HANDLER(mouseDownInternal)
1156 NATIVE_MOUSE_EVENT_HANDLER(mouseUpInternal)
1157 NATIVE_MOUSE_EVENT_HANDLER(mouseDraggedInternal)
1158 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDown)
1159 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDragged)
1160 NATIVE_MOUSE_EVENT_HANDLER(otherMouseMoved)
1161 NATIVE_MOUSE_EVENT_HANDLER(otherMouseUp)
1162 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDown)
1163 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDragged)
1164 NATIVE_MOUSE_EVENT_HANDLER(rightMouseUp)
1166 #undef NATIVE_MOUSE_EVENT_HANDLER
1168 - (void)_ensureGestureController
1170 if (_data->_gestureController)
1173 _data->_gestureController = std::make_unique<ViewGestureController>(*_data->_page);
1176 - (void)scrollWheel:(NSEvent *)event
1178 if ([self shouldIgnoreMouseEvents])
1181 if (_data->_allowsBackForwardNavigationGestures) {
1182 [self _ensureGestureController];
1183 if (_data->_gestureController->handleScrollWheelEvent(event))
1187 NativeWebWheelEvent webEvent = NativeWebWheelEvent(event, self);
1188 _data->_page->handleWheelEvent(webEvent);
1191 - (void)swipeWithEvent:(NSEvent *)event
1193 if ([self shouldIgnoreMouseEvents])
1196 if (!_data->_allowsBackForwardNavigationGestures) {
1197 [super swipeWithEvent:event];
1201 if (event.deltaX > 0.0)
1202 _data->_page->goBack();
1203 else if (event.deltaX < 0.0)
1204 _data->_page->goForward();
1206 [super swipeWithEvent:event];
1209 - (void)mouseMoved:(NSEvent *)event
1211 if ([self shouldIgnoreMouseEvents])
1214 // When a view is first responder, it gets mouse moved events even when the mouse is outside its visible rect.
1215 if (self == [[self window] firstResponder] && !NSPointInRect([self convertPoint:[event locationInWindow] fromView:nil], [self visibleRect]))
1218 [self mouseMovedInternal:event];
1221 - (void)mouseDown:(NSEvent *)event
1223 if ([self shouldIgnoreMouseEvents])
1226 [self _setMouseDownEvent:event];
1227 _data->_ignoringMouseDraggedEvents = NO;
1228 [self mouseDownInternal:event];
1231 - (void)mouseUp:(NSEvent *)event
1233 if ([self shouldIgnoreMouseEvents])
1236 [self _setMouseDownEvent:nil];
1237 [self mouseUpInternal:event];
1240 - (void)mouseDragged:(NSEvent *)event
1242 if ([self shouldIgnoreMouseEvents])
1245 if (_data->_ignoringMouseDraggedEvents)
1247 [self mouseDraggedInternal:event];
1250 - (BOOL)acceptsFirstMouse:(NSEvent *)event
1252 // There's a chance that responding to this event will run a nested event loop, and
1253 // fetching a new event might release the old one. Retaining and then autoreleasing
1254 // the current event prevents that from causing a problem inside WebKit or AppKit code.
1255 [[event retain] autorelease];
1257 if (![self hitTest:[event locationInWindow]])
1260 [self _setMouseDownEvent:event];
1261 bool result = _data->_page->acceptsFirstMouse([event eventNumber], WebEventFactory::createWebMouseEvent(event, self));
1262 [self _setMouseDownEvent:nil];
1266 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
1268 // If this is the active window or we don't have a range selection, there is no need to perform additional checks
1269 // and we can avoid making a synchronous call to the WebProcess.
1270 if ([[self window] isKeyWindow] || _data->_page->editorState().selectionIsNone || !_data->_page->editorState().selectionIsRange)
1273 // There's a chance that responding to this event will run a nested event loop, and
1274 // fetching a new event might release the old one. Retaining and then autoreleasing
1275 // the current event prevents that from causing a problem inside WebKit or AppKit code.
1276 [[event retain] autorelease];
1278 if (![self hitTest:[event locationInWindow]])
1281 [self _setMouseDownEvent:event];
1282 bool result = _data->_page->shouldDelayWindowOrderingForEvent(WebEventFactory::createWebMouseEvent(event, self));
1283 [self _setMouseDownEvent:nil];
1287 - (void)_disableComplexTextInputIfNecessary
1289 if (!_data->_pluginComplexTextInputIdentifier)
1292 if (_data->_pluginComplexTextInputState != PluginComplexTextInputEnabled)
1295 // Check if the text input window has been dismissed.
1296 if (![[WKTextInputWindowController sharedTextInputWindowController] hasMarkedText])
1297 [self _setPluginComplexTextInputState:PluginComplexTextInputDisabled];
1300 - (BOOL)_handlePluginComplexTextInputKeyDown:(NSEvent *)event
1302 ASSERT(_data->_pluginComplexTextInputIdentifier);
1303 ASSERT(_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled);
1305 BOOL usingLegacyCocoaTextInput = _data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy;
1307 NSString *string = nil;
1308 BOOL didHandleEvent = [[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:event usingLegacyCocoaTextInput:usingLegacyCocoaTextInput string:&string];
1311 _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string);
1313 if (!usingLegacyCocoaTextInput)
1314 _data->_pluginComplexTextInputState = PluginComplexTextInputDisabled;
1317 return didHandleEvent;
1320 - (BOOL)_tryHandlePluginComplexTextInputKeyDown:(NSEvent *)event
1322 if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
1325 // Check if the text input window has been dismissed and let the plug-in process know.
1326 // This is only valid with the updated Cocoa text input spec.
1327 [self _disableComplexTextInputIfNecessary];
1329 // Try feeding the keyboard event directly to the plug-in.
1330 if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
1331 return [self _handlePluginComplexTextInputKeyDown:event];
1336 static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result)
1338 int length = [[string string] length];
1341 while (i < length) {
1343 NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)];
1345 if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
1346 Color color = Color::black;
1347 if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName])
1348 color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
1349 result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1));
1352 i = range.location + range.length;
1356 #if USE(ASYNC_NSTEXTINPUTCLIENT)
1358 - (void)_collectKeyboardLayoutCommandsForEvent:(NSEvent *)event to:(Vector<KeypressCommand>&)commands
1360 if ([event type] != NSKeyDown)
1363 ASSERT(!_data->_collectedKeypressCommands);
1364 _data->_collectedKeypressCommands = &commands;
1366 if (NSTextInputContext *context = [self inputContext])
1367 [context handleEventByKeyboardLayout:event];
1369 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
1371 _data->_collectedKeypressCommands = nullptr;
1374 - (void)_interpretKeyEvent:(NSEvent *)event completionHandler:(void(^)(BOOL handled, const Vector<KeypressCommand>& commands))completionHandler
1376 // For regular Web content, input methods run before passing a keydown to DOM, but plug-ins get an opportunity to handle the event first.
1377 // There is no need to collect commands, as the plug-in cannot execute them.
1378 if (_data->_pluginComplexTextInputIdentifier) {
1379 completionHandler(NO, Vector<KeypressCommand>());
1383 if (![self inputContext]) {
1384 Vector<KeypressCommand> commands;
1385 [self _collectKeyboardLayoutCommandsForEvent:event to:commands];
1386 completionHandler(NO, commands);
1390 LOG(TextInput, "-> handleEventByInputMethod:%p %@", event, event);
1391 [[self inputContext] handleEventByInputMethod:event completionHandler:^(BOOL handled) {
1393 LOG(TextInput, "... handleEventByInputMethod%s handled", handled ? "" : " not");
1395 completionHandler(YES, Vector<KeypressCommand>());
1399 Vector<KeypressCommand> commands;
1400 [self _collectKeyboardLayoutCommandsForEvent:event to:commands];
1401 completionHandler(NO, commands);
1405 - (void)doCommandBySelector:(SEL)selector
1407 LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector));
1409 Vector<KeypressCommand>* keypressCommands = _data->_collectedKeypressCommands;
1411 if (keypressCommands) {
1412 KeypressCommand command(NSStringFromSelector(selector));
1413 keypressCommands->append(command);
1414 LOG(TextInput, "...stored");
1415 _data->_page->registerKeypressCommandName(command.commandName);
1417 // FIXME: Send the command to Editor synchronously and only send it along the
1418 // responder chain if it's a selector that does not correspond to an editing command.
1419 [super doCommandBySelector:selector];
1423 - (void)insertText:(id)string
1425 // Unlike an NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context,
1426 // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText
1427 // command ensures that a keypress event is dispatched as appropriate.
1428 [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
1431 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
1433 BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1434 ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1436 if (replacementRange.location != NSNotFound)
1437 LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length);
1439 LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
1442 Vector<TextAlternativeWithRange> dictationAlternatives;
1444 bool registerUndoGroup = false;
1445 if (isAttributedString) {
1446 #if USE(DICTATION_ALTERNATIVES)
1447 collectDictationTextAlternatives(string, dictationAlternatives);
1449 #if USE(INSERTION_UNDO_GROUPING)
1450 registerUndoGroup = shouldRegisterInsertionUndoGroup(string);
1452 // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data.
1453 text = [string string];
1457 // insertText can be called for several reasons:
1458 // - If it's from normal key event processing (including key bindings), we save the action to perform it later.
1459 // - If it's from an input method, then we should go ahead and insert the text now.
1460 // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse),
1461 // then we also execute it immediately, as there will be no other chance.
1462 Vector<KeypressCommand>* keypressCommands = _data->_collectedKeypressCommands;
1463 if (keypressCommands) {
1464 ASSERT(replacementRange.location == NSNotFound);
1465 KeypressCommand command("insertText:", text);
1466 keypressCommands->append(command);
1467 LOG(TextInput, "...stored");
1468 _data->_page->registerKeypressCommandName(command.commandName);
1472 String eventText = text;
1473 eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
1474 if (!dictationAlternatives.isEmpty())
1475 _data->_page->insertDictatedTextAsync(eventText, replacementRange, dictationAlternatives, registerUndoGroup);
1477 _data->_page->insertTextAsync(eventText, replacementRange, registerUndoGroup);
1480 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
1482 RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1484 LOG(TextInput, "selectedRange");
1485 _data->_page->getSelectedRangeAsync([completionHandler](const EditingRange& editingRangeResult, CallbackBase::Error error) {
1486 void (^completionHandlerBlock)(NSRange) = (void (^)(NSRange))completionHandler.get();
1487 if (error != CallbackBase::Error::None) {
1488 LOG(TextInput, " ...selectedRange failed.");
1489 completionHandlerBlock(NSMakeRange(NSNotFound, 0));
1492 NSRange result = editingRangeResult;
1493 if (result.location == NSNotFound)
1494 LOG(TextInput, " -> selectedRange returned (NSNotFound, %llu)", result.length);
1496 LOG(TextInput, " -> selectedRange returned (%llu, %llu)", result.location, result.length);
1497 completionHandlerBlock(result);
1501 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
1503 RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1505 LOG(TextInput, "markedRange");
1506 _data->_page->getMarkedRangeAsync([completionHandler](const EditingRange& editingRangeResult, CallbackBase::Error error) {
1507 void (^completionHandlerBlock)(NSRange) = (void (^)(NSRange))completionHandler.get();
1508 if (error != CallbackBase::Error::None) {
1509 LOG(TextInput, " ...markedRange failed.");
1510 completionHandlerBlock(NSMakeRange(NSNotFound, 0));
1513 NSRange result = editingRangeResult;
1514 if (result.location == NSNotFound)
1515 LOG(TextInput, " -> markedRange returned (NSNotFound, %llu)", result.length);
1517 LOG(TextInput, " -> markedRange returned (%llu, %llu)", result.location, result.length);
1518 completionHandlerBlock(result);
1522 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
1524 RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1526 LOG(TextInput, "hasMarkedText");
1527 _data->_page->getMarkedRangeAsync([completionHandler](const EditingRange& editingRangeResult, CallbackBase::Error error) {
1528 void (^completionHandlerBlock)(BOOL) = (void (^)(BOOL))completionHandler.get();
1529 if (error != CallbackBase::Error::None) {
1530 LOG(TextInput, " ...hasMarkedText failed.");
1531 completionHandlerBlock(NO);
1534 BOOL hasMarkedText = editingRangeResult.location != notFound;
1535 LOG(TextInput, " -> hasMarkedText returned %u", hasMarkedText);
1536 completionHandlerBlock(hasMarkedText);
1540 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
1542 RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1544 LOG(TextInput, "attributedSubstringFromRange:(%u, %u)", nsRange.location, nsRange.length);
1545 _data->_page->attributedSubstringForCharacterRangeAsync(nsRange, [completionHandler](const AttributedString& string, const EditingRange& actualRange, CallbackBase::Error error) {
1546 void (^completionHandlerBlock)(NSAttributedString *, NSRange) = (void (^)(NSAttributedString *, NSRange))completionHandler.get();
1547 if (error != CallbackBase::Error::None) {
1548 LOG(TextInput, " ...attributedSubstringFromRange failed.");
1549 completionHandlerBlock(0, NSMakeRange(NSNotFound, 0));
1552 LOG(TextInput, " -> attributedSubstringFromRange returned %@", [string.string.get() string]);
1553 completionHandlerBlock([[string.string.get() retain] autorelease], actualRange);
1557 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
1559 RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1561 LOG(TextInput, "firstRectForCharacterRange:(%u, %u)", theRange.location, theRange.length);
1563 // Just to match NSTextView's behavior. Regression tests cannot detect this;
1564 // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
1565 // (type something; try ranges (1, -1) and (2, -1).
1566 if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
1567 theRange.length = 0;
1569 if (theRange.location == NSNotFound) {
1570 LOG(TextInput, " -> NSZeroRect");
1571 completionHandlerPtr(NSZeroRect, theRange);
1575 _data->_page->firstRectForCharacterRangeAsync(theRange, [self, completionHandler](const IntRect& rect, const EditingRange& actualRange, CallbackBase::Error error) {
1576 void (^completionHandlerBlock)(NSRect, NSRange) = (void (^)(NSRect, NSRange))completionHandler.get();
1577 if (error != CallbackBase::Error::None) {
1578 LOG(TextInput, " ...firstRectForCharacterRange failed.");
1579 completionHandlerBlock(NSZeroRect, NSMakeRange(NSNotFound, 0));
1583 NSRect resultRect = [self convertRect:rect toView:nil];
1584 resultRect = [self.window convertRectToScreen:resultRect];
1586 LOG(TextInput, " -> firstRectForCharacterRange returned (%f, %f, %f, %f)", resultRect.origin.x, resultRect.origin.y, resultRect.size.width, resultRect.size.height);
1587 completionHandlerBlock(resultRect, actualRange);
1591 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
1593 RetainPtr<id> completionHandler = adoptNS([completionHandlerPtr copy]);
1595 LOG(TextInput, "characterIndexForPoint:(%f, %f)", thePoint.x, thePoint.y);
1597 NSWindow *window = [self window];
1599 #pragma clang diagnostic push
1600 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1602 thePoint = [window convertScreenToBase:thePoint];
1603 #pragma clang diagnostic pop
1604 thePoint = [self convertPoint:thePoint fromView:nil]; // the point is relative to the main frame
1606 _data->_page->characterIndexForPointAsync(IntPoint(thePoint), [completionHandler](uint64_t result, CallbackBase::Error error) {
1607 void (^completionHandlerBlock)(NSUInteger) = (void (^)(NSUInteger))completionHandler.get();
1608 if (error != CallbackBase::Error::None) {
1609 LOG(TextInput, " ...characterIndexForPoint failed.");
1610 completionHandlerBlock(0);
1613 if (result == notFound)
1614 result = NSNotFound;
1615 LOG(TextInput, " -> characterIndexForPoint returned %lu", result);
1616 completionHandlerBlock(result);
1620 - (NSTextInputContext *)inputContext
1622 if (_data->_pluginComplexTextInputIdentifier) {
1623 ASSERT(!_data->_collectedKeypressCommands); // Should not get here from -_interpretKeyEvent:completionHandler:, we only use WKTextInputWindowController after giving the plug-in a chance to handle keydown natively.
1624 return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
1627 // Disable text input machinery when in non-editable content. An invisible inline input area affects performance, and can prevent Expose from working.
1628 if (!_data->_page->editorState().isContentEditable)
1631 return [super inputContext];
1636 LOG(TextInput, "unmarkText");
1638 _data->_page->confirmCompositionAsync();
1641 - (void)setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
1643 BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1644 ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1646 LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u) replacementRange:(%u, %u)", isAttributedString ? [string string] : string, selectedRange.location, selectedRange.length, replacementRange.location, replacementRange.length);
1648 Vector<CompositionUnderline> underlines;
1651 if (isAttributedString) {
1652 // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation.
1653 text = [string string];
1654 extractUnderlines(string, underlines);
1658 if (_data->_inSecureInputState) {
1659 // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField.
1660 // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard.
1661 ASSERT(!_data->_page->editorState().hasComposition);
1662 [self _notifyInputContextAboutDiscardedComposition];
1663 // FIXME: We should store the command to handle it after DOM event processing, as it's regular keyboard input now, not a composition.
1664 if ([text length] == 1 && isASCII([text characterAtIndex:0]))
1665 _data->_page->insertTextAsync(text, replacementRange);
1671 _data->_page->setCompositionAsync(text, underlines, selectedRange, replacementRange);
1674 // Synchronous NSTextInputClient is still implemented to catch spurious sync calls. Remove when that is no longer needed.
1676 - (NSRange)selectedRange NO_RETURN_DUE_TO_ASSERT
1678 ASSERT_NOT_REACHED();
1679 return NSMakeRange(NSNotFound, 0);
1682 - (BOOL)hasMarkedText NO_RETURN_DUE_TO_ASSERT
1684 ASSERT_NOT_REACHED();
1688 - (NSRange)markedRange NO_RETURN_DUE_TO_ASSERT
1690 ASSERT_NOT_REACHED();
1691 return NSMakeRange(NSNotFound, 0);
1694 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange NO_RETURN_DUE_TO_ASSERT
1696 ASSERT_NOT_REACHED();
1700 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint NO_RETURN_DUE_TO_ASSERT
1702 ASSERT_NOT_REACHED();
1706 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange NO_RETURN_DUE_TO_ASSERT
1708 ASSERT_NOT_REACHED();
1709 return NSMakeRect(0, 0, 0, 0);
1712 - (BOOL)performKeyEquivalent:(NSEvent *)event
1714 // There's a chance that responding to this event will run a nested event loop, and
1715 // fetching a new event might release the old one. Retaining and then autoreleasing
1716 // the current event prevents that from causing a problem inside WebKit or AppKit code.
1717 [[event retain] autorelease];
1719 // We get Esc key here after processing either Esc or Cmd+period. The former starts as a keyDown, and the latter starts as a key equivalent,
1720 // but both get transformed to a cancelOperation: command, executing which passes an Esc key event to -performKeyEquivalent:.
1721 // Don't interpret this event again, avoiding re-entrancy and infinite loops.
1722 if ([[event charactersIgnoringModifiers] isEqualToString:@"\e"] && !([event modifierFlags] & NSDeviceIndependentModifierFlagsMask))
1723 return [super performKeyEquivalent:event];
1725 if (_data->_keyDownEventBeingResent) {
1726 // WebCore has already seen the event, no need for custom processing.
1727 // Note that we can get multiple events for each event being re-sent. For example, for Cmd+'=' AppKit
1728 // first performs the original key equivalent, and if that isn't handled, it dispatches a synthetic Cmd+'+'.
1729 return [super performKeyEquivalent:event];
1732 ASSERT(event == [NSApp currentEvent]);
1734 [self _disableComplexTextInputIfNecessary];
1736 // Pass key combos through WebCore if there is a key binding available for
1737 // this event. This lets webpages have a crack at intercepting key-modified keypresses.
1738 // FIXME: Why is the firstResponder check needed?
1739 if (self == [[self window] firstResponder]) {
1740 [self _interpretKeyEvent:event completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1741 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, handledByInputMethod, commands));
1746 return [super performKeyEquivalent:event];
1749 - (void)keyUp:(NSEvent *)theEvent
1751 LOG(TextInput, "keyUp:%p %@", theEvent, theEvent);
1753 [self _interpretKeyEvent:theEvent completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1754 ASSERT(!handledByInputMethod || commands.isEmpty());
1755 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
1759 - (void)keyDown:(NSEvent *)theEvent
1761 LOG(TextInput, "keyDown:%p %@%s", theEvent, theEvent, (theEvent == _data->_keyDownEventBeingResent) ? " (re-sent)" : "");
1763 if ([self _tryHandlePluginComplexTextInputKeyDown:theEvent]) {
1764 LOG(TextInput, "...handled by plug-in");
1768 // We could be receiving a key down from AppKit if we have re-sent an event
1769 // that maps to an action that is currently unavailable (for example a copy when
1770 // there is no range selection).
1771 // If this is the case we should ignore the key down.
1772 if (_data->_keyDownEventBeingResent == theEvent) {
1773 [super keyDown:theEvent];
1777 [self _interpretKeyEvent:theEvent completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1778 ASSERT(!handledByInputMethod || commands.isEmpty());
1779 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
1783 - (void)flagsChanged:(NSEvent *)theEvent
1785 LOG(TextInput, "flagsChanged:%p %@", theEvent, theEvent);
1787 unsigned short keyCode = [theEvent keyCode];
1789 // Don't make an event from the num lock and function keys
1790 if (!keyCode || keyCode == 10 || keyCode == 63)
1793 [self _interpretKeyEvent:theEvent completionHandler:^(BOOL handledByInputMethod, const Vector<KeypressCommand>& commands) {
1794 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
1798 #else // USE(ASYNC_NSTEXTINPUTCLIENT)
1800 - (BOOL)_interpretKeyEvent:(NSEvent *)event savingCommandsTo:(Vector<WebCore::KeypressCommand>&)commands
1802 ASSERT(!_data->_interpretKeyEventsParameters);
1803 ASSERT(commands.isEmpty());
1805 if ([event type] == NSFlagsChanged)
1808 WKViewInterpretKeyEventsParameters parameters;
1809 parameters.eventInterpretationHadSideEffects = false;
1810 parameters.executingSavedKeypressCommands = false;
1811 // We assume that an input method has consumed the event, and only change this assumption if one of the NSTextInput methods is called.
1812 // We assume the IM will *not* consume hotkey sequences.
1813 parameters.consumedByIM = !([event modifierFlags] & NSCommandKeyMask);
1814 parameters.commands = &commands;
1815 _data->_interpretKeyEventsParameters = ¶meters;
1817 LOG(TextInput, "-> interpretKeyEvents:%p %@", event, event);
1818 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
1820 _data->_interpretKeyEventsParameters = nullptr;
1822 // An input method may consume an event and not tell us (e.g. when displaying a candidate window),
1823 // in which case we should not bubble the event up the DOM.
1824 if (parameters.consumedByIM) {
1825 ASSERT(commands.isEmpty());
1826 LOG(TextInput, "...event %p was consumed by an input method", event);
1830 LOG(TextInput, "...interpretKeyEvents for event %p done, returns %d", event, parameters.eventInterpretationHadSideEffects);
1832 // If we have already executed all or some of the commands, the event is "handled". Note that there are additional checks on web process side.
1833 return parameters.eventInterpretationHadSideEffects;
1836 - (void)_executeSavedKeypressCommands
1838 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1839 if (!parameters || parameters->commands->isEmpty())
1842 // We could be called again if the execution of one command triggers a call to selectedRange.
1843 // In this case, the state is up to date, and we don't need to execute any more saved commands to return a result.
1844 if (parameters->executingSavedKeypressCommands)
1847 LOG(TextInput, "Executing %u saved keypress commands...", parameters->commands->size());
1849 parameters->executingSavedKeypressCommands = true;
1850 parameters->eventInterpretationHadSideEffects |= _data->_page->executeKeypressCommands(*parameters->commands);
1851 parameters->commands->clear();
1852 parameters->executingSavedKeypressCommands = false;
1854 LOG(TextInput, "...done executing saved keypress commands.");
1857 - (void)doCommandBySelector:(SEL)selector
1859 LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector));
1861 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1863 parameters->consumedByIM = false;
1865 // As in insertText:replacementRange:, we assume that the call comes from an input method if there is marked text.
1866 bool isFromInputMethod = _data->_page->editorState().hasComposition;
1868 if (parameters && !isFromInputMethod) {
1869 KeypressCommand command(NSStringFromSelector(selector));
1870 parameters->commands->append(command);
1871 LOG(TextInput, "...stored");
1872 _data->_page->registerKeypressCommandName(command.commandName);
1874 // FIXME: Send the command to Editor synchronously and only send it along the
1875 // responder chain if it's a selector that does not correspond to an editing command.
1876 [super doCommandBySelector:selector];
1880 - (void)insertText:(id)string
1882 // Unlike an NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context,
1883 // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText
1884 // command ensures that a keypress event is dispatched as appropriate.
1885 [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
1888 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
1890 BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1891 ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1893 if (replacementRange.location != NSNotFound)
1894 LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length);
1896 LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
1897 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1899 parameters->consumedByIM = false;
1902 bool isFromInputMethod = _data->_page->editorState().hasComposition;
1904 Vector<TextAlternativeWithRange> dictationAlternatives;
1906 if (isAttributedString) {
1907 #if USE(DICTATION_ALTERNATIVES)
1908 collectDictationTextAlternatives(string, dictationAlternatives);
1910 // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data.
1911 text = [string string];
1915 // insertText can be called for several reasons:
1916 // - If it's from normal key event processing (including key bindings), we may need to save the action to perform it later.
1917 // - If it's from an input method, then we should go ahead and insert the text now. We assume it's from the input method if we have marked text.
1918 // FIXME: In theory, this could be wrong for some input methods, so we should try to find another way to determine if the call is from the input method.
1919 // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse),
1920 // then we also execute it immediately, as there will be no other chance.
1921 if (parameters && !isFromInputMethod) {
1922 // FIXME: Handle replacementRange in this case, too. It's known to occur in practice when canceling Press and Hold (see <rdar://11940670>).
1923 ASSERT(replacementRange.location == NSNotFound);
1924 KeypressCommand command("insertText:", text);
1925 parameters->commands->append(command);
1926 _data->_page->registerKeypressCommandName(command.commandName);
1930 String eventText = text;
1931 eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
1933 if (!dictationAlternatives.isEmpty())
1934 eventHandled = _data->_page->insertDictatedText(eventText, replacementRange, dictationAlternatives);
1936 eventHandled = _data->_page->insertText(eventText, replacementRange);
1939 parameters->eventInterpretationHadSideEffects |= eventHandled;
1942 - (NSTextInputContext *)inputContext
1944 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1946 if (_data->_pluginComplexTextInputIdentifier && !parameters)
1947 return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
1949 // Disable text input machinery when in non-editable content. An invisible inline input area affects performance, and can prevent Expose from working.
1950 if (!_data->_page->editorState().isContentEditable)
1953 return [super inputContext];
1956 - (NSRange)selectedRange
1958 [self _executeSavedKeypressCommands];
1960 EditingRange selectedRange;
1961 _data->_page->getSelectedRange(selectedRange);
1963 NSRange result = selectedRange;
1964 if (result.location == NSNotFound)
1965 LOG(TextInput, "selectedRange -> (NSNotFound, %u)", result.length);
1967 LOG(TextInput, "selectedRange -> (%u, %u)", result.location, result.length);
1972 - (BOOL)hasMarkedText
1974 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1978 result = _data->_page->editorState().hasComposition;
1980 // A saved command can confirm a composition, but it cannot start a new one.
1981 [self _executeSavedKeypressCommands];
1982 result = _data->_page->editorState().hasComposition;
1985 EditingRange markedRange;
1986 _data->_page->getMarkedRange(markedRange);
1987 result = markedRange.location != notFound;
1990 LOG(TextInput, "hasMarkedText -> %u", result);
1996 [self _executeSavedKeypressCommands];
1998 LOG(TextInput, "unmarkText");
2000 // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
2001 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
2004 parameters->eventInterpretationHadSideEffects = true;
2005 parameters->consumedByIM = false;
2008 _data->_page->confirmComposition();
2011 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
2013 [self _executeSavedKeypressCommands];
2015 BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
2016 ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
2018 LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelectedRange.location, newSelectedRange.length);
2020 // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
2021 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
2024 parameters->eventInterpretationHadSideEffects = true;
2025 parameters->consumedByIM = false;
2028 Vector<CompositionUnderline> underlines;
2031 if (isAttributedString) {
2032 // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation.
2033 text = [string string];
2034 extractUnderlines(string, underlines);
2038 if (_data->_page->editorState().isInPasswordField) {
2039 // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField.
2040 // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard.
2041 ASSERT(!_data->_page->editorState().hasComposition);
2042 [self _notifyInputContextAboutDiscardedComposition];
2043 if ([text length] == 1 && [[text decomposedStringWithCanonicalMapping] characterAtIndex:0] < 0x80) {
2044 _data->_page->insertText(text, replacementRange);
2050 _data->_page->setComposition(text, underlines, newSelectedRange, replacementRange);
2053 - (NSRange)markedRange
2055 [self _executeSavedKeypressCommands];
2057 EditingRange markedRange;
2058 _data->_page->getMarkedRange(markedRange);
2060 NSRange result = markedRange;
2061 if (result.location == NSNotFound)
2062 LOG(TextInput, "markedRange -> (NSNotFound, %u)", result.length);
2064 LOG(TextInput, "markedRange -> (%u, %u)", result.location, result.length);
2069 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
2071 [self _executeSavedKeypressCommands];
2073 if (!_data->_page->editorState().isContentEditable) {
2074 LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> nil", nsRange.location, nsRange.length);
2078 if (_data->_page->editorState().isInPasswordField)
2081 AttributedString result;
2082 _data->_page->getAttributedSubstringFromRange(nsRange, result);
2085 *actualRange = nsRange;
2086 actualRange->length = [result.string length];
2089 LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> \"%@\"", nsRange.location, nsRange.length, [result.string string]);
2090 return [[result.string retain] autorelease];
2093 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
2095 [self _executeSavedKeypressCommands];
2097 NSWindow *window = [self window];
2099 #pragma clang diagnostic push
2100 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2102 thePoint = [window convertScreenToBase:thePoint];
2103 #pragma clang diagnostic pop
2104 thePoint = [self convertPoint:thePoint fromView:nil]; // the point is relative to the main frame
2106 uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint));
2107 if (result == notFound)
2108 result = NSNotFound;
2109 LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result);
2113 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
2115 [self _executeSavedKeypressCommands];
2117 // Just to match NSTextView's behavior. Regression tests cannot detect this;
2118 // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
2119 // (type something; try ranges (1, -1) and (2, -1).
2120 if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
2121 theRange.length = 0;
2123 if (theRange.location == NSNotFound) {
2125 *actualRange = theRange;
2126 LOG(TextInput, "firstRectForCharacterRange:(NSNotFound, %u) -> NSZeroRect", theRange.length);
2130 NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange);
2131 resultRect = [self convertRect:resultRect toView:nil];
2132 resultRect = [self.window convertRectToScreen:resultRect];
2135 // FIXME: Update actualRange to match the range of first rect.
2136 *actualRange = theRange;
2139 LOG(TextInput, "firstRectForCharacterRange:(%u, %u) -> (%f, %f, %f, %f)", theRange.location, theRange.length, resultRect.origin.x, resultRect.origin.y, resultRect.size.width, resultRect.size.height);
2143 - (BOOL)performKeyEquivalent:(NSEvent *)event
2145 // There's a chance that responding to this event will run a nested event loop, and
2146 // fetching a new event might release the old one. Retaining and then autoreleasing
2147 // the current event prevents that from causing a problem inside WebKit or AppKit code.
2148 [[event retain] autorelease];
2150 // We get Esc key here after processing either Esc or Cmd+period. The former starts as a keyDown, and the latter starts as a key equivalent,
2151 // but both get transformed to a cancelOperation: command, executing which passes an Esc key event to -performKeyEquivalent:.
2152 // Don't interpret this event again, avoiding re-entrancy and infinite loops.
2153 if ([[event charactersIgnoringModifiers] isEqualToString:@"\e"] && !([event modifierFlags] & NSDeviceIndependentModifierFlagsMask))
2154 return [super performKeyEquivalent:event];
2156 if (_data->_keyDownEventBeingResent) {
2157 // WebCore has already seen the event, no need for custom processing.
2158 // Note that we can get multiple events for each event being re-sent. For example, for Cmd+'=' AppKit
2159 // first performs the original key equivalent, and if that isn't handled, it dispatches a synthetic Cmd+'+'.
2160 return [super performKeyEquivalent:event];
2163 ASSERT(event == [NSApp currentEvent]);
2165 [self _disableComplexTextInputIfNecessary];
2167 // Pass key combos through WebCore if there is a key binding available for
2168 // this event. This lets webpages have a crack at intercepting key-modified keypresses.
2169 // FIXME: Why is the firstResponder check needed?
2170 if (self == [[self window] firstResponder]) {
2171 Vector<KeypressCommand> commands;
2172 BOOL handledByInputMethod = [self _interpretKeyEvent:event savingCommandsTo:commands];
2173 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, handledByInputMethod, commands));
2177 return [super performKeyEquivalent:event];
2180 - (void)keyUp:(NSEvent *)theEvent
2182 LOG(TextInput, "keyUp:%p %@", theEvent, theEvent);
2183 // We don't interpret the keyUp event, as this breaks key bindings (see <https://bugs.webkit.org/show_bug.cgi?id=130100>).
2184 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, false, Vector<KeypressCommand>()));
2187 - (void)keyDown:(NSEvent *)theEvent
2189 LOG(TextInput, "keyDown:%p %@%s", theEvent, theEvent, (theEvent == _data->_keyDownEventBeingResent) ? " (re-sent)" : "");
2191 // There's a chance that responding to this event will run a nested event loop, and
2192 // fetching a new event might release the old one. Retaining and then autoreleasing
2193 // the current event prevents that from causing a problem inside WebKit or AppKit code.
2194 [[theEvent retain] autorelease];
2196 if ([self _tryHandlePluginComplexTextInputKeyDown:theEvent]) {
2197 LOG(TextInput, "...handled by plug-in");
2201 // We could be receiving a key down from AppKit if we have re-sent an event
2202 // that maps to an action that is currently unavailable (for example a copy when
2203 // there is no range selection).
2204 // If this is the case we should ignore the key down.
2205 if (_data->_keyDownEventBeingResent == theEvent) {
2206 [super keyDown:theEvent];
2210 Vector<KeypressCommand> commands;
2211 BOOL handledByInputMethod = [self _interpretKeyEvent:theEvent savingCommandsTo:commands];
2212 if (!commands.isEmpty()) {
2213 // An input method may make several actions per keypress. For example, pressing Return with Korean IM both confirms it and sends a newline.
2214 // IM-like actions are handled immediately (so the return value from UI process is true), but there are saved commands that
2215 // should be handled like normal text input after DOM event dispatch.
2216 handledByInputMethod = NO;
2219 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, handledByInputMethod, commands));
2222 - (void)flagsChanged:(NSEvent *)theEvent
2224 LOG(TextInput, "flagsChanged:%p %@", theEvent, theEvent);
2226 // There's a chance that responding to this event will run a nested event loop, and
2227 // fetching a new event might release the old one. Retaining and then autoreleasing
2228 // the current event prevents that from causing a problem inside WebKit or AppKit code.
2229 [[theEvent retain] autorelease];
2231 unsigned short keyCode = [theEvent keyCode];
2233 // Don't make an event from the num lock and function keys
2234 if (!keyCode || keyCode == 10 || keyCode == 63)
2237 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, false, Vector<KeypressCommand>()));
2240 #endif // USE(ASYNC_NSTEXTINPUTCLIENT)
2242 - (NSArray *)validAttributesForMarkedText
2244 static NSArray *validAttributes;
2245 if (!validAttributes) {
2246 validAttributes = [[NSArray alloc] initWithObjects:
2247 NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
2248 NSMarkedClauseSegmentAttributeName,
2249 #if USE(DICTATION_ALTERNATIVES)
2250 NSTextAlternativesAttributeName,
2252 #if USE(INSERTION_UNDO_GROUPING)
2253 NSTextInsertionUndoableAttributeName,
2256 // NSText also supports the following attributes, but it's
2257 // hard to tell which are really required for text input to
2258 // work well; I have not seen any input method make use of them yet.
2259 // NSFontAttributeName, NSForegroundColorAttributeName,
2260 // NSBackgroundColorAttributeName, NSLanguageAttributeName.
2261 CFRetain(validAttributes);
2263 LOG(TextInput, "validAttributesForMarkedText -> (...)");
2264 return validAttributes;
2267 #if ENABLE(DRAG_SUPPORT)
2268 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2270 NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2271 NSPoint windowMouseLoc = windowImageLoc;
2273 // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2274 _data->_ignoringMouseDraggedEvents = YES;
2276 _data->_page->dragEnded(IntPoint(windowMouseLoc), globalPoint(windowMouseLoc, [self window]), operation);
2279 - (DragApplicationFlags)applicationFlags:(id <NSDraggingInfo>)draggingInfo
2282 if ([NSApp modalWindow])
2283 flags = DragApplicationIsModal;
2284 if ([[self window] attachedSheet])
2285 flags |= DragApplicationHasAttachedSheet;
2286 if ([draggingInfo draggingSource] == self)
2287 flags |= DragApplicationIsSource;
2288 if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
2289 flags |= DragApplicationIsCopyKeyDown;
2290 return static_cast<DragApplicationFlags>(flags);
2293 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2295 IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2296 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2297 DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2299 _data->_page->resetCurrentDragInformation();
2300 _data->_page->dragEntered(dragData, [[draggingInfo draggingPasteboard] name]);
2301 return NSDragOperationCopy;
2304 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2306 IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2307 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2308 DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2309 _data->_page->dragUpdated(dragData, [[draggingInfo draggingPasteboard] name]);
2311 NSInteger numberOfValidItemsForDrop = _data->_page->currentDragNumberOfFilesToBeAccepted();
2312 NSDraggingFormation draggingFormation = NSDraggingFormationNone;
2313 if (_data->_page->currentDragIsOverFileInput() && numberOfValidItemsForDrop > 0)
2314 draggingFormation = NSDraggingFormationList;
2316 if ([draggingInfo numberOfValidItemsForDrop] != numberOfValidItemsForDrop)
2317 [draggingInfo setNumberOfValidItemsForDrop:numberOfValidItemsForDrop];
2318 if ([draggingInfo draggingFormation] != draggingFormation)
2319 [draggingInfo setDraggingFormation:draggingFormation];
2321 return _data->_page->currentDragOperation();
2324 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2326 IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2327 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2328 DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2329 _data->_page->dragExited(dragData, [[draggingInfo draggingPasteboard] name]);
2330 _data->_page->resetCurrentDragInformation();
2333 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2338 // FIXME: This code is more or less copied from Pasteboard::getBestURL.
2339 // It would be nice to be able to share the code somehow.
2340 static bool maybeCreateSandboxExtensionFromPasteboard(NSPasteboard *pasteboard, SandboxExtension::Handle& sandboxExtensionHandle)
2342 NSArray *types = [pasteboard types];
2343 if (![types containsObject:NSFilenamesPboardType])
2346 NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
2347 if ([files count] != 1)
2350 NSString *file = [files objectAtIndex:0];
2352 if (![[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory])
2358 SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle);
2362 static void createSandboxExtensionsForFileUpload(NSPasteboard *pasteboard, SandboxExtension::HandleArray& handles)
2364 NSArray *types = [pasteboard types];
2365 if (![types containsObject:NSFilenamesPboardType])
2368 NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
2369 handles.allocate([files count]);
2370 for (unsigned i = 0; i < [files count]; i++) {
2371 NSString *file = [files objectAtIndex:i];
2372 if (![[NSFileManager defaultManager] fileExistsAtPath:file])
2374 SandboxExtension::Handle handle;
2375 SandboxExtension::createHandle(file, SandboxExtension::ReadOnly, handles[i]);
2379 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2381 IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
2382 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2383 DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
2385 SandboxExtension::Handle sandboxExtensionHandle;
2386 bool createdExtension = maybeCreateSandboxExtensionFromPasteboard([draggingInfo draggingPasteboard], sandboxExtensionHandle);
2387 if (createdExtension)
2388 _data->_page->process().willAcquireUniversalFileReadSandboxExtension();
2390 SandboxExtension::HandleArray sandboxExtensionForUpload;
2391 createSandboxExtensionsForFileUpload([draggingInfo draggingPasteboard], sandboxExtensionForUpload);
2393 _data->_page->performDragOperation(dragData, [[draggingInfo draggingPasteboard] name], sandboxExtensionHandle, sandboxExtensionForUpload);
2398 // This code is needed to support drag and drop when the drag types cannot be matched.
2399 // This is the case for elements that do not place content
2400 // in the drag pasteboard automatically when the drag start (i.e. dragging a DIV element).
2401 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
2403 if ([[self superview] mouse:*point inRect:[self frame]])
2407 #endif // ENABLE(DRAG_SUPPORT)
2409 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)loc
2411 NSPoint localPoint = [self convertPoint:loc fromView:nil];
2412 NSRect visibleThumbRect = NSRect(_data->_page->visibleScrollerThumbRect());
2413 return NSMouseInRect(localPoint, visibleThumbRect, [self isFlipped]);
2416 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2417 static void* keyValueObservingContext = &keyValueObservingContext;
2420 - (void)addWindowObserversForWindow:(NSWindow *)window
2423 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
2424 name:NSWindowDidBecomeKeyNotification object:nil];
2425 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
2426 name:NSWindowDidResignKeyNotification object:nil];
2427 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:)
2428 name:NSWindowDidMiniaturizeNotification object:window];
2429 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
2430 name:NSWindowDidDeminiaturizeNotification object:window];
2431 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMove:)
2432 name:NSWindowDidMoveNotification object:window];
2433 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResize:)
2434 name:NSWindowDidResizeNotification object:window];
2435 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOffScreen:)
2436 name:@"NSWindowDidOrderOffScreenNotification" object:window];
2437 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOnScreen:)
2438 name:@"_NSWindowDidBecomeVisible" object:window];
2439 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeBackingProperties:)
2440 name:NSWindowDidChangeBackingPropertiesNotification object:window];
2441 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeScreen:)
2442 name:NSWindowDidChangeScreenNotification object:window];
2443 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeLayerHosting:)
2444 name:@"_NSWindowDidChangeContentsHostedInLayerSurfaceNotification" object:window];
2445 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2446 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeOcclusionState:)
2447 name:NSWindowDidChangeOcclusionStateNotification object:window];
2449 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2450 [window addObserver:self forKeyPath:@"contentLayoutRect" options:NSKeyValueObservingOptionInitial context:keyValueObservingContext];
2451 [window addObserver:self forKeyPath:@"titlebarAppearsTransparent" options:NSKeyValueObservingOptionInitial context:keyValueObservingContext];
2456 - (void)removeWindowObservers
2458 NSWindow *window = [self window];
2462 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
2463 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
2464 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
2465 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
2466 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
2467 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
2468 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowWillOrderOffScreenNotification" object:window];
2469 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowDidOrderOffScreenNotification" object:window];
2470 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"_NSWindowDidBecomeVisible" object:window];
2471 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeBackingPropertiesNotification object:window];
2472 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeScreenNotification object:window];
2473 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"_NSWindowDidChangeContentsHostedInLayerSurfaceNotification" object:window];
2474 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2475 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeOcclusionStateNotification object:window];
2477 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2478 [window removeObserver:self forKeyPath:@"contentLayoutRect" context:keyValueObservingContext];
2479 [window removeObserver:self forKeyPath:@"titlebarAppearsTransparent" context:keyValueObservingContext];
2483 - (void)viewWillMoveToWindow:(NSWindow *)window
2485 NSWindow *currentWindow = [self window];
2486 if (window == currentWindow)
2489 _data->_pageClient->viewWillMoveToAnotherWindow();
2491 [self removeWindowObservers];
2492 [self addWindowObserversForWindow:window];
2495 - (void)viewDidMoveToWindow
2497 if ([self window]) {
2498 [self doWindowDidChangeScreen];
2500 ViewState::Flags viewStateChanges = ViewState::WindowIsActive | ViewState::IsVisible;
2501 if ([self isDeferringViewInWindowChanges])
2502 _data->_viewInWindowChangeWasDeferred = YES;
2504 viewStateChanges |= ViewState::IsInWindow;
2505 _data->_page->viewStateDidChange(viewStateChanges);
2507 [self _updateWindowAndViewFrames];
2509 if (!_data->_flagsChangedEventMonitor) {
2510 _data->_flagsChangedEventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSFlagsChangedMask handler:^(NSEvent *flagsChangedEvent) {
2511 [self _postFakeMouseMovedEventForFlagsChangedEvent:flagsChangedEvent];
2512 return flagsChangedEvent;
2516 [self _accessibilityRegisterUIProcessTokens];
2518 ViewState::Flags viewStateChanges = ViewState::WindowIsActive | ViewState::IsVisible;
2519 if ([self isDeferringViewInWindowChanges])
2520 _data->_viewInWindowChangeWasDeferred = YES;
2522 viewStateChanges |= ViewState::IsInWindow;
2523 _data->_page->viewStateDidChange(viewStateChanges);
2525 [NSEvent removeMonitor:_data->_flagsChangedEventMonitor];
2526 _data->_flagsChangedEventMonitor = nil;
2528 WKHideWordDefinitionWindow();
2531 _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]);
2534 - (void)doWindowDidChangeScreen
2536 _data->_page->windowScreenDidChange((PlatformDisplayID)[[[[[self window] screen] deviceDescription] objectForKey:@"NSScreenNumber"] intValue]);
2539 - (void)_windowDidBecomeKey:(NSNotification *)notification
2541 NSWindow *keyWindow = [notification object];
2542 if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet]) {
2543 [self _updateSecureInputState];
2544 _data->_page->viewStateDidChange(ViewState::WindowIsActive);
2548 - (void)_windowDidChangeScreen:(NSNotification *)notification
2550 [self doWindowDidChangeScreen];
2553 - (void)_windowDidChangeLayerHosting:(NSNotification *)notification
2555 _data->_page->layerHostingModeDidChange();
2558 - (void)_windowDidResignKey:(NSNotification *)notification
2560 NSWindow *formerKeyWindow = [notification object];
2561 if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) {
2562 [self _updateSecureInputState];
2563 _data->_page->viewStateDidChange(ViewState::WindowIsActive);
2567 - (void)_windowDidMiniaturize:(NSNotification *)notification
2569 _data->_page->viewStateDidChange(ViewState::IsVisible);
2572 - (void)_windowDidDeminiaturize:(NSNotification *)notification
2574 _data->_page->viewStateDidChange(ViewState::IsVisible);
2577 - (void)_windowDidMove:(NSNotification *)notification
2579 [self _updateWindowAndViewFrames];
2582 - (void)_windowDidResize:(NSNotification *)notification
2584 [self _updateWindowAndViewFrames];
2587 - (void)_windowDidOrderOffScreen:(NSNotification *)notification
2589 _data->_page->viewStateDidChange(ViewState::IsVisible | ViewState::WindowIsActive);
2592 - (void)_windowDidOrderOnScreen:(NSNotification *)notification
2594 _data->_page->viewStateDidChange(ViewState::IsVisible | ViewState::WindowIsActive);
2597 - (void)_windowDidChangeBackingProperties:(NSNotification *)notification
2599 CGFloat oldBackingScaleFactor = [[notification.userInfo objectForKey:NSBackingPropertyOldScaleFactorKey] doubleValue];
2600 CGFloat newBackingScaleFactor = [self _intrinsicDeviceScaleFactor];
2601 if (oldBackingScaleFactor == newBackingScaleFactor)
2604 _data->_page->setIntrinsicDeviceScaleFactor(newBackingScaleFactor);
2607 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2608 - (void)_windowDidChangeOcclusionState:(NSNotification *)notification
2610 _data->_page->viewStateDidChange(ViewState::IsVisible);
2614 - (void)drawRect:(NSRect)rect
2616 LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
2617 _data->_page->endPrinting();
2622 return _data->_page->drawsBackground();
2625 - (BOOL)mouseDownCanMoveWindow
2627 // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent,
2628 // but we don't want a drag in the NSView to move the window, even if it's transparent.
2634 _data->_page->viewStateDidChange(ViewState::IsVisible);
2637 - (void)viewDidUnhide
2639 _data->_page->viewStateDidChange(ViewState::IsVisible);
2642 - (void)viewDidChangeBackingProperties
2644 NSColorSpace *colorSpace = [[self window] colorSpace];
2645 if ([colorSpace isEqualTo:_data->_colorSpace.get()])
2648 _data->_colorSpace = nullptr;
2649 if (DrawingAreaProxy *drawingArea = _data->_page->drawingArea())
2650 drawingArea->colorSpaceDidChange();
2653 - (void)_activeSpaceDidChange:(NSNotification *)notification
2655 _data->_page->viewStateDidChange(ViewState::IsVisible);
2658 - (void)_applicationWillTerminate:(NSNotification *)notification
2660 _data->_page->process().context().applicationWillTerminate();
2663 - (void)_accessibilityRegisterUIProcessTokens
2665 // Initialize remote accessibility when the window connection has been established.
2666 NSData *remoteElementToken = WKAXRemoteTokenForElement(self);
2667 NSData *remoteWindowToken = WKAXRemoteTokenForElement([self window]);
2668 IPC::DataReference elementToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteElementToken bytes]), [remoteElementToken length]);
2669 IPC::DataReference windowToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteWindowToken bytes]), [remoteWindowToken length]);
2670 _data->_page->registerUIProcessAccessibilityTokens(elementToken, windowToken);
2673 - (void)_updateRemoteAccessibilityRegistration:(BOOL)registerProcess
2675 // When the tree is connected/disconnected, the remote accessibility registration
2676 // needs to be updated with the pid of the remote process. If the process is going
2677 // away, that information is not present in WebProcess
2679 if (registerProcess)
2680 pid = _data->_page->process().processIdentifier();
2681 else if (!registerProcess) {
2682 pid = WKAXRemoteProcessIdentifier(_data->_remoteAccessibilityChild.get());
2683 _data->_remoteAccessibilityChild = nil;
2686 WKAXRegisterRemoteProcess(registerProcess, pid);
2689 - (void)enableAccessibilityIfNecessary
2691 if (WebCore::AXObjectCache::accessibilityEnabled())
2694 // After enabling accessibility update the window frame on the web process so that the
2695 // correct accessibility position is transmitted (when AX is off, that position is not calculated).
2696 WebCore::AXObjectCache::enableAccessibility();
2697 [self _updateWindowAndViewFrames];
2700 - (id)accessibilityFocusedUIElement
2702 [self enableAccessibilityIfNecessary];
2703 return _data->_remoteAccessibilityChild.get();
2706 - (BOOL)accessibilityIsIgnored
2711 - (id)accessibilityHitTest:(NSPoint)point
2713 [self enableAccessibilityIfNecessary];
2714 return _data->_remoteAccessibilityChild.get();
2717 - (id)accessibilityAttributeValue:(NSString*)attribute
2719 [self enableAccessibilityIfNecessary];
2721 if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
2724 if (_data->_remoteAccessibilityChild)
2725 child = _data->_remoteAccessibilityChild.get();
2729 return [NSArray arrayWithObject:child];
2731 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
2732 return NSAccessibilityGroupRole;
2733 if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
2734 return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil);
2735 if ([attribute isEqualToString:NSAccessibilityParentAttribute])
2736 return NSAccessibilityUnignoredAncestor([self superview]);
2737 if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
2738 return [NSNumber numberWithBool:YES];
2740 return [super accessibilityAttributeValue:attribute];
2743 - (NSView *)hitTest:(NSPoint)point
2745 NSView *hitView = [super hitTest:point];
2746 if (hitView && _data && hitView == _data->_layerHostingView)
2752 - (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent
2754 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved location:[[flagsChangedEvent window] mouseLocationOutsideOfEventStream]
2755 modifierFlags:[flagsChangedEvent modifierFlags] timestamp:[flagsChangedEvent timestamp] windowNumber:[flagsChangedEvent windowNumber]
2756 context:[flagsChangedEvent context] eventNumber:0 clickCount:0 pressure:0];
2757 NativeWebMouseEvent webEvent(fakeEvent, self);
2758 _data->_page->handleMouseEvent(webEvent);
2761 - (NSInteger)conversationIdentifier
2763 return (NSInteger)self;
2766 - (float)_intrinsicDeviceScaleFactor
2768 NSWindow *window = [self window];
2770 return [window backingScaleFactor];
2771 return [[NSScreen mainScreen] backingScaleFactor];
2774 - (void)_setDrawingAreaSize:(NSSize)size
2776 if (!_data->_page->drawingArea())
2779 _data->_page->drawingArea()->setSize(IntSize(size), IntSize(0, 0), IntSize(_data->_resizeScrollOffset));
2780 _data->_resizeScrollOffset = NSZeroSize;
2783 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
2784 - (void)quickLookWithEvent:(NSEvent *)event
2786 NSPoint locationInViewCoordinates = [self convertPoint:[event locationInWindow] fromView:nil];
2787 _data->_page->performDictionaryLookupAtLocation(FloatPoint(locationInViewCoordinates.x, locationInViewCoordinates.y));
2791 - (std::unique_ptr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy
2793 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"WebKit2UseRemoteLayerTreeDrawingArea"] boolValue])
2794 return std::make_unique<RemoteLayerTreeDrawingAreaProxy>(_data->_page.get());
2796 return std::make_unique<TiledCoreAnimationDrawingAreaProxy>(_data->_page.get());
2801 if (_data->_inBecomeFirstResponder)
2803 if (_data->_inResignFirstResponder)
2805 return [[self window] firstResponder] == self;
2808 - (WebKit::ColorSpaceData)_colorSpace
2810 if (!_data->_colorSpace) {
2812 _data->_colorSpace = [[self window] colorSpace];
2814 _data->_colorSpace = [[NSScreen mainScreen] colorSpace];
2817 ColorSpaceData colorSpaceData;
2818 colorSpaceData.cgColorSpace = [_data->_colorSpace CGColorSpace];
2820 return colorSpaceData;
2823 - (void)_processDidExit
2825 if (_data->_layerHostingView)
2826 [self _setAcceleratedCompositingModeRootLayer:nil];
2828 [self _updateRemoteAccessibilityRegistration:NO];
2830 _data->_gestureController = nullptr;
2835 [self _updateRemoteAccessibilityRegistration:NO];
2838 - (void)_didRelaunchProcess
2840 [self _accessibilityRegisterUIProcessTokens];
2843 - (void)_preferencesDidChange
2845 BOOL needsViewFrameInWindowCoordinates = _data->_page->preferences().pluginsEnabled();
2847 if (!!needsViewFrameInWindowCoordinates == !!_data->_needsViewFrameInWindowCoordinates)
2850 _data->_needsViewFrameInWindowCoordinates = needsViewFrameInWindowCoordinates;
2852 [self _updateWindowAndViewFrames];
2855 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
2857 ValidationVector items = _data->_validationMap.take(commandName);
2858 size_t size = items.size();
2859 for (size_t i = 0; i < size; ++i) {
2860 ValidationItem item = items[i].get();
2861 [menuItem(item) setState:newState];
2862 [menuItem(item) setEnabled:isEnabled];
2863 [toolbarItem(item) setEnabled:isEnabled];
2864 // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
2868 - (BOOL)_tryPostProcessPluginComplexTextInputKeyDown:(NSEvent *)event
2870 if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
2873 // In the legacy text input model, the event has already been sent to the input method.
2874 if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
2877 return [self _handlePluginComplexTextInputKeyDown:event];
2880 - (void)_doneWithKeyEvent:(NSEvent *)event eventWasHandled:(BOOL)eventWasHandled
2882 if ([event type] != NSKeyDown)
2885 if ([self _tryPostProcessPluginComplexTextInputKeyDown:event])
2888 if (eventWasHandled) {
2889 [NSCursor setHiddenUntilMouseMoves:YES];
2893 // resending the event may destroy this WKView
2894 RetainPtr<WKView> protector(self);
2896 ASSERT(!_data->_keyDownEventBeingResent);
2897 _data->_keyDownEventBeingResent = event;
2898 [NSApp _setCurrentEvent:event];
2899 [NSApp sendEvent:event];
2901 _data->_keyDownEventBeingResent = nullptr;
2904 - (NSRect)_convertToDeviceSpace:(NSRect)rect
2906 return toDeviceSpace(rect, [self window]);
2909 - (NSRect)_convertToUserSpace:(NSRect)rect
2911 return toUserSpace(rect, [self window]);
2914 // Any non-zero value will do, but using something recognizable might help us debug some day.
2915 #define TRACKING_RECT_TAG 0xBADFACE
2917 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2919 ASSERT(_data->_trackingRectOwner == nil);
2920 _data->_trackingRectOwner = owner;
2921 _data->_trackingRectUserData = data;
2922 return TRACKING_RECT_TAG;
2925 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2927 ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
2928 ASSERT(_data->_trackingRectOwner == nil);
2929 _data->_trackingRectOwner = owner;
2930 _data->_trackingRectUserData = data;
2931 return TRACKING_RECT_TAG;
2934 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
2937 ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
2938 ASSERT(_data->_trackingRectOwner == nil);
2939 _data->_trackingRectOwner = owner;
2940 _data->_trackingRectUserData = userDataList[0];
2941 trackingNums[0] = TRACKING_RECT_TAG;
2944 - (void)removeTrackingRect:(NSTrackingRectTag)tag
2952 if (tag == TRACKING_RECT_TAG) {
2953 _data->_trackingRectOwner = nil;
2957 if (tag == _data->_lastToolTipTag) {
2958 [super removeTrackingRect:tag];
2959 _data->_lastToolTipTag = 0;
2963 // If any other tracking rect is being removed, we don't know how it was created
2964 // and it's possible there's a leak involved (see 3500217)
2965 ASSERT_NOT_REACHED();
2968 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
2971 for (i = 0; i < count; ++i) {
2975 ASSERT(tag == TRACKING_RECT_TAG);
2977 _data->_trackingRectOwner = nil;
2982 - (void)_sendToolTipMouseExited
2984 // Nothing matters except window, trackingNumber, and userData.
2985 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
2986 location:NSMakePoint(0, 0)
2989 windowNumber:[[self window] windowNumber]
2992 trackingNumber:TRACKING_RECT_TAG
2993 userData:_data->_trackingRectUserData];
2994 [_data->_trackingRectOwner mouseExited:fakeEvent];
2997 - (void)_sendToolTipMouseEntered
2999 // Nothing matters except window, trackingNumber, and userData.
3000 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
3001 location:NSMakePoint(0, 0)
3004 windowNumber:[[self window] windowNumber]
3007 trackingNumber:TRACKING_RECT_TAG
3008 userData:_data->_trackingRectUserData];
3009 [_data->_trackingRectOwner mouseEntered:fakeEvent];
3012 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
3014 return nsStringFromWebCoreString(_data->_page->toolTip());
3017 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
3020 [self _sendToolTipMouseExited];
3022 if (newToolTip && [newToolTip length] > 0) {
3023 // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
3024 [self removeAllToolTips];
3025 NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
3026 _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
3027 [self _sendToolTipMouseEntered];
3031 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut animate:(BOOL)animate
3033 if (!findIndicator) {
3034 _data->_findIndicatorWindow = nullptr;
3038 if (!_data->_findIndicatorWindow)
3039 _data->_findIndicatorWindow = std::make_unique<FindIndicatorWindow>(self);
3041 _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut, animate);
3044 - (CALayer *)_rootLayer
3046 return [_data->_layerHostingView layer];
3049 - (void)_setAcceleratedCompositingModeRootLayer:(CALayer *)rootLayer
3051 [rootLayer web_disableAllActions];
3053 _data->_rootLayer = rootLayer;
3056 if (_data->_thumbnailView) {
3057 [self _updateThumbnailViewLayer];
3062 [CATransaction begin];
3063 [CATransaction setDisableActions:YES];
3066 if (!_data->_layerHostingView) {
3067 // Create an NSView that will host our layer tree.
3068 _data->_layerHostingView = adoptNS([[WKFlippedView alloc] initWithFrame:[self bounds]]);
3069 [_data->_layerHostingView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
3072 [self addSubview:_data->_layerHostingView.get() positioned:NSWindowBelow relativeTo:nil];
3074 // Create a root layer that will back the NSView.
3075 RetainPtr<CALayer> layer = adoptNS([[CALayer alloc] init]);
3076 [layer setDelegate:[WebActionDisablingCALayerDelegate shared]];
3078 [layer setName:@"Hosting root layer"];
3081 [_data->_layerHostingView setLayer:layer.get()];
3082 [_data->_layerHostingView setWantsLayer:YES];
3085 [_data->_layerHostingView layer].sublayers = [NSArray arrayWithObject:rootLayer];
3087 if (_data->_layerHostingView) {
3088 [_data->_layerHostingView removeFromSuperview];
3089 [_data->_layerHostingView setLayer:nil];
3090 [_data->_layerHostingView setWantsLayer:NO];
3092 _data->_layerHostingView = nullptr;
3096 [CATransaction commit];
3099 - (CALayer *)_acceleratedCompositingModeRootLayer
3101 return _data->_rootLayer.get();
3104 - (ViewSnapshot)_takeViewSnapshot
3106 NSWindow *window = self.window;
3108 ViewSnapshot snapshot;
3110 CGSWindowID windowID = (CGSWindowID)[window windowNumber];
3114 RetainPtr<CGImageRef> windowSnapshotImage = adoptCF(CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, windowID, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageShouldBeOpaque));
3116 // Work around <rdar://problem/17084993>; re-request the snapshot at kCGWindowImageNominalResolution if it was captured at the wrong scale.
3117 CGFloat desiredSnapshotWidth = window.frame.size.width * window.screen.backingScaleFactor;
3118 if (CGImageGetWidth(windowSnapshotImage.get()) != desiredSnapshotWidth)
3119 windowSnapshotImage = adoptCF(CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, windowID, kCGWindowImageBoundsIgnoreFraming | kCGWindowImageShouldBeOpaque | kCGWindowImageNominalResolution));
3121 [self _ensureGestureController];
3123 NSRect windowCaptureRect;
3124 FloatRect boundsForCustomSwipeViews = _data->_gestureController->windowRelativeBoundsForCustomSwipeViews();
3125 if (!boundsForCustomSwipeViews.isEmpty())
3126 windowCaptureRect = boundsForCustomSwipeViews;
3128 NSRect unobscuredBounds = self.bounds;
3129 float topContentInset = _data->_page->topContentInset();
3130 unobscuredBounds.origin.y += topContentInset;
3131 unobscuredBounds.size.height -= topContentInset;
3132 windowCaptureRect = [self convertRect:unobscuredBounds toView:nil];
3135 NSRect windowCaptureScreenRect = [window convertRectToScreen:windowCaptureRect];
3136 CGRect windowScreenRect;
3137 CGSGetScreenRectForWindow(CGSMainConnectionID(), (CGSWindowID)[window windowNumber], &windowScreenRect);
3139 NSRect croppedImageRect = windowCaptureRect;
3140 croppedImageRect.origin.y = windowScreenRect.size.height - windowCaptureScreenRect.size.height - NSMinY(windowCaptureRect);
3142 auto croppedSnapshotImage = adoptCF(CGImageCreateWithImageInRect(windowSnapshotImage.get(), NSRectToCGRect([window convertRectToBacking:croppedImageRect])));
3144 snapshot.image = croppedSnapshotImage.get();
3146 IntSize imageSize(CGImageGetWidth(croppedSnapshotImage.get()), CGImageGetHeight(croppedSnapshotImage.get()));
3147 snapshot.size = imageSize;
3148 snapshot.imageSizeInBytes = imageSize.width() * imageSize.height() * 4;
3149 snapshot.backgroundColor = _data->_page->pageExtendedBackgroundColor();
3154 - (void)_wheelEventWasNotHandledByWebCore:(NSEvent *)event
3156 if (_data->_gestureController)
3157 _data->_gestureController->wheelEventWasNotHandledByWebCore(event);
3160 - (void)_setAccessibilityWebProcessToken:(NSData *)data
3162 _data->_remoteAccessibilityChild = WKAXRemoteElementForToken(data);
3163 [self _updateRemoteAccessibilityRegistration:YES];
3166 - (void)_pluginFocusOrWindowFocusChanged:(BOOL)pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
3168 BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
3170 if (pluginHasFocusAndWindowHasFocus) {
3171 // Check if we're already allowing text input for this plug-in.
3172 if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
3175 _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
3178 // Check if we got a request to unfocus a plug-in that isn't focused.
3179 if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
3182 _data->_pluginComplexTextInputIdentifier = 0;
3185 if (inputSourceChanged) {
3186 // The input source changed, go ahead and discard any entered text.
3187 [[WKTextInputWindowController sharedTextInputWindowController] unmarkText];
3190 // This will force the current input context to be updated to its correct value.
3191 [NSApp updateWindows];
3194 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
3196 if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier) {
3197 // We're asked to update the state for a plug-in that doesn't have focus.
3201 [self _setPluginComplexTextInputState:pluginComplexTextInputState];
3204 - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag
3206 IntSize size([image size]);
3207 size.scale(1.0 / _data->_page->deviceScaleFactor());
3208 [image setSize:size];
3210 // The call below could release this WKView.
3211 RetainPtr<WKView> protector(self);
3213 #pragma clang diagnostic push
3214 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
3215 [self dragImage:image
3218 event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent
3219 pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
3222 #pragma clang diagnostic pop
3225 static bool matchesExtensionOrEquivalent(NSString *filename, NSString *extension)
3227 NSString *extensionAsSuffix = [@"." stringByAppendingString:extension];
3228 return hasCaseInsensitiveSuffix(filename, extensionAsSuffix) || (stringIsCaseInsensitiveEqualToString(extension, @"jpeg")
3229 && hasCaseInsensitiveSuffix(filename, @".jpg"));
3232 - (void)_setPromisedData:(WebCore::Image *)image withFileName:(NSString *)filename withExtension:(NSString *)extension withTitle:(NSString *)title withURL:(NSString *)url withVisibleURL:(NSString *)visibleUrl withArchive:(WebCore::SharedBuffer*) archiveBuffer forPasteboard:(NSString *)pasteboardName
3235 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName];
3236 RetainPtr<NSMutableArray> types = adoptNS([[NSMutableArray alloc] initWithObjects:NSFilesPromisePboardType, nil]);
3238 [types addObjectsFromArray:archiveBuffer ? PasteboardTypes::forImagesWithArchive() : PasteboardTypes::forImages()];
3239 [pasteboard declareTypes:types.get() owner:self];
3240 if (!matchesExtensionOrEquivalent(filename, extension))
3241 filename = [[filename stringByAppendingString:@"."] stringByAppendingString:extension];
3243 [pasteboard setString:visibleUrl forType:NSStringPboardType];
3244 [pasteboard setString:visibleUrl forType:PasteboardTypes::WebURLPboardType];
3245 [pasteboard setString:title forType:PasteboardTypes::WebURLNamePboardType];
3246 [pasteboard setPropertyList:[NSArray arrayWithObjects:[NSArray arrayWithObject:visibleUrl], [NSArray arrayWithObject:title], nil] forType:PasteboardTypes::WebURLsWithTitlesPboardType];
3247 [pasteboard setPropertyList:[NSArray arrayWithObject:extension] forType:NSFilesPromisePboardType];
3250 [pasteboard setData:archiveBuffer->createNSData().get() forType:PasteboardTypes::WebArchivePboardType];
3252 _data->_promisedImage = image;
3253 _data->_promisedFilename = filename;
3254 _data->_promisedURL = url;
3257 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
3259 _data->_promisedImage = 0;
3260 _data->_promisedFilename = "";
3261 _data->_promisedURL = "";
3264 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
3266 // FIXME: need to support NSRTFDPboardType
3268 if ([type isEqual:NSTIFFPboardType] && _data->_promisedImage) {
3269 [pasteboard setData:(NSData *)_data->_promisedImage->getTIFFRepresentation() forType:NSTIFFPboardType];
3270 _data->_promisedImage = 0;
3274 static BOOL fileExists(NSString *path)
3276 struct stat statBuffer;
3277 return !lstat([path fileSystemRepresentation], &statBuffer);
3280 static NSString *pathWithUniqueFilenameForPath(NSString *path)
3282 // "Fix" the filename of the path.
3283 NSString *filename = filenameByFixingIllegalCharacters([path lastPathComponent]);
3284 path = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:filename];
3286 if (fileExists(path)) {
3287 // Don't overwrite existing file by appending "-n", "-n.ext" or "-n.ext.ext" to the filename.
3288 NSString *extensions = nil;
3289 NSString *pathWithoutExtensions;
3290 NSString *lastPathComponent = [path lastPathComponent];
3291 NSRange periodRange = [lastPathComponent rangeOfString:@"."];
3293 if (periodRange.location == NSNotFound) {
3294 pathWithoutExtensions = path;
3296 extensions = [lastPathComponent substringFromIndex:periodRange.location + 1];
3297 lastPathComponent = [lastPathComponent substringToIndex:periodRange.location];
3298 pathWithoutExtensions = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:lastPathComponent];
3301 for (unsigned i = 1; ; i++) {
3302 NSString *pathWithAppendedNumber = [NSString stringWithFormat:@"%@-%d", pathWithoutExtensions, i];
3303 path = [extensions length] ? [pathWithAppendedNumber stringByAppendingPathExtension:extensions] : pathWithAppendedNumber;
3304 if (!fileExists(path))
3312 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
3314 RetainPtr<NSFileWrapper> wrapper;
3315 RetainPtr<NSData> data;
3317 if (_data->_promisedImage) {
3318 data = _data->_promisedImage->data()->createNSData();
3319 wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:data.get()]);
3320 [wrapper setPreferredFilename:_data->_promisedFilename];
3324 LOG_ERROR("Failed to create image file.");
3328 // FIXME: Report an error if we fail to create a file.
3329 NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
3330 path = pathWithUniqueFilenameForPath(path);
3331 if (![wrapper writeToURL:[NSURL fileURLWithPath:path] options:NSFileWrapperWritingWithNameUpdating originalContentsURL:nil error:nullptr])
3332 LOG_ERROR("Failed to create image file via -[NSFileWrapper writeToURL:options:originalContentsURL:error:]");
3334 if (!_data->_promisedURL.isEmpty())
3335 WebCore::setMetadataURL(_data->_promisedURL, "", String(path));
3337 return [NSArray arrayWithObject:[path lastPathComponent]];
3340 - (void)_updateSecureInputState
3342 if (![[self window] isKeyWindow] || ![self _isFocused]) {
3343 if (_data->_inSecureInputState) {
3344 DisableSecureEventInput();
3345 _data->_inSecureInputState = NO;
3349 // WKView has a single input context for all editable areas (except for plug-ins).
3350 NSTextInputContext *context = [super inputContext];
3351 bool isInPasswordField = _data->_page->editorState().isInPasswordField;
3353 if (isInPasswordField) {
3354 if (!_data->_inSecureInputState)
3355 EnableSecureEventInput();
3356 static NSArray *romanInputSources = [[NSArray alloc] initWithObjects:&NSAllRomanInputSourcesLocaleIdentifier count:1];
3357 LOG(TextInput, "-> setAllowedInputSourceLocales:romanInputSources");
3358 [context setAllowedInputSourceLocales:romanInputSources];
3360 if (_data->_inSecureInputState)
3361 DisableSecureEventInput();
3362 LOG(TextInput, "-> setAllowedInputSourceLocales:nil");
3363 [context setAllowedInputSourceLocales:nil];
3365 _data->_inSecureInputState = isInPasswordField;
3368 - (void)_resetSecureInputState
3370 if (_data->_inSecureInputState) {
3371 DisableSecureEventInput();
3372 _data->_inSecureInputState = NO;
3376 - (void)_notifyInputContextAboutDiscardedComposition
3378 // <rdar://problem/9359055>: -discardMarkedText can only be called for active contexts.
3379 // FIXME: We fail to ever notify the input context if something (e.g. a navigation) happens while the window is not key.
3380 // This is not a problem when the window is key, because we discard marked text on resigning first responder.
3381 if (![[self window] isKeyWindow] || self != [[self window] firstResponder])
3384 LOG(TextInput, "-> discardMarkedText");
3385 [[super inputContext] discardMarkedText]; // Inform the input method that we won't have an inline input area despite having been asked to.
3388 #if ENABLE(FULLSCREEN_API)
3389 - (BOOL)_hasFullScreenWindowController
3391 return (bool)_data->_fullScreenWindowController;
3394 - (WKFullScreenWindowController *)_fullScreenWindowController
3396 if (!_data->_fullScreenWindowController)
3397 _data->_fullScreenWindowController = adoptNS([[WKFullScreenWindowController alloc] initWithWindow:[self createFullScreenWindow] webView:self]);
3399 return _data->_fullScreenWindowController.get();
3402 - (void)_closeFullScreenWindowController
3404 if (!_data->_fullScreenWindowController)
3407 [_data->_fullScreenWindowController close];
3408 _data->_fullScreenWindowController = nullptr;
3412 - (bool)_executeSavedCommandBySelector:(SEL)selector
3414 LOG(TextInput, "Executing previously saved command %s", sel_getName(selector));
3415 // The sink does two things: 1) Tells us if the responder went unhandled, and
3416 // 2) prevents any NSBeep; we don't ever want to beep here.
3417 RetainPtr<WKResponderChainSink> sink = adoptNS([[WKResponderChainSink alloc] initWithResponderChain:self]);
3418 [super doCommandBySelector:selector];
3420 return ![sink didReceiveUnhandledCommand];
3423 - (void)_setIntrinsicContentSize:(NSSize)intrinsicContentSize
3425 // If the intrinsic content size is less than the minimum layout width, the content flowed to fit,
3426 // so we can report that that dimension is flexible. If not, we need to report our intrinsic width
3427 // so that autolayout will know to provide space for us.
3429 NSSize intrinsicContentSizeAcknowledgingFlexibleWidth = intrinsicContentSize;
3430 if (intrinsicContentSize.width < _data->_page->minimumLayoutSize().width())
3431 intrinsicContentSizeAcknowledgingFlexibleWidth.width = NSViewNoInstrinsicMetric;
3433 _data->_intrinsicContentSize = intrinsicContentSizeAcknowledgingFlexibleWidth;
3434 [self invalidateIntrinsicContentSize];
3437 - (void)_cacheWindowBottomCornerRect
3439 // FIXME: We should remove this code when <rdar://problem/9362085> is resolved.
3440 NSWindow *window = [self window];
3444 _data->_windowBottomCornerIntersectionRect = [window _intersectBottomCornersWithRect:[self convertRect:[self visibleRect] toView:nil]];
3445 if (!NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect))
3446 [self setNeedsDisplayInRect:[self convertRect:_data->_windowBottomCornerIntersectionRect fromView:nil]];
3449 - (NSInteger)spellCheckerDocumentTag
3451 if (!_data->_hasSpellCheckerDocumentTag) {
3452 _data->_spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
3453 _data->_hasSpellCheckerDocumentTag = YES;
3455 return _data->_spellCheckerDocumentTag;
3458 - (void)handleAcceptedAlternativeText:(NSString*)text
3460 _data->_page->handleAlternativeTextUIResult(text);
3463 - (void)_setSuppressVisibilityUpdates:(BOOL)suppressVisibilityUpdates
3465 _data->_page->setSuppressVisibilityUpdates(suppressVisibilityUpdates);
3468 - (BOOL)_suppressVisibilityUpdates
3470 return _data->_page->suppressVisibilityUpdates();
3473 - (instancetype)initWithFrame:(NSRect)frame context:(WebContext&)context configuration:(WebPageConfiguration)webPageConfiguration webView:(WKWebView *)webView
3475 self = [super initWithFrame:frame];
3479 [NSApp registerServicesMenuSendTypes:PasteboardTypes::forSelection() returnTypes:PasteboardTypes::forEditing()];
3481 InitializeWebKit2();
3483 // Legacy style scrollbars have design details that rely on tracking the mouse all the time.
3484 NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect;