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.
29 #import "AttributedString.h"
30 #import "ChunkedUpdateDrawingAreaProxy.h"
31 #import "DataReference.h"
32 #import "DrawingAreaProxyImpl.h"
33 #import "EditorState.h"
34 #import "FindIndicator.h"
35 #import "FindIndicatorWindow.h"
36 #import "LayerTreeContext.h"
38 #import "NativeWebKeyboardEvent.h"
39 #import "NativeWebMouseEvent.h"
40 #import "PDFViewController.h"
41 #import "PageClientImpl.h"
42 #import "PasteboardTypes.h"
45 #import "TextChecker.h"
46 #import "TextCheckerState.h"
48 #import "WKFullScreenWindowController.h"
49 #import "WKPrintingView.h"
50 #import "WKStringCF.h"
51 #import "WKTextInputWindowController.h"
52 #import "WKViewInternal.h"
53 #import "WKViewPrivate.h"
54 #import "WebContext.h"
55 #import "WebEventFactory.h"
56 #import "WebFullScreenManagerProxy.h"
58 #import "WebPageProxy.h"
59 #import "WebProcessProxy.h"
60 #import "WebSystemInterface.h"
61 #import <QuartzCore/QuartzCore.h>
62 #import <WebCore/ColorMac.h>
63 #import <WebCore/DragController.h>
64 #import <WebCore/DragData.h>
65 #import <WebCore/LocalizedStrings.h>
66 #import <WebCore/FloatRect.h>
67 #import <WebCore/IntRect.h>
68 #import <WebCore/KeyboardEvent.h>
69 #import <WebCore/PlatformMouseEvent.h>
70 #import <WebCore/PlatformScreen.h>
71 #import <WebKitSystemInterface.h>
72 #import <wtf/RefPtr.h>
73 #import <wtf/RetainPtr.h>
75 @interface NSApplication (WKNSApplicationDetails)
76 - (void)speakString:(NSString *)string;
77 - (void)_setCurrentEvent:(NSEvent *)event;
80 @interface NSObject (WKNSTextInputContextDetails)
81 - (BOOL)wantsToHandleMouseEvents;
82 - (BOOL)handleMouseEvent:(NSEvent *)event;
85 @interface NSWindow (WKNSWindowDetails)
86 - (NSRect)_growBoxRect;
88 - (void)_setShowOpaqueGrowBoxForOwner:(id)owner;
89 - (BOOL)_updateGrowBoxForWindowFrameChange;
92 using namespace WebKit;
93 using namespace WebCore;
97 typedef id <NSValidatedUserInterfaceItem> ValidationItem;
98 typedef Vector<RetainPtr<ValidationItem> > ValidationVector;
99 typedef HashMap<String, ValidationVector> ValidationMap;
103 struct WKViewInterpretKeyEventsParameters {
104 bool eventInterpretationHadSideEffects;
106 bool executingSavedKeypressCommands;
107 Vector<KeypressCommand>* commands;
110 @interface WKViewData : NSObject {
112 OwnPtr<PageClientImpl> _pageClient;
113 RefPtr<WebPageProxy> _page;
116 NSToolTipTag _lastToolTipTag;
117 id _trackingRectOwner;
118 void* _trackingRectUserData;
120 RetainPtr<NSView> _layerHostingView;
122 RetainPtr<id> _remoteAccessibilityChild;
124 // For asynchronous validation.
125 ValidationMap _validationMap;
127 OwnPtr<PDFViewController> _pdfViewController;
129 OwnPtr<FindIndicatorWindow> _findIndicatorWindow;
130 // We keep here the event when resending it to
131 // the application to distinguish the case of a new event from one
132 // that has been already sent to WebCore.
133 RetainPtr<NSEvent> _keyDownEventBeingResent;
134 WKViewInterpretKeyEventsParameters* _interpretKeyEventsParameters;
136 NSSize _resizeScrollOffset;
138 // The identifier of the plug-in we want to send complex text input to, or 0 if there is none.
139 uint64_t _pluginComplexTextInputIdentifier;
141 bool _inBecomeFirstResponder;
142 bool _inResignFirstResponder;
143 NSEvent *_mouseDownEvent;
144 BOOL _ignoringMouseDraggedEvents;
145 BOOL _dragHasStarted;
147 #if ENABLE(GESTURE_EVENTS)
148 id _endGestureMonitor;
151 #if ENABLE(FULLSCREEN_API)
152 RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
155 BOOL _hasSpellCheckerDocumentTag;
156 NSInteger _spellCheckerDocumentTag;
158 BOOL _inSecureInputState;
162 @interface WKResponderChainSink : NSResponder {
163 NSResponder *_lastResponderInChain;
164 bool _didReceiveUnhandledCommand;
166 - (id)initWithResponderChain:(NSResponder *)chain;
168 - (bool)didReceiveUnhandledCommand;
171 @implementation WKViewData
174 @implementation WKView
176 - (id)initWithFrame:(NSRect)frame
178 return [self initWithFrame:frame contextRef:toAPI(WebContext::sharedProcessContext())];
181 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef
183 return [self initWithFrame:frame contextRef:contextRef pageGroupRef:nil];
186 - (void)_registerDraggedTypes
188 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:PasteboardTypes::forEditing()];
189 [types addObjectsFromArray:PasteboardTypes::forURL()];
190 [self registerForDraggedTypes:[types allObjects]];
194 - (void)_updateRemoteAccessibilityRegistration:(BOOL)registerProcess
196 #if !defined(BUILDING_ON_SNOW_LEOPARD)
197 // When the tree is connected/disconnected, the remote accessibility registration
198 // needs to be updated with the pid of the remote process. If the process is going
199 // away, that information is not present in WebProcess
201 if (registerProcess && _data->_page->process())
202 pid = _data->_page->process()->processIdentifier();
203 else if (!registerProcess) {
204 pid = WKAXRemoteProcessIdentifier(_data->_remoteAccessibilityChild.get());
205 _data->_remoteAccessibilityChild = nil;
208 WKAXRegisterRemoteProcess(registerProcess, pid);
212 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef
214 self = [super initWithFrame:frame];
218 [NSApp registerServicesMenuSendTypes:PasteboardTypes::forSelection() returnTypes:PasteboardTypes::forEditing()];
220 InitWebCoreSystemInterface();
221 RunLoop::initializeMainRunLoop();
223 NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame
224 options:(NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect)
227 [self addTrackingArea:trackingArea];
228 [trackingArea release];
230 _data = [[WKViewData alloc] init];
232 _data->_pageClient = PageClientImpl::create(self);
233 _data->_page = toImpl(contextRef)->createWebPage(_data->_pageClient.get(), toImpl(pageGroupRef));
234 _data->_page->initializeWebPage();
235 #if ENABLE(FULLSCREEN_API)
236 _data->_page->fullScreenManager()->setWebView(self);
238 _data->_mouseDownEvent = nil;
239 _data->_ignoringMouseDraggedEvents = NO;
241 [self _registerDraggedTypes];
243 WebContext::statistics().wkViewCount++;
250 _data->_page->close();
252 ASSERT(!_data->_inSecureInputState);
257 WebContext::statistics().wkViewCount--;
264 return toAPI(_data->_page.get());
267 - (void)setDrawsBackground:(BOOL)drawsBackground
269 _data->_page->setDrawsBackground(drawsBackground);
272 - (BOOL)drawsBackground
274 return _data->_page->drawsBackground();
277 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
279 _data->_page->setDrawsTransparentBackground(drawsTransparentBackground);
282 - (BOOL)drawsTransparentBackground
284 return _data->_page->drawsTransparentBackground();
287 - (BOOL)acceptsFirstResponder
292 - (BOOL)becomeFirstResponder
294 NSSelectionDirection direction = [[self window] keyViewSelectionDirection];
296 _data->_inBecomeFirstResponder = true;
298 [self _updateSecureInputState];
299 _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
301 _data->_inBecomeFirstResponder = false;
303 if (direction != NSDirectSelection)
304 _data->_page->setInitialFocus(direction == NSSelectingNext);
309 - (BOOL)resignFirstResponder
311 _data->_inResignFirstResponder = true;
313 if (_data->_page->editorState().hasComposition && !_data->_page->editorState().shouldIgnoreCompositionSelectionChange)
314 _data->_page->confirmCompositionWithoutDisturbingSelection();
315 [self _resetTextInputState];
317 if (!_data->_page->maintainsInactiveSelection())
318 _data->_page->clearSelection();
320 _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
322 _data->_inResignFirstResponder = false;
327 - (void)viewWillStartLiveResize
329 _data->_page->viewWillStartLiveResize();
332 - (void)viewDidEndLiveResize
334 _data->_page->viewWillEndLiveResize();
342 - (void)setFrame:(NSRect)rect andScrollBy:(NSSize)offset
344 ASSERT(NSEqualSizes(_data->_resizeScrollOffset, NSZeroSize));
346 _data->_resizeScrollOffset = offset;
347 [self setFrame:rect];
350 - (void)setFrameSize:(NSSize)size
352 [super setFrameSize:size];
354 if (![self frameSizeUpdatesDisabled])
355 [self _setDrawingAreaSize:size];
358 - (void)_updateWindowAndViewFrames
360 NSWindow *window = [self window];
363 NSRect windowFrameInScreenCoordinates = [window frame];
364 NSRect viewFrameInWindowCoordinates = [self convertRect:[self frame] toView:nil];
365 NSPoint accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue];
367 _data->_page->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates), IntPoint(accessibilityPosition));
372 // Hide the find indicator.
373 _data->_findIndicatorWindow = nullptr;
375 // Update the view frame.
377 [self _updateWindowAndViewFrames];
382 typedef HashMap<SEL, String> SelectorNameMap;
384 // Map selectors into Editor command names.
385 // This is not needed for any selectors that have the same name as the Editor command.
386 static const SelectorNameMap* createSelectorExceptionMap()
388 SelectorNameMap* map = new HashMap<SEL, String>;
390 map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
391 map->add(@selector(insertParagraphSeparator:), "InsertNewline");
392 map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
393 map->add(@selector(pageDown:), "MovePageDown");
394 map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
395 map->add(@selector(pageUp:), "MovePageUp");
396 map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
397 map->add(@selector(scrollPageDown:), "ScrollPageForward");
398 map->add(@selector(scrollPageUp:), "ScrollPageBackward");
403 static String commandNameForSelector(SEL selector)
405 // Check the exception map first.
406 static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
407 SelectorNameMap::const_iterator it = exceptionMap->find(selector);
408 if (it != exceptionMap->end())
411 // Remove the trailing colon.
412 // No need to capitalize the command name since Editor command names are
413 // not case sensitive.
414 const char* selectorName = sel_getName(selector);
415 size_t selectorNameLength = strlen(selectorName);
416 if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
418 return String(selectorName, selectorNameLength - 1);
423 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
425 WEBCORE_COMMAND(alignCenter)
426 WEBCORE_COMMAND(alignJustified)
427 WEBCORE_COMMAND(alignLeft)
428 WEBCORE_COMMAND(alignRight)
429 WEBCORE_COMMAND(copy)
431 WEBCORE_COMMAND(delete)
432 WEBCORE_COMMAND(deleteBackward)
433 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
434 WEBCORE_COMMAND(deleteForward)
435 WEBCORE_COMMAND(deleteToBeginningOfLine)
436 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
437 WEBCORE_COMMAND(deleteToEndOfLine)
438 WEBCORE_COMMAND(deleteToEndOfParagraph)
439 WEBCORE_COMMAND(deleteToMark)
440 WEBCORE_COMMAND(deleteWordBackward)
441 WEBCORE_COMMAND(deleteWordForward)
442 WEBCORE_COMMAND(ignoreSpelling)
443 WEBCORE_COMMAND(indent)
444 WEBCORE_COMMAND(insertBacktab)
445 WEBCORE_COMMAND(insertLineBreak)
446 WEBCORE_COMMAND(insertNewline)
447 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
448 WEBCORE_COMMAND(insertParagraphSeparator)
449 WEBCORE_COMMAND(insertTab)
450 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
451 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
452 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
453 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
454 WEBCORE_COMMAND(moveBackward)
455 WEBCORE_COMMAND(moveBackwardAndModifySelection)
456 WEBCORE_COMMAND(moveDown)
457 WEBCORE_COMMAND(moveDownAndModifySelection)
458 WEBCORE_COMMAND(moveForward)
459 WEBCORE_COMMAND(moveForwardAndModifySelection)
460 WEBCORE_COMMAND(moveLeft)
461 WEBCORE_COMMAND(moveLeftAndModifySelection)
462 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
463 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
464 WEBCORE_COMMAND(moveRight)
465 WEBCORE_COMMAND(moveRightAndModifySelection)
466 WEBCORE_COMMAND(moveToBeginningOfDocument)
467 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
468 WEBCORE_COMMAND(moveToBeginningOfLine)
469 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
470 WEBCORE_COMMAND(moveToBeginningOfParagraph)
471 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
472 WEBCORE_COMMAND(moveToBeginningOfSentence)
473 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
474 WEBCORE_COMMAND(moveToEndOfDocument)
475 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
476 WEBCORE_COMMAND(moveToEndOfLine)
477 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
478 WEBCORE_COMMAND(moveToEndOfParagraph)
479 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
480 WEBCORE_COMMAND(moveToEndOfSentence)
481 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
482 WEBCORE_COMMAND(moveToLeftEndOfLine)
483 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
484 WEBCORE_COMMAND(moveToRightEndOfLine)
485 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
486 WEBCORE_COMMAND(moveUp)
487 WEBCORE_COMMAND(moveUpAndModifySelection)
488 WEBCORE_COMMAND(moveWordBackward)
489 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
490 WEBCORE_COMMAND(moveWordForward)
491 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
492 WEBCORE_COMMAND(moveWordLeft)
493 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
494 WEBCORE_COMMAND(moveWordRight)
495 WEBCORE_COMMAND(moveWordRightAndModifySelection)
496 WEBCORE_COMMAND(outdent)
497 WEBCORE_COMMAND(pageDown)
498 WEBCORE_COMMAND(pageDownAndModifySelection)
499 WEBCORE_COMMAND(pageUp)
500 WEBCORE_COMMAND(pageUpAndModifySelection)
501 WEBCORE_COMMAND(paste)
502 WEBCORE_COMMAND(pasteAsPlainText)
503 WEBCORE_COMMAND(scrollPageDown)
504 WEBCORE_COMMAND(scrollPageUp)
505 WEBCORE_COMMAND(scrollToBeginningOfDocument)
506 WEBCORE_COMMAND(scrollToEndOfDocument)
507 WEBCORE_COMMAND(selectAll)
508 WEBCORE_COMMAND(selectLine)
509 WEBCORE_COMMAND(selectParagraph)
510 WEBCORE_COMMAND(selectSentence)
511 WEBCORE_COMMAND(selectToMark)
512 WEBCORE_COMMAND(selectWord)
513 WEBCORE_COMMAND(setMark)
514 WEBCORE_COMMAND(subscript)
515 WEBCORE_COMMAND(superscript)
516 WEBCORE_COMMAND(swapWithMark)
517 WEBCORE_COMMAND(takeFindStringFromSelection)
518 WEBCORE_COMMAND(transpose)
519 WEBCORE_COMMAND(underline)
520 WEBCORE_COMMAND(unscript)
521 WEBCORE_COMMAND(yank)
522 WEBCORE_COMMAND(yankAndSelect)
524 #undef WEBCORE_COMMAND
526 // This method is needed to support Mac OS X services.
528 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
530 Vector<String> pasteboardTypes;
531 size_t numTypes = [types count];
532 for (size_t i = 0; i < numTypes; ++i)
533 pasteboardTypes.append([types objectAtIndex:i]);
534 return _data->_page->writeSelectionToPasteboard([pasteboard name], pasteboardTypes);
537 // This method is needed to support Mac OS X services.
539 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
541 BOOL isValidSendType = !sendType || ([PasteboardTypes::forSelection() containsObject:sendType] && !_data->_page->editorState().selectionIsNone);
542 BOOL isValidReturnType = NO;
544 isValidReturnType = YES;
545 else if ([PasteboardTypes::forEditing() containsObject:returnType] && _data->_page->editorState().isContentEditable) {
546 // We can insert strings in any editable context. We can insert other types, like images, only in rich edit contexts.
547 isValidReturnType = _data->_page->editorState().isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType];
549 if (isValidSendType && isValidReturnType)
551 return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
554 // This method is needed to support Mac OS X services.
556 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
558 return _data->_page->readSelectionFromPasteboard([pasteboard name]);
563 When possible, editing-related methods should be implemented in WebCore with the
564 EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing
565 individual methods here with Mac-specific code.
567 Editing-related methods still unimplemented that are implemented in WebKit1:
569 - (void)capitalizeWord:(id)sender;
570 - (void)centerSelectionInVisibleArea:(id)sender;
571 - (void)changeFont:(id)sender;
572 - (void)complete:(id)sender;
573 - (void)copyFont:(id)sender;
574 - (void)lowercaseWord:(id)sender;
575 - (void)makeBaseWritingDirectionLeftToRight:(id)sender;
576 - (void)makeBaseWritingDirectionNatural:(id)sender;
577 - (void)makeBaseWritingDirectionRightToLeft:(id)sender;
578 - (void)pasteFont:(id)sender;
579 - (void)scrollLineDown:(id)sender;
580 - (void)scrollLineUp:(id)sender;
581 - (void)showGuessPanel:(id)sender;
582 - (void)uppercaseWord:(id)sender;
584 Some other editing-related methods still unimplemented:
586 - (void)changeCaseOfLetter:(id)sender;
587 - (void)copyRuler:(id)sender;
588 - (void)insertContainerBreak:(id)sender;
589 - (void)insertDoubleQuoteIgnoringSubstitution:(id)sender;
590 - (void)insertSingleQuoteIgnoringSubstitution:(id)sender;
591 - (void)pasteRuler:(id)sender;
592 - (void)toggleRuler:(id)sender;
593 - (void)transposeWords:(id)sender;
597 // Menu items validation
599 static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item)
601 if (![(NSObject *)item isKindOfClass:[NSMenuItem class]])
603 return (NSMenuItem *)item;
606 static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item)
608 if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]])
610 return (NSToolbarItem *)item;
613 static void validateCommandCallback(WKStringRef commandName, bool isEnabled, int32_t state, WKErrorRef error, void* context)
615 // If the process exits before the command can be validated, we'll be called back with an error.
619 WKView* wkView = static_cast<WKView*>(context);
622 [wkView _setUserInterfaceItemState:nsStringFromWebCoreString(toImpl(commandName)->string()) enabled:isEnabled state:state];
625 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
627 SEL action = [item action];
629 if (action == @selector(showGuessPanel:)) {
630 if (NSMenuItem *menuItem = ::menuItem(item))
631 [menuItem setTitle:contextMenuItemTagShowSpellingPanel(![[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible])];
632 return _data->_page->editorState().isContentEditable;
635 if (action == @selector(checkSpelling:) || action == @selector(changeSpelling:))
636 return _data->_page->editorState().isContentEditable;
638 if (action == @selector(toggleContinuousSpellChecking:)) {
639 bool enabled = TextChecker::isContinuousSpellCheckingAllowed();
640 bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled;
641 [menuItem(item) setState:checked ? NSOnState : NSOffState];
645 if (action == @selector(toggleGrammarChecking:)) {
646 bool checked = TextChecker::state().isGrammarCheckingEnabled;
647 [menuItem(item) setState:checked ? NSOnState : NSOffState];
651 if (action == @selector(toggleAutomaticSpellingCorrection:)) {
652 bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled;
653 [menuItem(item) setState:checked ? NSOnState : NSOffState];
654 return _data->_page->editorState().isContentEditable;
657 if (action == @selector(orderFrontSubstitutionsPanel:)) {
658 if (NSMenuItem *menuItem = ::menuItem(item))
659 [menuItem setTitle:contextMenuItemTagShowSubstitutions(![[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible])];
660 return _data->_page->editorState().isContentEditable;
663 if (action == @selector(toggleSmartInsertDelete:)) {
664 bool checked = _data->_page->isSmartInsertDeleteEnabled();
665 [menuItem(item) setState:checked ? NSOnState : NSOffState];
666 return _data->_page->editorState().isContentEditable;
669 if (action == @selector(toggleAutomaticQuoteSubstitution:)) {
670 bool checked = TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
671 [menuItem(item) setState:checked ? NSOnState : NSOffState];
672 return _data->_page->editorState().isContentEditable;
675 if (action == @selector(toggleAutomaticDashSubstitution:)) {
676 bool checked = TextChecker::state().isAutomaticDashSubstitutionEnabled;
677 [menuItem(item) setState:checked ? NSOnState : NSOffState];
678 return _data->_page->editorState().isContentEditable;
681 if (action == @selector(toggleAutomaticLinkDetection:)) {
682 bool checked = TextChecker::state().isAutomaticLinkDetectionEnabled;
683 [menuItem(item) setState:checked ? NSOnState : NSOffState];
684 return _data->_page->editorState().isContentEditable;
687 if (action == @selector(toggleAutomaticTextReplacement:)) {
688 bool checked = TextChecker::state().isAutomaticTextReplacementEnabled;
689 [menuItem(item) setState:checked ? NSOnState : NSOffState];
690 return _data->_page->editorState().isContentEditable;
693 if (action == @selector(uppercaseWord:) || action == @selector(lowercaseWord:) || action == @selector(capitalizeWord:))
694 return _data->_page->editorState().selectionIsRange && _data->_page->editorState().isContentEditable;
696 if (action == @selector(stopSpeaking:))
697 return [NSApp isSpeaking];
699 // Next, handle editor commands. Start by returning YES for anything that is not an editor command.
700 // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized.
701 String commandName = commandNameForSelector([item action]);
702 if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName))
705 // Add this item to the vector of items for a given command that are awaiting validation.
706 pair<ValidationMap::iterator, bool> addResult = _data->_validationMap.add(commandName, ValidationVector());
707 addResult.first->second.append(item);
708 if (addResult.second) {
709 // If we are not already awaiting validation for this command, start the asynchronous validation process.
710 // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
711 // we asked for the same command; there is no guarantee the answer is still valid.
712 _data->_page->validateCommand(commandName, ValidateCommandCallback::create(self, validateCommandCallback));
715 // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called.
716 // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment.
717 // But returning NO here would be worse; that would make keyboard commands such as command-C fail.
721 static void speakString(WKStringRef string, WKErrorRef error, void*)
728 NSString *convertedString = toImpl(string)->string();
729 [NSApp speakString:convertedString];
732 - (IBAction)startSpeaking:(id)sender
734 _data->_page->getSelectionOrContentsAsString(StringCallback::create(0, speakString));
737 - (IBAction)stopSpeaking:(id)sender
739 [NSApp stopSpeaking:sender];
742 - (IBAction)showGuessPanel:(id)sender
744 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
746 LOG_ERROR("No NSSpellChecker");
750 NSPanel *spellingPanel = [checker spellingPanel];
751 if ([spellingPanel isVisible]) {
752 [spellingPanel orderOut:sender];
756 _data->_page->advanceToNextMisspelling(true);
757 [spellingPanel orderFront:sender];
760 - (IBAction)checkSpelling:(id)sender
762 _data->_page->advanceToNextMisspelling(false);
765 - (void)changeSpelling:(id)sender
767 NSString *word = [[sender selectedCell] stringValue];
769 _data->_page->changeSpellingToWord(word);
772 - (IBAction)toggleContinuousSpellChecking:(id)sender
774 bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled;
775 TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled);
777 _data->_page->process()->updateTextCheckerState();
780 - (BOOL)isGrammarCheckingEnabled
782 return TextChecker::state().isGrammarCheckingEnabled;
785 - (void)setGrammarCheckingEnabled:(BOOL)flag
787 if (static_cast<bool>(flag) == TextChecker::state().isGrammarCheckingEnabled)
790 TextChecker::setGrammarCheckingEnabled(flag);
791 _data->_page->process()->updateTextCheckerState();
794 - (IBAction)toggleGrammarChecking:(id)sender
796 bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled;
797 TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled);
799 _data->_page->process()->updateTextCheckerState();
802 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
804 TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
806 _data->_page->process()->updateTextCheckerState();
809 - (void)orderFrontSubstitutionsPanel:(id)sender
811 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
813 LOG_ERROR("No NSSpellChecker");
817 NSPanel *substitutionsPanel = [checker substitutionsPanel];
818 if ([substitutionsPanel isVisible]) {
819 [substitutionsPanel orderOut:sender];
822 [substitutionsPanel orderFront:sender];
825 - (IBAction)toggleSmartInsertDelete:(id)sender
827 _data->_page->setSmartInsertDeleteEnabled(!_data->_page->isSmartInsertDeleteEnabled());
830 - (BOOL)isAutomaticQuoteSubstitutionEnabled
832 return TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
835 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
837 if (static_cast<bool>(flag) == TextChecker::state().isAutomaticQuoteSubstitutionEnabled)
840 TextChecker::setAutomaticQuoteSubstitutionEnabled(flag);
841 _data->_page->process()->updateTextCheckerState();
844 - (void)toggleAutomaticQuoteSubstitution:(id)sender
846 TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled);
847 _data->_page->process()->updateTextCheckerState();
850 - (BOOL)isAutomaticDashSubstitutionEnabled
852 return TextChecker::state().isAutomaticDashSubstitutionEnabled;
855 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
857 if (static_cast<bool>(flag) == TextChecker::state().isAutomaticDashSubstitutionEnabled)
860 TextChecker::setAutomaticDashSubstitutionEnabled(flag);
861 _data->_page->process()->updateTextCheckerState();
864 - (void)toggleAutomaticDashSubstitution:(id)sender
866 TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled);
867 _data->_page->process()->updateTextCheckerState();
870 - (BOOL)isAutomaticLinkDetectionEnabled
872 return TextChecker::state().isAutomaticLinkDetectionEnabled;
875 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
877 if (static_cast<bool>(flag) == TextChecker::state().isAutomaticLinkDetectionEnabled)
880 TextChecker::setAutomaticLinkDetectionEnabled(flag);
881 _data->_page->process()->updateTextCheckerState();
884 - (void)toggleAutomaticLinkDetection:(id)sender
886 TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled);
887 _data->_page->process()->updateTextCheckerState();
890 - (BOOL)isAutomaticTextReplacementEnabled
892 return TextChecker::state().isAutomaticTextReplacementEnabled;
895 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
897 if (static_cast<bool>(flag) == TextChecker::state().isAutomaticTextReplacementEnabled)
900 TextChecker::setAutomaticTextReplacementEnabled(flag);
901 _data->_page->process()->updateTextCheckerState();
904 - (void)toggleAutomaticTextReplacement:(id)sender
906 TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled);
907 _data->_page->process()->updateTextCheckerState();
910 - (void)uppercaseWord:(id)sender
912 _data->_page->uppercaseWord();
915 - (void)lowercaseWord:(id)sender
917 _data->_page->lowercaseWord();
920 - (void)capitalizeWord:(id)sender
922 _data->_page->capitalizeWord();
927 // Override this so that AppKit will send us arrow keys as key down events so we can
928 // support them via the key bindings mechanism.
929 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
934 - (void)_setMouseDownEvent:(NSEvent *)event
936 ASSERT(!event || [event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
938 if (event == _data->_mouseDownEvent)
941 [_data->_mouseDownEvent release];
942 _data->_mouseDownEvent = [event retain];
945 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
946 - (void)Selector:(NSEvent *)theEvent \
948 if ([[self inputContext] handleEvent:theEvent]) { \
949 LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
952 NativeWebMouseEvent webEvent(theEvent, self); \
953 _data->_page->handleMouseEvent(webEvent); \
956 NATIVE_MOUSE_EVENT_HANDLER(mouseEntered)
957 NATIVE_MOUSE_EVENT_HANDLER(mouseExited)
958 NATIVE_MOUSE_EVENT_HANDLER(mouseMovedInternal)
959 NATIVE_MOUSE_EVENT_HANDLER(mouseDownInternal)
960 NATIVE_MOUSE_EVENT_HANDLER(mouseUpInternal)
961 NATIVE_MOUSE_EVENT_HANDLER(mouseDraggedInternal)
962 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDown)
963 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDragged)
964 NATIVE_MOUSE_EVENT_HANDLER(otherMouseMoved)
965 NATIVE_MOUSE_EVENT_HANDLER(otherMouseUp)
966 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDown)
967 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDragged)
968 NATIVE_MOUSE_EVENT_HANDLER(rightMouseUp)
970 #undef NATIVE_MOUSE_EVENT_HANDLER
972 #define EVENT_HANDLER(Selector, Type) \
973 - (void)Selector:(NSEvent *)theEvent \
975 Web##Type##Event webEvent = WebEventFactory::createWeb##Type##Event(theEvent, self); \
976 _data->_page->handle##Type##Event(webEvent); \
979 EVENT_HANDLER(scrollWheel, Wheel)
983 - (void)mouseMoved:(NSEvent *)event
985 // When a view is first responder, it gets mouse moved events even when the mouse is outside its visible rect.
986 if (self == [[self window] firstResponder] && !NSPointInRect([self convertPoint:[event locationInWindow] fromView:nil], [self visibleRect]))
989 [self mouseMovedInternal:event];
992 - (void)mouseDown:(NSEvent *)event
994 [self _setMouseDownEvent:event];
995 _data->_ignoringMouseDraggedEvents = NO;
996 _data->_dragHasStarted = NO;
997 [self mouseDownInternal:event];
1000 - (void)mouseUp:(NSEvent *)event
1002 [self _setMouseDownEvent:nil];
1003 [self mouseUpInternal:event];
1006 - (void)mouseDragged:(NSEvent *)event
1008 if (_data->_ignoringMouseDraggedEvents)
1010 [self mouseDraggedInternal:event];
1013 - (BOOL)acceptsFirstMouse:(NSEvent *)event
1015 // There's a chance that responding to this event will run a nested event loop, and
1016 // fetching a new event might release the old one. Retaining and then autoreleasing
1017 // the current event prevents that from causing a problem inside WebKit or AppKit code.
1018 [[event retain] autorelease];
1020 if (![self hitTest:[event locationInWindow]])
1023 [self _setMouseDownEvent:event];
1024 bool result = _data->_page->acceptsFirstMouse([event eventNumber], WebEventFactory::createWebMouseEvent(event, self));
1025 [self _setMouseDownEvent:nil];
1029 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
1031 // If this is the active window or we don't have a range selection, there is no need to perform additional checks
1032 // and we can avoid making a synchronous call to the WebProcess.
1033 if ([[self window] isKeyWindow] || _data->_page->editorState().selectionIsNone || !_data->_page->editorState().selectionIsRange)
1036 // There's a chance that responding to this event will run a nested event loop, and
1037 // fetching a new event might release the old one. Retaining and then autoreleasing
1038 // the current event prevents that from causing a problem inside WebKit or AppKit code.
1039 [[event retain] autorelease];
1041 if (![self hitTest:[event locationInWindow]])
1044 [self _setMouseDownEvent:event];
1045 bool result = _data->_page->shouldDelayWindowOrderingForEvent(WebEventFactory::createWebMouseEvent(event, self));
1046 [self _setMouseDownEvent:nil];
1050 #if ENABLE(GESTURE_EVENTS)
1052 static const short kIOHIDEventTypeScroll = 6;
1054 - (void)shortCircuitedEndGestureWithEvent:(NSEvent *)event
1056 if ([event subtype] != kIOHIDEventTypeScroll)
1059 WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
1060 _data->_page->handleGestureEvent(webEvent);
1062 if (_data->_endGestureMonitor) {
1063 [NSEvent removeMonitor:_data->_endGestureMonitor];
1064 _data->_endGestureMonitor = nil;
1068 - (void)beginGestureWithEvent:(NSEvent *)event
1070 if ([event subtype] != kIOHIDEventTypeScroll)
1073 WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
1074 _data->_page->handleGestureEvent(webEvent);
1076 if (!_data->_endGestureMonitor) {
1077 _data->_endGestureMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskEndGesture handler:^(NSEvent *blockEvent) {
1078 [self shortCircuitedEndGestureWithEvent:blockEvent];
1085 - (void)doCommandBySelector:(SEL)selector
1087 LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector));
1089 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1091 parameters->consumedByIM = false;
1093 // As in insertText:replacementRange:, we assume that the call comes from an input method if there is marked text.
1094 bool isFromInputMethod = _data->_page->editorState().hasComposition;
1096 if (parameters && !isFromInputMethod)
1097 parameters->commands->append(KeypressCommand(NSStringFromSelector(selector)));
1099 // FIXME: Send the command to Editor synchronously and only send it along the
1100 // responder chain if it's a selector that does not correspond to an editing command.
1101 [super doCommandBySelector:selector];
1105 - (void)insertText:(id)string
1107 // Unlike and NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context,
1108 // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText
1109 // command ensures that a keypress event is dispatched as appropriate.
1110 [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
1113 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
1115 BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1116 ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1118 if (replacementRange.location != NSNotFound)
1119 LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length);
1121 LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
1122 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1124 parameters->consumedByIM = false;
1127 bool isFromInputMethod = _data->_page->editorState().hasComposition;
1129 if (isAttributedString) {
1130 // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data.
1131 text = [string string];
1135 // insertText can be called for several reasons:
1136 // - If it's from normal key event processing (including key bindings), we may need to save the action to perform it later.
1137 // - 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.
1138 // 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.
1139 // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse),
1140 // then we also execute it immediately, as there will be no other chance.
1141 if (parameters && !isFromInputMethod) {
1142 ASSERT(replacementRange.location == NSNotFound);
1143 parameters->commands->append(KeypressCommand("insertText:", text));
1147 String eventText = text;
1148 eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
1149 bool eventHandled = _data->_page->insertText(eventText, replacementRange.location, NSMaxRange(replacementRange));
1152 parameters->eventInterpretationHadSideEffects |= eventHandled;
1155 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
1157 if (!_data->_page->editorState().isContentEditable)
1160 if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) != NSCommandKeyMask)
1163 // Here we special case cmd+b and cmd+i but not cmd+u, for historic reason.
1164 // This should not be changed, since it could break some Mac applications that
1165 // rely on this inherent behavior.
1166 // See https://bugs.webkit.org/show_bug.cgi?id=24943
1168 NSString *string = [event characters];
1169 if ([string caseInsensitiveCompare:@"b"] == NSOrderedSame) {
1170 _data->_page->executeEditCommand("ToggleBold");
1173 if ([string caseInsensitiveCompare:@"i"] == NSOrderedSame) {
1174 _data->_page->executeEditCommand("ToggleItalic");
1181 - (BOOL)performKeyEquivalent:(NSEvent *)event
1183 // There's a chance that responding to this event will run a nested event loop, and
1184 // fetching a new event might release the old one. Retaining and then autoreleasing
1185 // the current event prevents that from causing a problem inside WebKit or AppKit code.
1186 [[event retain] autorelease];
1188 BOOL eventWasSentToWebCore = (_data->_keyDownEventBeingResent == event);
1190 // Pass key combos through WebCore if there is a key binding available for
1191 // this event. This lets web pages have a crack at intercepting key-modified keypresses.
1192 // But don't do it if we have already handled the event.
1193 // Pressing Esc results in a fake event being sent - don't pass it to WebCore.
1194 if (!eventWasSentToWebCore && event == [NSApp currentEvent] && self == [[self window] firstResponder]) {
1195 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, self));
1199 return [self _handleStyleKeyEquivalent:event] || [super performKeyEquivalent:event];
1202 - (void)keyUp:(NSEvent *)theEvent
1204 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1207 - (void)keyDown:(NSEvent *)theEvent
1209 // There's a chance that responding to this event will run a nested event loop, and
1210 // fetching a new event might release the old one. Retaining and then autoreleasing
1211 // the current event prevents that from causing a problem inside WebKit or AppKit code.
1212 [[theEvent retain] autorelease];
1214 if (_data->_pluginComplexTextInputIdentifier) {
1215 // Try feeding the keyboard event directly to the plug-in.
1216 NSString *string = nil;
1217 if ([[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:theEvent string:&string]) {
1219 _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string);
1224 // We could be receiving a key down from AppKit if we have re-sent an event
1225 // that maps to an action that is currently unavailable (for example a copy when
1226 // there is no range selection).
1227 // If this is the case we should ignore the key down.
1228 if (_data->_keyDownEventBeingResent == theEvent) {
1229 [super keyDown:theEvent];
1232 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1235 - (void)flagsChanged:(NSEvent *)theEvent
1237 // There's a chance that responding to this event will run a nested event loop, and
1238 // fetching a new event might release the old one. Retaining and then autoreleasing
1239 // the current event prevents that from causing a problem inside WebKit or AppKit code.
1240 [[theEvent retain] autorelease];
1242 unsigned short keyCode = [theEvent keyCode];
1244 // Don't make an event from the num lock and function keys
1245 if (!keyCode || keyCode == 10 || keyCode == 63)
1248 _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1251 - (void)_executeSavedKeypressCommands
1253 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1254 if (!parameters || parameters->commands->isEmpty())
1257 // We could be called again if the execution of one command triggers a call to selectedRange.
1258 // In this case, the state is up to date, and we don't need to execute any more saved commands to return a result.
1259 if (parameters->executingSavedKeypressCommands)
1262 parameters->executingSavedKeypressCommands = true;
1263 parameters->eventInterpretationHadSideEffects |= _data->_page->executeKeypressCommands(*parameters->commands);
1264 parameters->commands->clear();
1265 parameters->executingSavedKeypressCommands = false;
1268 - (NSTextInputContext *)inputContext
1270 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1272 if (_data->_pluginComplexTextInputIdentifier && !parameters)
1273 return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
1275 // Disable text input machinery when in non-editable content. An invisible inline input area affects performance, and can prevent Expose from working.
1276 if (!_data->_page->editorState().isContentEditable)
1279 return [super inputContext];
1282 - (NSRange)selectedRange
1284 [self _executeSavedKeypressCommands];
1286 uint64_t selectionStart;
1287 uint64_t selectionLength;
1288 _data->_page->getSelectedRange(selectionStart, selectionLength);
1290 NSRange result = NSMakeRange(selectionStart, selectionLength);
1291 if (result.location == NSNotFound)
1292 LOG(TextInput, "selectedRange -> (NSNotFound, %u)", result.length);
1294 LOG(TextInput, "selectedRange -> (%u, %u)", result.location, result.length);
1299 - (BOOL)hasMarkedText
1301 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1305 result = _data->_page->editorState().hasComposition;
1307 // A saved command can confirm a composition, but it cannot start a new one.
1308 [self _executeSavedKeypressCommands];
1309 result = _data->_page->editorState().hasComposition;
1314 _data->_page->getMarkedRange(location, length);
1315 result = location != NSNotFound;
1318 LOG(TextInput, "hasMarkedText -> %u", result);
1324 [self _executeSavedKeypressCommands];
1326 LOG(TextInput, "unmarkText");
1328 // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
1329 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1332 parameters->eventInterpretationHadSideEffects = true;
1333 parameters->consumedByIM = false;
1336 _data->_page->confirmComposition();
1339 - (NSArray *)validAttributesForMarkedText
1341 static NSArray *validAttributes;
1342 if (!validAttributes) {
1343 validAttributes = [[NSArray alloc] initWithObjects:
1344 NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
1345 NSMarkedClauseSegmentAttributeName, nil];
1346 // NSText also supports the following attributes, but it's
1347 // hard to tell which are really required for text input to
1348 // work well; I have not seen any input method make use of them yet.
1349 // NSFontAttributeName, NSForegroundColorAttributeName,
1350 // NSBackgroundColorAttributeName, NSLanguageAttributeName.
1351 CFRetain(validAttributes);
1353 LOG(TextInput, "validAttributesForMarkedText -> (...)");
1354 return validAttributes;
1357 static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result)
1359 int length = [[string string] length];
1362 while (i < length) {
1364 NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)];
1366 if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
1367 Color color = Color::black;
1368 if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName])
1369 color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
1370 result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1));
1373 i = range.location + range.length;
1377 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange replacementRange:(NSRange)replacementRange
1379 [self _executeSavedKeypressCommands];
1381 BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1382 ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1384 LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelRange.location, newSelRange.length);
1386 // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
1387 WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1390 parameters->eventInterpretationHadSideEffects = true;
1391 parameters->consumedByIM = false;
1394 Vector<CompositionUnderline> underlines;
1397 if (isAttributedString) {
1398 // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation.
1399 text = [string string];
1400 extractUnderlines(string, underlines);
1404 if (_data->_page->editorState().isInPasswordField) {
1405 // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField.
1406 // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard.
1407 ASSERT(!_data->_page->editorState().hasComposition);
1408 [[super inputContext] discardMarkedText]; // Inform the input method that we won't have an inline input area despite having been asked to.
1409 if ([text length] == 1 && [[text decomposedStringWithCanonicalMapping] characterAtIndex:0] < 0x80) {
1410 _data->_page->insertText(text, replacementRange.location, NSMaxRange(replacementRange));
1416 _data->_page->setComposition(text, underlines, newSelRange.location, NSMaxRange(newSelRange), replacementRange.location, NSMaxRange(replacementRange));
1419 - (NSRange)markedRange
1421 [self _executeSavedKeypressCommands];
1425 _data->_page->getMarkedRange(location, length);
1427 LOG(TextInput, "markedRange -> (%u, %u)", location, length);
1428 return NSMakeRange(location, length);
1431 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
1433 [self _executeSavedKeypressCommands];
1435 if (!_data->_page->editorState().isContentEditable) {
1436 LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> nil", nsRange.location, nsRange.length);
1440 if (_data->_page->editorState().isInPasswordField)
1443 AttributedString result;
1444 _data->_page->getAttributedSubstringFromRange(nsRange.location, NSMaxRange(nsRange), result);
1447 *actualRange = nsRange;
1449 LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> \"%@\"", nsRange.location, nsRange.length, [result.string.get() string]);
1450 return [[result.string.get() retain] autorelease];
1453 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1455 [self _executeSavedKeypressCommands];
1457 NSWindow *window = [self window];
1460 thePoint = [window convertScreenToBase:thePoint];
1461 thePoint = [self convertPoint:thePoint fromView:nil]; // the point is relative to the main frame
1463 uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint));
1464 LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result);
1468 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
1470 [self _executeSavedKeypressCommands];
1472 // Just to match NSTextView's behavior. Regression tests cannot detect this;
1473 // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
1474 // (type something; try ranges (1, -1) and (2, -1).
1475 if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
1476 theRange.length = 0;
1478 NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange.location, theRange.length);
1479 resultRect = [self convertRect:resultRect toView:nil];
1481 NSWindow *window = [self window];
1483 resultRect.origin = [window convertBaseToScreen:resultRect.origin];
1486 *actualRange = theRange;
1488 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);
1492 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
1494 NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
1495 NSPoint windowMouseLoc = windowImageLoc;
1497 // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
1498 _data->_ignoringMouseDraggedEvents = YES;
1500 _data->_page->dragEnded(IntPoint(windowMouseLoc), globalPoint(windowMouseLoc, [self window]), operation);
1503 - (DragApplicationFlags)applicationFlags:(id <NSDraggingInfo>)draggingInfo
1506 if ([NSApp modalWindow])
1507 flags = DragApplicationIsModal;
1508 if ([[self window] attachedSheet])
1509 flags |= DragApplicationHasAttachedSheet;
1510 if ([draggingInfo draggingSource] == self)
1511 flags |= DragApplicationIsSource;
1512 if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1513 flags |= DragApplicationIsCopyKeyDown;
1514 return static_cast<DragApplicationFlags>(flags);
1517 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
1519 IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1520 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1521 DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1523 _data->_page->resetDragOperation();
1524 _data->_page->dragEntered(&dragData, [[draggingInfo draggingPasteboard] name]);
1525 return NSDragOperationCopy;
1528 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
1530 IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1531 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1532 DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1533 _data->_page->dragUpdated(&dragData, [[draggingInfo draggingPasteboard] name]);
1534 return _data->_page->dragOperation();
1537 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
1539 IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1540 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1541 DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1542 _data->_page->dragExited(&dragData, [[draggingInfo draggingPasteboard] name]);
1543 _data->_page->resetDragOperation();
1546 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
1551 // FIXME: This code is more or less copied from Pasteboard::getBestURL.
1552 // It would be nice to be able to share the code somehow.
1553 static void maybeCreateSandboxExtensionFromPasteboard(NSPasteboard *pasteboard, SandboxExtension::Handle& sandboxExtensionHandle)
1555 NSArray *types = [pasteboard types];
1556 if (![types containsObject:NSFilenamesPboardType])
1559 NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
1560 if ([files count] != 1)
1563 NSString *file = [files objectAtIndex:0];
1565 if (![[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory])
1571 SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle);
1574 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
1576 IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1577 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1578 DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1580 SandboxExtension::Handle sandboxExtensionHandle;
1581 maybeCreateSandboxExtensionFromPasteboard([draggingInfo draggingPasteboard], sandboxExtensionHandle);
1583 _data->_page->performDrag(&dragData, [[draggingInfo draggingPasteboard] name], sandboxExtensionHandle);
1588 // This code is needed to support drag and drop when the drag types cannot be matched.
1589 // This is the case for elements that do not place content
1590 // in the drag pasteboard automatically when the drag start (i.e. dragging a DIV element).
1591 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
1593 if ([[self superview] mouse:*point inRect:[self frame]])
1598 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)loc
1600 NSPoint localPoint = [self convertPoint:loc fromView:nil];
1601 NSRect visibleThumbRect = NSRect(_data->_page->visibleScrollerThumbRect());
1602 return NSMouseInRect(localPoint, visibleThumbRect, [self isFlipped]);
1605 - (void)_updateWindowVisibility
1607 _data->_page->updateWindowIsVisible(![[self window] isMiniaturized]);
1610 - (BOOL)_ownsWindowGrowBox
1612 NSWindow* window = [self window];
1616 NSView *superview = [self superview];
1620 NSRect growBoxRect = [window _growBoxRect];
1621 if (NSIsEmptyRect(growBoxRect))
1624 NSRect visibleRect = [self visibleRect];
1625 if (NSIsEmptyRect(visibleRect))
1628 NSRect visibleRectInWindowCoords = [self convertRect:visibleRect toView:nil];
1629 if (!NSIntersectsRect(growBoxRect, visibleRectInWindowCoords))
1635 - (BOOL)_updateGrowBoxForWindowFrameChange
1637 // Temporarily enable the resize indicator to make a the _ownsWindowGrowBox calculation work.
1638 BOOL wasShowingIndicator = [[self window] showsResizeIndicator];
1639 if (!wasShowingIndicator)
1640 [[self window] setShowsResizeIndicator:YES];
1642 BOOL ownsGrowBox = [self _ownsWindowGrowBox];
1643 _data->_page->setWindowResizerSize(ownsGrowBox ? enclosingIntRect([[self window] _growBoxRect]).size() : IntSize());
1646 [[self window] _setShowOpaqueGrowBoxForOwner:(_data->_page->hasHorizontalScrollbar() || _data->_page->hasVerticalScrollbar() ? self : nil)];
1648 [[self window] _setShowOpaqueGrowBoxForOwner:nil];
1650 // Once WebCore can draw the window resizer, this should read:
1651 // if (wasShowingIndicator)
1652 // [[self window] setShowsResizeIndicator:!ownsGrowBox];
1653 if (!wasShowingIndicator)
1654 [[self window] setShowsResizeIndicator:NO];
1659 - (void)addWindowObserversForWindow:(NSWindow *)window
1662 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
1663 name:NSWindowDidBecomeKeyNotification object:nil];
1664 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
1665 name:NSWindowDidResignKeyNotification object:nil];
1666 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:)
1667 name:NSWindowDidMiniaturizeNotification object:window];
1668 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
1669 name:NSWindowDidDeminiaturizeNotification object:window];
1670 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:)
1671 name:NSWindowDidMoveNotification object:window];
1672 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:)
1673 name:NSWindowDidResizeNotification object:window];
1674 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOffScreen:)
1675 name:@"NSWindowDidOrderOffScreenNotification" object:window];
1676 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOnScreen:)
1677 name:@"_NSWindowDidBecomeVisible" object:window];
1681 - (void)removeWindowObservers
1683 NSWindow *window = [self window];
1687 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
1688 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
1689 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
1690 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
1691 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
1692 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
1693 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowDidOrderOffScreenNotification" object:window];
1694 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"_NSWindowDidBecomeVisible" object:window];
1697 - (void)viewWillMoveToWindow:(NSWindow *)window
1699 NSWindow *currentWindow = [self window];
1700 if (window == currentWindow)
1703 [self removeWindowObservers];
1704 [self addWindowObserversForWindow:window];
1706 if ([currentWindow _growBoxOwner] == self)
1707 [currentWindow _setShowOpaqueGrowBoxForOwner:nil];
1710 - (void)viewDidMoveToWindow
1712 // We want to make sure to update the active state while hidden, so if the view is about to become visible, we
1713 // update the active state first and then make it visible. If the view is about to be hidden, we hide it first and then
1714 // update the active state.
1715 if ([self window]) {
1716 _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1717 _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible | WebPageProxy::ViewIsInWindow);
1718 [self _updateWindowVisibility];
1719 [self _updateWindowAndViewFrames];
1721 // Initialize remote accessibility when the window connection has been established.
1722 #if !defined(BUILDING_ON_SNOW_LEOPARD)
1723 NSData *remoteElementToken = WKAXRemoteTokenForElement(self);
1724 NSData *remoteWindowToken = WKAXRemoteTokenForElement([self accessibilityAttributeValue:NSAccessibilityWindowAttribute]);
1725 CoreIPC::DataReference elementToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteElementToken bytes]), [remoteElementToken length]);
1726 CoreIPC::DataReference windowToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteWindowToken bytes]), [remoteWindowToken length]);
1727 _data->_page->registerUIProcessAccessibilityTokens(elementToken, windowToken);
1731 _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1732 _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive | WebPageProxy::ViewIsInWindow);
1734 #if ENABLE(GESTURE_EVENTS)
1735 if (_data->_endGestureMonitor) {
1736 [NSEvent removeMonitor:_data->_endGestureMonitor];
1737 _data->_endGestureMonitor = nil;
1740 #if !defined(BUILDING_ON_SNOW_LEOPARD)
1741 WKHideWordDefinitionWindow();
1746 - (void)_windowDidBecomeKey:(NSNotification *)notification
1748 NSWindow *keyWindow = [notification object];
1749 if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet]) {
1750 [self _updateSecureInputState];
1751 _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1755 - (void)_windowDidResignKey:(NSNotification *)notification
1757 NSWindow *formerKeyWindow = [notification object];
1758 if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) {
1759 [self _updateSecureInputState];
1760 _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1764 - (void)_windowDidMiniaturize:(NSNotification *)notification
1766 [self _updateWindowVisibility];
1769 - (void)_windowDidDeminiaturize:(NSNotification *)notification
1771 [self _updateWindowVisibility];
1774 - (void)_windowFrameDidChange:(NSNotification *)notification
1776 [self _updateWindowAndViewFrames];
1779 - (void)_windowDidOrderOffScreen:(NSNotification *)notification
1781 _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1784 - (void)_windowDidOrderOnScreen:(NSNotification *)notification
1786 _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1789 static void drawPageBackground(CGContextRef context, WebPageProxy* page, const IntRect& rect)
1791 if (!page->drawsBackground())
1794 CGContextSaveGState(context);
1795 CGContextSetBlendMode(context, kCGBlendModeCopy);
1797 CGColorRef backgroundColor;
1798 if (page->drawsTransparentBackground())
1799 backgroundColor = CGColorGetConstantColor(kCGColorClear);
1801 backgroundColor = CGColorGetConstantColor(kCGColorWhite);
1803 CGContextSetFillColorWithColor(context, backgroundColor);
1804 CGContextFillRect(context, rect);
1806 CGContextRestoreGState(context);
1809 - (void)drawRect:(NSRect)rect
1811 LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1812 _data->_page->endPrinting();
1813 CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
1815 if (DrawingAreaProxyImpl* drawingArea = static_cast<DrawingAreaProxyImpl*>(_data->_page->drawingArea())) {
1816 const NSRect *rectsBeingDrawn;
1817 NSInteger numRectsBeingDrawn;
1818 [self getRectsBeingDrawn:&rectsBeingDrawn count:&numRectsBeingDrawn];
1819 for (NSInteger i = 0; i < numRectsBeingDrawn; ++i) {
1820 Region unpaintedRegion;
1821 IntRect rect = enclosingIntRect(rectsBeingDrawn[i]);
1822 drawingArea->paint(context, rect, unpaintedRegion);
1824 Vector<IntRect> unpaintedRects = unpaintedRegion.rects();
1825 for (size_t i = 0; i < unpaintedRects.size(); ++i)
1826 drawPageBackground(context, _data->_page.get(), unpaintedRects[i]);
1829 drawPageBackground(context, _data->_page.get(), enclosingIntRect(rect));
1831 _data->_page->didDraw();
1836 return _data->_page->drawsBackground();
1839 - (BOOL)mouseDownCanMoveWindow
1841 // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent,
1842 // but we don't want a drag in the NSView to move the window, even if it's transparent.
1848 _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1851 - (void)viewDidUnhide
1853 _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1856 - (id)accessibilityFocusedUIElement
1858 if (_data->_pdfViewController)
1859 return NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView());
1861 return _data->_remoteAccessibilityChild.get();
1864 - (BOOL)accessibilityIsIgnored
1869 - (id)accessibilityHitTest:(NSPoint)point
1871 if (_data->_pdfViewController)
1872 return [_data->_pdfViewController->pdfView() accessibilityHitTest:point];
1874 return _data->_remoteAccessibilityChild.get();
1877 - (id)accessibilityAttributeValue:(NSString*)attribute
1879 if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
1882 if (_data->_pdfViewController)
1883 child = NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView());
1884 else if (_data->_remoteAccessibilityChild)
1885 child = _data->_remoteAccessibilityChild.get();
1889 return [NSArray arrayWithObject:child];
1891 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
1892 return NSAccessibilityGroupRole;
1893 if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
1894 return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil);
1895 if ([attribute isEqualToString:NSAccessibilityParentAttribute])
1896 return NSAccessibilityUnignoredAncestor([self superview]);
1897 if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
1898 return [NSNumber numberWithBool:YES];
1900 return [super accessibilityAttributeValue:attribute];
1903 - (NSView *)hitTest:(NSPoint)point
1905 NSView *hitView = [super hitTest:point];
1906 if (hitView && _data && hitView == _data->_layerHostingView)
1912 - (NSInteger)conversationIdentifier
1914 return (NSInteger)self;
1918 - (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef
1920 // PDF documents are already paginated, so we can't change them to add headers and footers.
1921 return !toImpl(frameRef)->isMainFrame() || !_data->_pdfViewController;
1924 - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef
1926 LOG(View, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data());
1928 // Only the top frame can currently contain a PDF view.
1929 if (_data->_pdfViewController) {
1930 if (!toImpl(frameRef)->isMainFrame())
1932 return _data->_pdfViewController->makePrintOperation(printInfo);
1934 RetainPtr<WKPrintingView> printingView(AdoptNS, [[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef) view:self]);
1935 // NSPrintOperation takes ownership of the view.
1936 NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get()];
1937 [printOperation setCanSpawnSeparateThread:YES];
1938 [printOperation setJobTitle:toImpl(frameRef)->title()];
1939 printingView->_printOperation = printOperation;
1940 return printOperation;
1946 @implementation WKView (Internal)
1948 - (PassOwnPtr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy
1950 return DrawingAreaProxyImpl::create(_data->_page.get());
1955 if (_data->_inBecomeFirstResponder)
1957 if (_data->_inResignFirstResponder)
1959 return [[self window] firstResponder] == self;
1962 - (void)_processDidCrash
1964 [self setNeedsDisplay:YES];
1965 [self _updateRemoteAccessibilityRegistration:NO];
1970 [self _updateRemoteAccessibilityRegistration:NO];
1973 - (void)_didRelaunchProcess
1975 [self setNeedsDisplay:YES];
1978 - (void)_setCursor:(NSCursor *)cursor
1980 if ([NSCursor currentCursor] == cursor)
1985 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
1987 ValidationVector items = _data->_validationMap.take(commandName);
1988 size_t size = items.size();
1989 for (size_t i = 0; i < size; ++i) {
1990 ValidationItem item = items[i].get();
1991 [menuItem(item) setState:newState];
1992 [menuItem(item) setEnabled:isEnabled];
1993 [toolbarItem(item) setEnabled:isEnabled];
1994 // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
1998 - (void)_resendKeyDownEvent:(NSEvent *)event
2000 // resending the event may destroy this WKView
2001 RetainPtr<WKView> protect(self);
2003 ASSERT(!_data->_keyDownEventBeingResent);
2004 _data->_keyDownEventBeingResent = event;
2005 [NSApp _setCurrentEvent:event];
2006 [NSApp sendEvent:event];
2008 _data->_keyDownEventBeingResent = nullptr;
2011 - (BOOL)_interpretKeyEvent:(NSEvent *)event savingCommandsTo:(Vector<WebCore::KeypressCommand>&)commands
2013 ASSERT(!_data->_interpretKeyEventsParameters);
2014 ASSERT(commands.isEmpty());
2016 if ([event type] == NSFlagsChanged)
2019 WKViewInterpretKeyEventsParameters parameters;
2020 parameters.eventInterpretationHadSideEffects = false;
2021 parameters.executingSavedKeypressCommands = false;
2022 // We assume that an input method has consumed the event, and only change this assumption if one of the NSTextInput methods is called.
2023 // We assume the IM will *not* consume hotkey sequences.
2024 parameters.consumedByIM = !([event modifierFlags] & NSCommandKeyMask);
2025 parameters.commands = &commands;
2026 _data->_interpretKeyEventsParameters = ¶meters;
2028 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2030 _data->_interpretKeyEventsParameters = 0;
2032 // An input method may consume an event and not tell us (e.g. when displaying a candidate window),
2033 // in which case we should not bubble the event up the DOM.
2034 if (parameters.consumedByIM)
2037 // 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.
2038 return parameters.eventInterpretationHadSideEffects;
2041 - (NSRect)_convertToDeviceSpace:(NSRect)rect
2043 return toDeviceSpace(rect, [self window]);
2046 - (NSRect)_convertToUserSpace:(NSRect)rect
2048 return toUserSpace(rect, [self window]);
2051 // Any non-zero value will do, but using something recognizable might help us debug some day.
2052 #define TRACKING_RECT_TAG 0xBADFACE
2054 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2056 ASSERT(_data->_trackingRectOwner == nil);
2057 _data->_trackingRectOwner = owner;
2058 _data->_trackingRectUserData = data;
2059 return TRACKING_RECT_TAG;
2062 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2064 ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
2065 ASSERT(_data->_trackingRectOwner == nil);
2066 _data->_trackingRectOwner = owner;
2067 _data->_trackingRectUserData = data;
2068 return TRACKING_RECT_TAG;
2071 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
2074 ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
2075 ASSERT(_data->_trackingRectOwner == nil);
2076 _data->_trackingRectOwner = owner;
2077 _data->_trackingRectUserData = userDataList[0];
2078 trackingNums[0] = TRACKING_RECT_TAG;
2081 - (void)removeTrackingRect:(NSTrackingRectTag)tag
2089 if (tag == TRACKING_RECT_TAG) {
2090 _data->_trackingRectOwner = nil;
2094 if (tag == _data->_lastToolTipTag) {
2095 [super removeTrackingRect:tag];
2096 _data->_lastToolTipTag = 0;
2100 // If any other tracking rect is being removed, we don't know how it was created
2101 // and it's possible there's a leak involved (see 3500217)
2102 ASSERT_NOT_REACHED();
2105 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
2108 for (i = 0; i < count; ++i) {
2112 ASSERT(tag == TRACKING_RECT_TAG);
2114 _data->_trackingRectOwner = nil;
2119 - (void)_sendToolTipMouseExited
2121 // Nothing matters except window, trackingNumber, and userData.
2122 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
2123 location:NSMakePoint(0, 0)
2126 windowNumber:[[self window] windowNumber]
2129 trackingNumber:TRACKING_RECT_TAG
2130 userData:_data->_trackingRectUserData];
2131 [_data->_trackingRectOwner mouseExited:fakeEvent];
2134 - (void)_sendToolTipMouseEntered
2136 // Nothing matters except window, trackingNumber, and userData.
2137 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
2138 location:NSMakePoint(0, 0)
2141 windowNumber:[[self window] windowNumber]
2144 trackingNumber:TRACKING_RECT_TAG
2145 userData:_data->_trackingRectUserData];
2146 [_data->_trackingRectOwner mouseEntered:fakeEvent];
2149 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
2151 return nsStringFromWebCoreString(_data->_page->toolTip());
2154 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
2157 [self _sendToolTipMouseExited];
2159 if (newToolTip && [newToolTip length] > 0) {
2160 // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
2161 [self removeAllToolTips];
2162 NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
2163 _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
2164 [self _sendToolTipMouseEntered];
2168 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut
2170 if (!findIndicator) {
2171 _data->_findIndicatorWindow = 0;
2175 if (!_data->_findIndicatorWindow)
2176 _data->_findIndicatorWindow = FindIndicatorWindow::create(self);
2178 _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut);
2181 - (void)_enterAcceleratedCompositingMode:(const LayerTreeContext&)layerTreeContext
2183 ASSERT(!_data->_layerHostingView);
2184 ASSERT(!layerTreeContext.isEmpty());
2186 // Create an NSView that will host our layer tree.
2187 _data->_layerHostingView.adoptNS([[NSView alloc] initWithFrame:[self bounds]]);
2188 [_data->_layerHostingView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
2190 [CATransaction begin];
2191 [CATransaction setDisableActions:YES];
2192 [self addSubview:_data->_layerHostingView.get()];
2194 // Create a root layer that will back the NSView.
2195 RetainPtr<CALayer> rootLayer(AdoptNS, [[CALayer alloc] init]);
2197 [rootLayer.get() setName:@"Hosting root layer"];
2200 CALayer *renderLayer = WKMakeRenderLayer(layerTreeContext.contextID);
2201 [rootLayer.get() addSublayer:renderLayer];
2203 [_data->_layerHostingView.get() setLayer:rootLayer.get()];
2204 [_data->_layerHostingView.get() setWantsLayer:YES];
2206 [CATransaction commit];
2209 - (void)_exitAcceleratedCompositingMode
2211 ASSERT(_data->_layerHostingView);
2213 [_data->_layerHostingView.get() removeFromSuperview];
2214 [_data->_layerHostingView.get() setLayer:nil];
2215 [_data->_layerHostingView.get() setWantsLayer:NO];
2217 _data->_layerHostingView = nullptr;
2220 - (void)_setAccessibilityWebProcessToken:(NSData *)data
2222 #if !defined(BUILDING_ON_SNOW_LEOPARD)
2223 _data->_remoteAccessibilityChild = WKAXRemoteElementForToken(data);
2224 [self _updateRemoteAccessibilityRegistration:YES];
2228 - (void)_setComplexTextInputEnabled:(BOOL)complexTextInputEnabled pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
2230 BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
2232 if (complexTextInputEnabled) {
2233 // Check if we're already allowing text input for this plug-in.
2234 if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
2237 _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
2240 // Check if we got a request to disable complex text input for a plug-in that is not the current plug-in.
2241 if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
2244 _data->_pluginComplexTextInputIdentifier = 0;
2247 if (inputSourceChanged) {
2248 // Inform the out of line window that the input source changed.
2249 [[WKTextInputWindowController sharedTextInputWindowController] keyboardInputSourceChanged];
2253 - (void)_setPageHasCustomRepresentation:(BOOL)pageHasCustomRepresentation
2255 _data->_pdfViewController = nullptr;
2257 if (pageHasCustomRepresentation)
2258 _data->_pdfViewController = PDFViewController::create(self);
2261 - (void)_didFinishLoadingDataForCustomRepresentationWithSuggestedFilename:(const String&)suggestedFilename dataReference:(const CoreIPC::DataReference&)dataReference
2263 ASSERT(_data->_pdfViewController);
2265 _data->_pdfViewController->setPDFDocumentData(_data->_page->mainFrame()->mimeType(), suggestedFilename, dataReference);
2268 - (double)_customRepresentationZoomFactor
2270 if (!_data->_pdfViewController)
2273 return _data->_pdfViewController->zoomFactor();
2276 - (void)_setCustomRepresentationZoomFactor:(double)zoomFactor
2278 if (!_data->_pdfViewController)
2281 _data->_pdfViewController->setZoomFactor(zoomFactor);
2284 - (void)_findStringInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count
2286 if (!_data->_pdfViewController)
2289 _data->_pdfViewController->findString(string, options, count);
2292 - (void)_countStringMatchesInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count
2294 if (!_data->_pdfViewController)
2297 _data->_pdfViewController->countStringMatches(string, options, count);
2300 - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag
2302 // We need to prevent re-entering this call to avoid crashing in AppKit.
2303 // Given the asynchronous nature of WebKit2 this can now happen.
2304 if (_data->_dragHasStarted)
2307 _data->_dragHasStarted = YES;
2308 [super dragImage:image
2311 event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent
2312 pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
2315 _data->_dragHasStarted = NO;
2318 - (void)_updateSecureInputState
2320 if (![[self window] isKeyWindow] || ![self _isFocused]) {
2321 if (_data->_inSecureInputState) {
2322 DisableSecureEventInput();
2323 _data->_inSecureInputState = NO;
2327 // WKView has a single input context for all editable areas (except for plug-ins).
2328 NSTextInputContext *context = [super inputContext];
2329 bool isInPasswordField = _data->_page->editorState().isInPasswordField;
2331 if (isInPasswordField) {
2332 if (!_data->_inSecureInputState)
2333 EnableSecureEventInput();
2334 static NSArray *romanInputSources = [[NSArray alloc] initWithObjects:&NSAllRomanInputSourcesLocaleIdentifier count:1];
2335 [context setAllowedInputSourceLocales:romanInputSources];
2337 if (_data->_inSecureInputState)
2338 DisableSecureEventInput();
2339 [context setAllowedInputSourceLocales:nil];
2341 _data->_inSecureInputState = isInPasswordField;
2344 - (void)_updateTextInputStateIncludingSecureInputState:(BOOL)updateSecureInputState
2346 const EditorState& editorState = _data->_page->editorState();
2347 if (updateSecureInputState) {
2348 // This is a temporary state when editing. Flipping secure input state too quickly can expose race conditions.
2349 if (!editorState.selectionIsNone)
2350 [self _updateSecureInputState];
2353 if (!editorState.hasComposition || editorState.shouldIgnoreCompositionSelectionChange)
2356 _data->_page->confirmCompositionWithoutDisturbingSelection();
2357 [[super inputContext] discardMarkedText];
2360 - (void)_resetTextInputState
2362 [[super inputContext] discardMarkedText];
2364 if (_data->_inSecureInputState) {
2365 DisableSecureEventInput();
2366 _data->_inSecureInputState = NO;
2370 - (void)_setDrawingAreaSize:(NSSize)size
2372 if (!_data->_page->drawingArea())
2375 _data->_page->drawingArea()->setSize(IntSize(size), IntSize(_data->_resizeScrollOffset));
2376 _data->_resizeScrollOffset = NSZeroSize;
2379 - (void)_didChangeScrollbarsForMainFrame
2381 [self _updateGrowBoxForWindowFrameChange];
2384 #if ENABLE(FULLSCREEN_API)
2385 - (WKFullScreenWindowController*)fullScreenWindowController
2387 if (!_data->_fullScreenWindowController) {
2388 _data->_fullScreenWindowController.adoptNS([[WKFullScreenWindowController alloc] init]);
2389 [_data->_fullScreenWindowController.get() setWebView:self];
2391 return _data->_fullScreenWindowController.get();
2395 - (bool)_executeSavedCommandBySelector:(SEL)selector
2397 // The sink does two things: 1) Tells us if the responder went unhandled, and
2398 // 2) prevents any NSBeep; we don't ever want to beep here.
2399 RetainPtr<WKResponderChainSink> sink(AdoptNS, [[WKResponderChainSink alloc] initWithResponderChain:self]);
2400 [super doCommandBySelector:selector];
2401 [sink.get() detach];
2402 return ![sink.get() didReceiveUnhandledCommand];
2407 @implementation WKView (Private)
2409 - (void)disableFrameSizeUpdates
2411 _frameSizeUpdatesDisabledCount++;
2414 - (void)enableFrameSizeUpdates
2416 if (!_frameSizeUpdatesDisabledCount)
2419 if (!(--_frameSizeUpdatesDisabledCount))
2420 [self _setDrawingAreaSize:[self frame].size];
2423 - (BOOL)frameSizeUpdatesDisabled
2425 return _frameSizeUpdatesDisabledCount > 0;
2428 - (void)performDictionaryLookupAtCurrentMouseLocation
2430 NSPoint thePoint = [NSEvent mouseLocation];
2431 thePoint = [[self window] convertScreenToBase:thePoint];
2432 thePoint = [self convertPoint:thePoint fromView:nil];
2434 _data->_page->performDictionaryLookupAtLocation(FloatPoint(thePoint.x, thePoint.y));
2437 - (NSInteger)spellCheckerDocumentTag
2439 if (!_data->_hasSpellCheckerDocumentTag) {
2440 _data->_spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
2441 _data->_hasSpellCheckerDocumentTag = YES;
2443 return _data->_spellCheckerDocumentTag;
2446 - (void)handleCorrectionPanelResult:(NSString*)result
2448 _data->_page->handleCorrectionPanelResult(result);
2453 @implementation WKResponderChainSink
2455 - (id)initWithResponderChain:(NSResponder *)chain
2457 self = [super init];
2460 _lastResponderInChain = chain;
2461 while (NSResponder *next = [_lastResponderInChain nextResponder])
2462 _lastResponderInChain = next;
2463 [_lastResponderInChain setNextResponder:self];
2469 [_lastResponderInChain setNextResponder:nil];
2470 _lastResponderInChain = nil;
2473 - (bool)didReceiveUnhandledCommand
2475 return _didReceiveUnhandledCommand;
2478 - (void)noResponderFor:(SEL)selector
2480 _didReceiveUnhandledCommand = true;
2483 - (void)doCommandBySelector:(SEL)selector
2485 _didReceiveUnhandledCommand = true;
2488 - (BOOL)tryToPerform:(SEL)action with:(id)object
2490 _didReceiveUnhandledCommand = true;