2a42319b4a9b48981f570090cc7bfbda6a06f003
[WebKit-https.git] / Source / WebKit2 / UIProcess / API / mac / WKView.mm
1 /*
2  * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "WKView.h"
28
29 #import "ChunkedUpdateDrawingAreaProxy.h"
30 #import "DataReference.h"
31 #import "DrawingAreaProxyImpl.h"
32 #import "FindIndicator.h"
33 #import "FindIndicatorWindow.h"
34 #import "LayerTreeContext.h"
35 #import "Logging.h"
36 #import "NativeWebKeyboardEvent.h"
37 #import "PDFViewController.h"
38 #import "PageClientImpl.h"
39 #import "PasteboardTypes.h"
40 #import "Region.h"
41 #import "RunLoop.h"
42 #import "TextChecker.h"
43 #import "TextCheckerState.h"
44 #import "WKAPICast.h"
45 #import "WKFullScreenWindowController.h"
46 #import "WKPrintingView.h"
47 #import "WKStringCF.h"
48 #import "WKTextInputWindowController.h"
49 #import "WKViewInternal.h"
50 #import "WKViewPrivate.h"
51 #import "WebContext.h"
52 #import "WebEventFactory.h"
53 #import "WebFullScreenManagerProxy.h"
54 #import "WebPage.h"
55 #import "WebPageProxy.h"
56 #import "WebProcessProxy.h"
57 #import "WebSystemInterface.h"
58 #import <QuartzCore/QuartzCore.h>
59 #import <WebCore/ColorMac.h>
60 #import <WebCore/DragController.h>
61 #import <WebCore/DragData.h>
62 #import <WebCore/FloatRect.h>
63 #import <WebCore/IntRect.h>
64 #import <WebCore/KeyboardEvent.h>
65 #import <WebCore/PlatformMouseEvent.h>
66 #import <WebCore/PlatformScreen.h>
67 #import <WebKitSystemInterface.h>
68 #import <wtf/RefPtr.h>
69 #import <wtf/RetainPtr.h>
70
71 // FIXME (WebKit2) <rdar://problem/8728860> WebKit2 needs to be localized
72 #define UI_STRING(__str, __desc) [NSString stringWithUTF8String:__str]
73
74 @interface NSApplication (WebNSApplicationDetails)
75 - (void)speakString:(NSString *)string;
76 - (void)_setCurrentEvent:(NSEvent *)event;
77 @end
78
79 @interface NSWindow (WebNSWindowDetails)
80 - (NSRect)_growBoxRect;
81 - (id)_growBoxOwner;
82 - (void)_setShowOpaqueGrowBoxForOwner:(id)owner;
83 - (BOOL)_updateGrowBoxForWindowFrameChange;
84 @end
85
86 extern "C" {
87     // Need to declare this attribute name because AppKit exports it but does not make it available in API or SPI headers.
88     // <rdar://problem/8631468> tracks the request to make it available. This code should be removed when the bug is closed.
89     extern NSString *NSTextInputReplacementRangeAttributeName;
90 }
91
92 using namespace WebKit;
93 using namespace WebCore;
94
95 namespace WebKit {
96
97 typedef id <NSValidatedUserInterfaceItem> ValidationItem;
98 typedef Vector<RetainPtr<ValidationItem> > ValidationVector;
99 typedef HashMap<String, ValidationVector> ValidationMap;
100
101 }
102
103 @interface WKViewData : NSObject {
104 @public
105     OwnPtr<PageClientImpl> _pageClient;
106     RefPtr<WebPageProxy> _page;
107
108     // For ToolTips.
109     NSToolTipTag _lastToolTipTag;
110     id _trackingRectOwner;
111     void* _trackingRectUserData;
112
113     RetainPtr<NSView> _layerHostingView;
114
115     RetainPtr<id> _remoteAccessibilityChild;
116     
117     // For asynchronous validation.
118     ValidationMap _validationMap;
119
120     OwnPtr<PDFViewController> _pdfViewController;
121
122     OwnPtr<FindIndicatorWindow> _findIndicatorWindow;
123     // We keep here the event when resending it to
124     // the application to distinguish the case of a new event from one 
125     // that has been already sent to WebCore.
126     RetainPtr<NSEvent> _keyDownEventBeingResent;
127     bool _isInInterpretKeyEvents;
128     Vector<KeypressCommand> _commandsList;
129
130     NSSize _resizeScrollOffset;
131
132     // The identifier of the plug-in we want to send complex text input to, or 0 if there is none.
133     uint64_t _pluginComplexTextInputIdentifier;
134
135     Vector<CompositionUnderline> _underlines;
136     unsigned _selectionStart;
137     unsigned _selectionEnd;
138
139     bool _inBecomeFirstResponder;
140     bool _inResignFirstResponder;
141     NSEvent *_mouseDownEvent;
142     BOOL _ignoringMouseDraggedEvents;
143     BOOL _dragHasStarted;
144
145 #if ENABLE(GESTURE_EVENTS)
146     id _endGestureMonitor;
147 #endif
148     
149 #if ENABLE(FULLSCREEN_API)
150     RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
151 #endif
152 }
153 @end
154
155 @implementation WKViewData
156 @end
157
158 @interface NSObject (NSTextInputContextDetails)
159 - (BOOL)wantsToHandleMouseEvents;
160 - (BOOL)handleMouseEvent:(NSEvent *)event;
161 @end
162
163 @implementation WKView
164
165 - (void)_registerDraggedTypes
166 {
167     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:PasteboardTypes::forEditing()];
168     [types addObjectsFromArray:PasteboardTypes::forURL()];
169     [self registerForDraggedTypes:[types allObjects]];
170     [types release];
171 }
172
173 - (void)_updateRemoteAccessibilityRegistration:(BOOL)registerProcess
174 {
175 #if !defined(BUILDING_ON_SNOW_LEOPARD)
176     // When the tree is connected/disconnected, the remote accessibility registration
177     // needs to be updated with the pid of the remote process. If the process is going
178     // away, that information is not present in WebProcess
179     pid_t pid = 0;
180     if (registerProcess && _data->_page->process())
181         pid = _data->_page->process()->processIdentifier();
182     else if (!registerProcess) {
183         pid = WKAXRemoteProcessIdentifier(_data->_remoteAccessibilityChild.get());
184         _data->_remoteAccessibilityChild = nil;
185     }
186     if (pid)
187         WKAXRegisterRemoteProcess(registerProcess, pid); 
188 #endif
189 }
190
191 - (id)initWithFrame:(NSRect)frame
192 {
193     return [self initWithFrame:frame contextRef:toAPI(WebContext::sharedProcessContext())];
194 }
195
196 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef
197 {   
198     return [self initWithFrame:frame contextRef:contextRef pageGroupRef:nil];
199 }
200
201 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef
202 {
203     return [self initWithFrame:frame contextRef:contextRef pageGroupRef:pageGroupRef mainFrameName:nil];
204 }
205
206 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef mainFrameName:(NSString *)mainFrameName
207 {
208     self = [super initWithFrame:frame];
209     if (!self)
210         return nil;
211
212     [NSApp registerServicesMenuSendTypes:PasteboardTypes::forSelection() returnTypes:PasteboardTypes::forEditing()];
213
214     InitWebCoreSystemInterface();
215     RunLoop::initializeMainRunLoop();
216
217     NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame
218                                                                 options:(NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect)
219                                                                   owner:self
220                                                                userInfo:nil];
221     [self addTrackingArea:trackingArea];
222     [trackingArea release];
223
224     _data = [[WKViewData alloc] init];
225
226     _data->_pageClient = PageClientImpl::create(self);
227     _data->_page = toImpl(contextRef)->createWebPage(_data->_pageClient.get(), toImpl(pageGroupRef));
228     _data->_page->setMainFrameName(mainFrameName);
229     _data->_page->initializeWebPage();
230
231 #if ENABLE(FULLSCREEN_API)
232     _data->_page->fullScreenManager()->setWebView(self);
233 #endif
234     _data->_mouseDownEvent = nil;
235     _data->_ignoringMouseDraggedEvents = NO;
236
237     [self _registerDraggedTypes];
238
239     WebContext::statistics().wkViewCount++;
240
241     return self;
242 }
243
244 - (void)dealloc
245 {
246     _data->_page->close();
247
248     [_data release];
249
250     WebContext::statistics().wkViewCount--;
251
252     [super dealloc];
253 }
254
255 - (WKPageRef)pageRef
256 {
257     return toAPI(_data->_page.get());
258 }
259
260 - (void)setDrawsBackground:(BOOL)drawsBackground
261 {
262     _data->_page->setDrawsBackground(drawsBackground);
263 }
264
265 - (BOOL)drawsBackground
266 {
267     return _data->_page->drawsBackground();
268 }
269
270 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
271 {
272     _data->_page->setDrawsTransparentBackground(drawsTransparentBackground);
273 }
274
275 - (BOOL)drawsTransparentBackground
276 {
277     return _data->_page->drawsTransparentBackground();
278 }
279
280 - (BOOL)acceptsFirstResponder
281 {
282     return YES;
283 }
284
285 - (BOOL)becomeFirstResponder
286 {
287     NSSelectionDirection direction = [[self window] keyViewSelectionDirection];
288
289     _data->_inBecomeFirstResponder = true;
290     _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
291     _data->_inBecomeFirstResponder = false;
292
293     if (direction != NSDirectSelection)
294         _data->_page->setInitialFocus(direction == NSSelectingNext);
295
296     return YES;
297 }
298
299 - (BOOL)resignFirstResponder
300 {
301     _data->_inResignFirstResponder = true;
302     _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
303     _data->_inResignFirstResponder = false;
304
305     return YES;
306 }
307
308 - (void)viewWillStartLiveResize
309 {
310     _data->_page->viewWillStartLiveResize();
311 }
312
313 - (void)viewDidEndLiveResize
314 {
315     _data->_page->viewWillEndLiveResize();
316 }
317
318 - (BOOL)isFlipped
319 {
320     return YES;
321 }
322
323 - (void)setFrame:(NSRect)rect andScrollBy:(NSSize)offset
324 {
325     ASSERT(NSEqualSizes(_data->_resizeScrollOffset, NSZeroSize));
326
327     _data->_resizeScrollOffset = offset;
328     [self setFrame:rect];
329 }
330
331 - (void)setFrameSize:(NSSize)size
332 {
333     [super setFrameSize:size];
334     
335     if (![self frameSizeUpdatesDisabled])
336         [self _setDrawingAreaSize:size];
337 }
338
339 - (void)_updateWindowAndViewFrames
340 {
341     NSWindow *window = [self window];
342     ASSERT(window);
343     
344     NSRect windowFrameInScreenCoordinates = [window frame];
345     NSRect viewFrameInWindowCoordinates = [self convertRect:[self frame] toView:nil];
346     NSPoint accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue];
347     
348     _data->_page->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates), IntPoint(accessibilityPosition));
349 }
350
351 - (void)renewGState
352 {
353     // Hide the find indicator.
354     _data->_findIndicatorWindow = nullptr;
355
356     // Update the view frame.
357     if ([self window])
358         [self _updateWindowAndViewFrames];
359
360     [super renewGState];
361 }
362
363 typedef HashMap<SEL, String> SelectorNameMap;
364
365 // Map selectors into Editor command names.
366 // This is not needed for any selectors that have the same name as the Editor command.
367 static const SelectorNameMap* createSelectorExceptionMap()
368 {
369     SelectorNameMap* map = new HashMap<SEL, String>;
370     
371     map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
372     map->add(@selector(insertParagraphSeparator:), "InsertNewline");
373     map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
374     map->add(@selector(pageDown:), "MovePageDown");
375     map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
376     map->add(@selector(pageUp:), "MovePageUp");
377     map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
378     map->add(@selector(scrollPageDown:), "ScrollPageForward");
379     map->add(@selector(scrollPageUp:), "ScrollPageBackward");
380     
381     return map;
382 }
383
384 static String commandNameForSelector(SEL selector)
385 {
386     // Check the exception map first.
387     static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
388     SelectorNameMap::const_iterator it = exceptionMap->find(selector);
389     if (it != exceptionMap->end())
390         return it->second;
391     
392     // Remove the trailing colon.
393     // No need to capitalize the command name since Editor command names are
394     // not case sensitive.
395     const char* selectorName = sel_getName(selector);
396     size_t selectorNameLength = strlen(selectorName);
397     if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
398         return String();
399     return String(selectorName, selectorNameLength - 1);
400 }
401
402 // Editing commands
403
404 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
405
406 WEBCORE_COMMAND(alignCenter)
407 WEBCORE_COMMAND(alignJustified)
408 WEBCORE_COMMAND(alignLeft)
409 WEBCORE_COMMAND(alignRight)
410 WEBCORE_COMMAND(copy)
411 WEBCORE_COMMAND(cut)
412 WEBCORE_COMMAND(delete)
413 WEBCORE_COMMAND(deleteBackward)
414 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
415 WEBCORE_COMMAND(deleteForward)
416 WEBCORE_COMMAND(deleteToBeginningOfLine)
417 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
418 WEBCORE_COMMAND(deleteToEndOfLine)
419 WEBCORE_COMMAND(deleteToEndOfParagraph)
420 WEBCORE_COMMAND(deleteToMark)
421 WEBCORE_COMMAND(deleteWordBackward)
422 WEBCORE_COMMAND(deleteWordForward)
423 WEBCORE_COMMAND(ignoreSpelling)
424 WEBCORE_COMMAND(indent)
425 WEBCORE_COMMAND(insertBacktab)
426 WEBCORE_COMMAND(insertLineBreak)
427 WEBCORE_COMMAND(insertNewline)
428 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
429 WEBCORE_COMMAND(insertParagraphSeparator)
430 WEBCORE_COMMAND(insertTab)
431 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
432 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
433 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
434 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
435 WEBCORE_COMMAND(moveBackward)
436 WEBCORE_COMMAND(moveBackwardAndModifySelection)
437 WEBCORE_COMMAND(moveDown)
438 WEBCORE_COMMAND(moveDownAndModifySelection)
439 WEBCORE_COMMAND(moveForward)
440 WEBCORE_COMMAND(moveForwardAndModifySelection)
441 WEBCORE_COMMAND(moveLeft)
442 WEBCORE_COMMAND(moveLeftAndModifySelection)
443 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
444 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
445 WEBCORE_COMMAND(moveRight)
446 WEBCORE_COMMAND(moveRightAndModifySelection)
447 WEBCORE_COMMAND(moveToBeginningOfDocument)
448 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
449 WEBCORE_COMMAND(moveToBeginningOfLine)
450 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
451 WEBCORE_COMMAND(moveToBeginningOfParagraph)
452 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
453 WEBCORE_COMMAND(moveToBeginningOfSentence)
454 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
455 WEBCORE_COMMAND(moveToEndOfDocument)
456 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
457 WEBCORE_COMMAND(moveToEndOfLine)
458 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
459 WEBCORE_COMMAND(moveToEndOfParagraph)
460 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
461 WEBCORE_COMMAND(moveToEndOfSentence)
462 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
463 WEBCORE_COMMAND(moveToLeftEndOfLine)
464 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
465 WEBCORE_COMMAND(moveToRightEndOfLine)
466 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
467 WEBCORE_COMMAND(moveUp)
468 WEBCORE_COMMAND(moveUpAndModifySelection)
469 WEBCORE_COMMAND(moveWordBackward)
470 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
471 WEBCORE_COMMAND(moveWordForward)
472 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
473 WEBCORE_COMMAND(moveWordLeft)
474 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
475 WEBCORE_COMMAND(moveWordRight)
476 WEBCORE_COMMAND(moveWordRightAndModifySelection)
477 WEBCORE_COMMAND(outdent)
478 WEBCORE_COMMAND(pageDown)
479 WEBCORE_COMMAND(pageDownAndModifySelection)
480 WEBCORE_COMMAND(pageUp)
481 WEBCORE_COMMAND(pageUpAndModifySelection)
482 WEBCORE_COMMAND(paste)
483 WEBCORE_COMMAND(pasteAsPlainText)
484 WEBCORE_COMMAND(scrollPageDown)
485 WEBCORE_COMMAND(scrollPageUp)
486 WEBCORE_COMMAND(scrollToBeginningOfDocument)
487 WEBCORE_COMMAND(scrollToEndOfDocument)
488 WEBCORE_COMMAND(selectAll)
489 WEBCORE_COMMAND(selectLine)
490 WEBCORE_COMMAND(selectParagraph)
491 WEBCORE_COMMAND(selectSentence)
492 WEBCORE_COMMAND(selectToMark)
493 WEBCORE_COMMAND(selectWord)
494 WEBCORE_COMMAND(setMark)
495 WEBCORE_COMMAND(subscript)
496 WEBCORE_COMMAND(superscript)
497 WEBCORE_COMMAND(swapWithMark)
498 WEBCORE_COMMAND(takeFindStringFromSelection)
499 WEBCORE_COMMAND(transpose)
500 WEBCORE_COMMAND(underline)
501 WEBCORE_COMMAND(unscript)
502 WEBCORE_COMMAND(yank)
503 WEBCORE_COMMAND(yankAndSelect)
504
505 #undef WEBCORE_COMMAND
506
507 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
508 {
509     Vector<String> pasteboardTypes;
510     size_t numTypes = [types count];
511     for (size_t i = 0; i < numTypes; ++i)
512         pasteboardTypes.append([types objectAtIndex:i]);
513     return _data->_page->writeSelectionToPasteboard([pasteboard name], pasteboardTypes);
514 }
515
516 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
517 {
518     BOOL isValidSendType = !sendType || ([PasteboardTypes::forSelection() containsObject:sendType] && !_data->_page->selectionState().isNone);
519     BOOL isValidReturnType = NO;
520     if (!returnType)
521         isValidReturnType = YES;
522     else if ([PasteboardTypes::forEditing() containsObject:returnType] && _data->_page->selectionState().isContentEditable) {
523         // We can insert strings in any editable context.  We can insert other types, like images, only in rich edit contexts.
524         isValidReturnType = _data->_page->selectionState().isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType];
525     }
526     if (isValidSendType && isValidReturnType)
527         return self;
528     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
529 }
530
531 /*
532
533 When possible, editing-related methods should be implemented in WebCore with the
534 EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing
535 individual methods here with Mac-specific code.
536
537 Editing-related methods still unimplemented that are implemented in WebKit1:
538
539 - (void)capitalizeWord:(id)sender;
540 - (void)centerSelectionInVisibleArea:(id)sender;
541 - (void)changeFont:(id)sender;
542 - (void)complete:(id)sender;
543 - (void)copyFont:(id)sender;
544 - (void)lowercaseWord:(id)sender;
545 - (void)makeBaseWritingDirectionLeftToRight:(id)sender;
546 - (void)makeBaseWritingDirectionNatural:(id)sender;
547 - (void)makeBaseWritingDirectionRightToLeft:(id)sender;
548 - (void)pasteFont:(id)sender;
549 - (void)scrollLineDown:(id)sender;
550 - (void)scrollLineUp:(id)sender;
551 - (void)showGuessPanel:(id)sender;
552 - (void)uppercaseWord:(id)sender;
553
554 Some other editing-related methods still unimplemented:
555
556 - (void)changeCaseOfLetter:(id)sender;
557 - (void)copyRuler:(id)sender;
558 - (void)insertContainerBreak:(id)sender;
559 - (void)insertDoubleQuoteIgnoringSubstitution:(id)sender;
560 - (void)insertSingleQuoteIgnoringSubstitution:(id)sender;
561 - (void)pasteRuler:(id)sender;
562 - (void)toggleRuler:(id)sender;
563 - (void)transposeWords:(id)sender;
564
565 */
566
567 // Menu items validation
568
569 static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item)
570 {
571     if (![(NSObject *)item isKindOfClass:[NSMenuItem class]])
572         return nil;
573     return (NSMenuItem *)item;
574 }
575
576 static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item)
577 {
578     if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]])
579         return nil;
580     return (NSToolbarItem *)item;
581 }
582
583 static void validateCommandCallback(WKStringRef commandName, bool isEnabled, int32_t state, WKErrorRef error, void* context)
584 {
585     // If the process exits before the command can be validated, we'll be called back with an error.
586     if (error)
587         return;
588     
589     WKView* wkView = static_cast<WKView*>(context);
590     ASSERT(wkView);
591     
592     [wkView _setUserInterfaceItemState:nsStringFromWebCoreString(toImpl(commandName)->string()) enabled:isEnabled state:state];
593 }
594
595 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
596 {
597     SEL action = [item action];
598
599     if (action == @selector(showGuessPanel:)) {
600         if (NSMenuItem *menuItem = ::menuItem(item)) {
601             BOOL panelShowing = [[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible];
602             [menuItem setTitle:panelShowing
603                 ? UI_STRING("Hide Spelling and Grammar", "menu item title")
604                 : UI_STRING("Show Spelling and Grammar", "menu item title")];
605         }
606         return _data->_page->selectionState().isContentEditable;
607     }
608
609     if (action == @selector(checkSpelling:) || action == @selector(changeSpelling:))
610         return _data->_page->selectionState().isContentEditable;
611
612     if (action == @selector(toggleContinuousSpellChecking:)) {
613         bool enabled = TextChecker::isContinuousSpellCheckingAllowed();
614         bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled;
615         [menuItem(item) setState:checked ? NSOnState : NSOffState];
616         return enabled;
617     }
618
619     if (action == @selector(toggleGrammarChecking:)) {
620         bool checked = TextChecker::state().isGrammarCheckingEnabled;
621         [menuItem(item) setState:checked ? NSOnState : NSOffState];
622         return YES;
623     }
624
625     if (action == @selector(toggleAutomaticSpellingCorrection:)) {
626         bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled;
627         [menuItem(item) setState:checked ? NSOnState : NSOffState];
628         return _data->_page->selectionState().isContentEditable;
629     }
630
631     if (action == @selector(orderFrontSubstitutionsPanel:)) {
632         if (NSMenuItem *menuItem = ::menuItem(item)) {
633             BOOL panelShowing = [[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible];
634             [menuItem setTitle:panelShowing
635                 ? UI_STRING("Hide Substitutions", "menu item title")
636                 : UI_STRING("Show Substitutions", "menu item title")];
637         }
638         return _data->_page->selectionState().isContentEditable;
639     }
640
641     if (action == @selector(toggleSmartInsertDelete:)) {
642         bool checked = _data->_page->isSmartInsertDeleteEnabled();
643         [menuItem(item) setState:checked ? NSOnState : NSOffState];
644         return _data->_page->selectionState().isContentEditable;
645     }
646
647     if (action == @selector(toggleAutomaticQuoteSubstitution:)) {
648         bool checked = TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
649         [menuItem(item) setState:checked ? NSOnState : NSOffState];
650         return _data->_page->selectionState().isContentEditable;
651     }
652
653     if (action == @selector(toggleAutomaticDashSubstitution:)) {
654         bool checked = TextChecker::state().isAutomaticDashSubstitutionEnabled;
655         [menuItem(item) setState:checked ? NSOnState : NSOffState];
656         return _data->_page->selectionState().isContentEditable;
657     }
658
659     if (action == @selector(toggleAutomaticLinkDetection:)) {
660         bool checked = TextChecker::state().isAutomaticLinkDetectionEnabled;
661         [menuItem(item) setState:checked ? NSOnState : NSOffState];
662         return _data->_page->selectionState().isContentEditable;
663     }
664
665     if (action == @selector(toggleAutomaticTextReplacement:)) {
666         bool checked = TextChecker::state().isAutomaticTextReplacementEnabled;
667         [menuItem(item) setState:checked ? NSOnState : NSOffState];
668         return _data->_page->selectionState().isContentEditable;
669     }
670
671     if (action == @selector(uppercaseWord:) || action == @selector(lowercaseWord:) || action == @selector(capitalizeWord:))
672         return _data->_page->selectionState().selectedRangeLength && _data->_page->selectionState().isContentEditable;
673     
674     if (action == @selector(stopSpeaking:))
675         return [NSApp isSpeaking];
676
677     // Next, handle editor commands. Start by returning YES for anything that is not an editor command.
678     // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized.
679     String commandName = commandNameForSelector([item action]);
680     if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName))
681         return YES;
682
683     // Add this item to the vector of items for a given command that are awaiting validation.
684     pair<ValidationMap::iterator, bool> addResult = _data->_validationMap.add(commandName, ValidationVector());
685     addResult.first->second.append(item);
686     if (addResult.second) {
687         // If we are not already awaiting validation for this command, start the asynchronous validation process.
688         // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
689         // we asked for the same command; there is no guarantee the answer is still valid.
690         _data->_page->validateCommand(commandName, ValidateCommandCallback::create(self, validateCommandCallback));
691     }
692
693     // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called.
694     // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment.
695     // But returning NO here would be worse; that would make keyboard commands such as command-C fail.
696     return YES;
697 }
698
699 static void speakString(WKStringRef string, WKErrorRef error, void*)
700 {
701     if (error)
702         return;
703     if (!string)
704         return;
705
706     NSString *convertedString = toImpl(string)->string();
707     [NSApp speakString:convertedString];
708 }
709
710 - (IBAction)startSpeaking:(id)sender
711 {
712     _data->_page->getSelectionOrContentsAsString(StringCallback::create(0, speakString));
713 }
714
715 - (IBAction)stopSpeaking:(id)sender
716 {
717     [NSApp stopSpeaking:sender];
718 }
719
720 - (IBAction)showGuessPanel:(id)sender
721 {
722     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
723     if (!checker) {
724         LOG_ERROR("No NSSpellChecker");
725         return;
726     }
727     
728     NSPanel *spellingPanel = [checker spellingPanel];
729     if ([spellingPanel isVisible]) {
730         [spellingPanel orderOut:sender];
731         return;
732     }
733     
734     _data->_page->advanceToNextMisspelling(true);
735     [spellingPanel orderFront:sender];
736 }
737
738 - (IBAction)checkSpelling:(id)sender
739 {
740     _data->_page->advanceToNextMisspelling(false);
741 }
742
743 - (void)changeSpelling:(id)sender
744 {
745     NSString *word = [[sender selectedCell] stringValue];
746
747     _data->_page->changeSpellingToWord(word);
748 }
749
750 - (IBAction)toggleContinuousSpellChecking:(id)sender
751 {
752     bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled;
753     TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled);
754
755     _data->_page->process()->updateTextCheckerState();
756
757     if (!spellCheckingEnabled)
758         _data->_page->unmarkAllMisspellings();
759 }
760
761 - (BOOL)isGrammarCheckingEnabled
762 {
763     return TextChecker::state().isGrammarCheckingEnabled;
764 }
765
766 - (void)setGrammarCheckingEnabled:(BOOL)flag
767 {
768     if (static_cast<bool>(flag) == TextChecker::state().isGrammarCheckingEnabled)
769         return;
770     
771     TextChecker::setGrammarCheckingEnabled(flag);
772     _data->_page->process()->updateTextCheckerState();
773
774     if (!flag)
775         _data->_page->unmarkAllBadGrammar();
776 }
777
778 - (IBAction)toggleGrammarChecking:(id)sender
779 {
780     bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled;
781     TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled);
782
783     _data->_page->process()->updateTextCheckerState();
784
785     if (!grammarCheckingEnabled)
786         _data->_page->unmarkAllBadGrammar();
787 }
788
789 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
790 {
791     TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
792
793     _data->_page->process()->updateTextCheckerState();
794 }
795
796 - (void)orderFrontSubstitutionsPanel:(id)sender
797 {
798     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
799     if (!checker) {
800         LOG_ERROR("No NSSpellChecker");
801         return;
802     }
803     
804     NSPanel *substitutionsPanel = [checker substitutionsPanel];
805     if ([substitutionsPanel isVisible]) {
806         [substitutionsPanel orderOut:sender];
807         return;
808     }
809     [substitutionsPanel orderFront:sender];
810 }
811
812 - (IBAction)toggleSmartInsertDelete:(id)sender
813 {
814     _data->_page->setSmartInsertDeleteEnabled(!_data->_page->isSmartInsertDeleteEnabled());
815 }
816
817 - (BOOL)isAutomaticQuoteSubstitutionEnabled
818 {
819     return TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
820 }
821
822 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
823 {
824     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticQuoteSubstitutionEnabled)
825         return;
826
827     TextChecker::setAutomaticQuoteSubstitutionEnabled(flag);
828     _data->_page->process()->updateTextCheckerState();
829 }
830
831 - (void)toggleAutomaticQuoteSubstitution:(id)sender
832 {
833     TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled);
834     _data->_page->process()->updateTextCheckerState();
835 }
836
837 - (BOOL)isAutomaticDashSubstitutionEnabled
838 {
839     return TextChecker::state().isAutomaticDashSubstitutionEnabled;
840 }
841
842 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
843 {
844     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticDashSubstitutionEnabled)
845         return;
846
847     TextChecker::setAutomaticDashSubstitutionEnabled(flag);
848     _data->_page->process()->updateTextCheckerState();
849 }
850
851 - (void)toggleAutomaticDashSubstitution:(id)sender
852 {
853     TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled);
854     _data->_page->process()->updateTextCheckerState();
855 }
856
857 - (BOOL)isAutomaticLinkDetectionEnabled
858 {
859     return TextChecker::state().isAutomaticLinkDetectionEnabled;
860 }
861
862 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
863 {
864     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticLinkDetectionEnabled)
865         return;
866
867     TextChecker::setAutomaticLinkDetectionEnabled(flag);
868     _data->_page->process()->updateTextCheckerState();
869 }
870
871 - (void)toggleAutomaticLinkDetection:(id)sender
872 {
873     TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled);
874     _data->_page->process()->updateTextCheckerState();
875 }
876
877 - (BOOL)isAutomaticTextReplacementEnabled
878 {
879     return TextChecker::state().isAutomaticTextReplacementEnabled;
880 }
881
882 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
883 {
884     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticTextReplacementEnabled)
885         return;
886
887     TextChecker::setAutomaticTextReplacementEnabled(flag);
888     _data->_page->process()->updateTextCheckerState();
889 }
890
891 - (void)toggleAutomaticTextReplacement:(id)sender
892 {
893     TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled);
894     _data->_page->process()->updateTextCheckerState();
895 }
896
897 - (void)uppercaseWord:(id)sender
898 {
899     _data->_page->uppercaseWord();
900 }
901
902 - (void)lowercaseWord:(id)sender
903 {
904     _data->_page->lowercaseWord();
905 }
906
907 - (void)capitalizeWord:(id)sender
908 {
909     _data->_page->capitalizeWord();
910 }
911
912 // Events
913
914 // Override this so that AppKit will send us arrow keys as key down events so we can
915 // support them via the key bindings mechanism.
916 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
917 {
918     return YES;
919 }
920
921 - (void)_setMouseDownEvent:(NSEvent *)event
922 {
923     ASSERT(!event || [event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
924     
925     if (event == _data->_mouseDownEvent)
926         return;
927     
928     [_data->_mouseDownEvent release];
929     _data->_mouseDownEvent = [event retain];
930 }
931
932 #define EVENT_HANDLER(Selector, Type) \
933     - (void)Selector:(NSEvent *)theEvent \
934     { \
935         Web##Type##Event webEvent = WebEventFactory::createWeb##Type##Event(theEvent, self); \
936         _data->_page->handle##Type##Event(webEvent); \
937     }
938
939 EVENT_HANDLER(mouseEntered, Mouse)
940 EVENT_HANDLER(mouseExited, Mouse)
941 EVENT_HANDLER(mouseMoved, Mouse)
942 EVENT_HANDLER(otherMouseDown, Mouse)
943 EVENT_HANDLER(otherMouseDragged, Mouse)
944 EVENT_HANDLER(otherMouseMoved, Mouse)
945 EVENT_HANDLER(otherMouseUp, Mouse)
946 EVENT_HANDLER(rightMouseDown, Mouse)
947 EVENT_HANDLER(rightMouseDragged, Mouse)
948 EVENT_HANDLER(rightMouseMoved, Mouse)
949 EVENT_HANDLER(rightMouseUp, Mouse)
950 EVENT_HANDLER(scrollWheel, Wheel)
951
952 #undef EVENT_HANDLER
953
954 - (void)_mouseHandler:(NSEvent *)event
955 {
956     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
957     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
958         return;
959     WebMouseEvent webEvent = WebEventFactory::createWebMouseEvent(event, self);
960     _data->_page->handleMouseEvent(webEvent);
961 }
962
963 - (void)mouseDown:(NSEvent *)event
964 {
965     [self _setMouseDownEvent:event];
966     _data->_ignoringMouseDraggedEvents = NO;
967     _data->_dragHasStarted = NO;
968     [self _mouseHandler:event];
969 }
970
971 - (void)mouseUp:(NSEvent *)event
972 {
973     [self _setMouseDownEvent:nil];
974     [self _mouseHandler:event];
975 }
976
977 - (void)mouseDragged:(NSEvent *)event
978 {
979     if (_data->_ignoringMouseDraggedEvents)
980         return;
981     [self _mouseHandler:event];
982 }
983
984 #if ENABLE(GESTURE_EVENTS)
985
986 static const short kIOHIDEventTypeScroll = 6;
987
988 - (void)shortCircuitedEndGestureWithEvent:(NSEvent *)event
989 {
990     if ([event subtype] != kIOHIDEventTypeScroll)
991         return;
992
993     WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
994     _data->_page->handleGestureEvent(webEvent);
995
996     if (_data->_endGestureMonitor) {
997         [NSEvent removeMonitor:_data->_endGestureMonitor];
998         _data->_endGestureMonitor = nil;
999     }
1000 }
1001
1002 - (void)beginGestureWithEvent:(NSEvent *)event
1003 {
1004     if ([event subtype] != kIOHIDEventTypeScroll)
1005         return;
1006
1007     WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
1008     _data->_page->handleGestureEvent(webEvent);
1009
1010     if (!_data->_endGestureMonitor) {
1011         _data->_endGestureMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskEndGesture handler:^(NSEvent *blockEvent) {
1012             [self shortCircuitedEndGestureWithEvent:blockEvent];
1013             return blockEvent;
1014         }];
1015     }
1016 }
1017 #endif
1018
1019 - (void)doCommandBySelector:(SEL)selector
1020 {
1021     if (!_data->_isInInterpretKeyEvents) {
1022         [super doCommandBySelector:selector];
1023         return;
1024     }
1025     if (selector != @selector(noop:))
1026         _data->_commandsList.append(KeypressCommand(commandNameForSelector(selector)));
1027 }
1028
1029 - (void)insertText:(id)string
1030 {
1031     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; // Otherwise, NSString
1032     
1033     LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
1034     NSString *text;
1035     bool isFromInputMethod = _data->_page->selectionState().hasComposition;
1036
1037     if (isAttributedString) {
1038         text = [string string];
1039         // We deal with the NSTextInputReplacementRangeAttributeName attribute from NSAttributedString here
1040         // simply because it is used by at least one Input Method -- it corresonds to the kEventParamTextInputSendReplaceRange
1041         // event in TSM.  This behaviour matches that of -[WebHTMLView setMarkedText:selectedRange:] when it receives an
1042         // NSAttributedString
1043         NSString *rangeString = [string attribute:NSTextInputReplacementRangeAttributeName atIndex:0 longestEffectiveRange:NULL inRange:NSMakeRange(0, [text length])];
1044         LOG(TextInput, "ReplacementRange: %@", rangeString);
1045         if (rangeString)
1046             isFromInputMethod = YES;
1047     } else
1048         text = string;
1049
1050     String eventText = text;
1051     
1052     // We'd need a different code path here if we wanted to be able to handle this
1053     // outside of interpretKeyEvents.
1054     ASSERT(_data->_isInInterpretKeyEvents);
1055
1056     if (!isFromInputMethod)
1057         _data->_commandsList.append(KeypressCommand("insertText", text));
1058     else {
1059         eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
1060         _data->_commandsList.append(KeypressCommand("insertText", eventText));
1061     }
1062 }
1063
1064 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
1065 {
1066     if (!_data->_page->selectionState().isContentEditable)
1067         return NO;
1068
1069     if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) != NSCommandKeyMask)
1070         return NO;
1071     
1072     // Here we special case cmd+b and cmd+i but not cmd+u, for historic reason.
1073     // This should not be changed, since it could break some Mac applications that
1074     // rely on this inherent behavior.
1075     // See https://bugs.webkit.org/show_bug.cgi?id=24943
1076     
1077     NSString *string = [event characters];
1078     if ([string caseInsensitiveCompare:@"b"] == NSOrderedSame) {
1079         _data->_page->executeEditCommand("ToggleBold");
1080         return YES;
1081     }
1082     if ([string caseInsensitiveCompare:@"i"] == NSOrderedSame) {
1083         _data->_page->executeEditCommand("ToggleItalic");
1084         return YES;
1085     }
1086     
1087     return NO;
1088 }
1089
1090 - (BOOL)performKeyEquivalent:(NSEvent *)event
1091 {
1092     // There's a chance that responding to this event will run a nested event loop, and
1093     // fetching a new event might release the old one. Retaining and then autoreleasing
1094     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1095     [[event retain] autorelease];
1096     
1097     BOOL eventWasSentToWebCore = (_data->_keyDownEventBeingResent == event);
1098
1099     // Pass key combos through WebCore if there is a key binding available for
1100     // this event. This lets web pages have a crack at intercepting key-modified keypresses.
1101     // But don't do it if we have already handled the event.
1102     // Pressing Esc results in a fake event being sent - don't pass it to WebCore.
1103     if (!eventWasSentToWebCore && event == [NSApp currentEvent] && self == [[self window] firstResponder]) {
1104         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, self));
1105         return YES;
1106     }
1107     
1108     return [self _handleStyleKeyEquivalent:event] || [super performKeyEquivalent:event];
1109 }
1110
1111 - (void)keyUp:(NSEvent *)theEvent
1112 {
1113     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1114 }
1115
1116 - (void)keyDown:(NSEvent *)theEvent
1117 {
1118     if (_data->_pluginComplexTextInputIdentifier) {
1119         // Try feeding the keyboard event directly to the plug-in.
1120         NSString *string = nil;
1121         if ([[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:theEvent string:&string]) {
1122             if (string)
1123                 _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string);
1124             return;
1125         }
1126     }
1127
1128     _data->_underlines.clear();
1129     _data->_selectionStart = 0;
1130     _data->_selectionEnd = 0;
1131     // We could be receiving a key down from AppKit if we have re-sent an event
1132     // that maps to an action that is currently unavailable (for example a copy when
1133     // there is no range selection).
1134     // If this is the case we should ignore the key down.
1135     if (_data->_keyDownEventBeingResent == theEvent) {
1136         [super keyDown:theEvent];
1137         return;
1138     }
1139     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1140 }
1141
1142 - (NSTextInputContext *)inputContext {
1143     if (_data->_pluginComplexTextInputIdentifier)
1144         return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
1145
1146     return [super inputContext];
1147 }
1148
1149 - (NSRange)selectedRange
1150 {
1151     if (_data->_page->selectionState().isNone || !_data->_page->selectionState().isContentEditable)
1152         return NSMakeRange(NSNotFound, 0);
1153     
1154     LOG(TextInput, "selectedRange -> (%u, %u)", _data->_page->selectionState().selectedRangeStart, _data->_page->selectionState().selectedRangeLength);
1155     return NSMakeRange(_data->_page->selectionState().selectedRangeStart, _data->_page->selectionState().selectedRangeLength);
1156 }
1157
1158 - (BOOL)hasMarkedText
1159 {
1160     LOG(TextInput, "hasMarkedText -> %u", _data->_page->selectionState().hasComposition);
1161     return _data->_page->selectionState().hasComposition;
1162 }
1163
1164 - (void)unmarkText
1165 {
1166     LOG(TextInput, "unmarkText");
1167
1168     // We'd need a different code path here if we wanted to be able to handle this
1169     // outside of interpretKeyEvents.
1170     ASSERT(_data->_isInInterpretKeyEvents);
1171
1172     _data->_commandsList.append(KeypressCommand("unmarkText"));
1173 }
1174
1175 - (NSArray *)validAttributesForMarkedText
1176 {
1177     static NSArray *validAttributes;
1178     if (!validAttributes) {
1179         validAttributes = [[NSArray alloc] initWithObjects:
1180                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
1181                            NSMarkedClauseSegmentAttributeName, NSTextInputReplacementRangeAttributeName, nil];
1182         // NSText also supports the following attributes, but it's
1183         // hard to tell which are really required for text input to
1184         // work well; I have not seen any input method make use of them yet.
1185         //     NSFontAttributeName, NSForegroundColorAttributeName,
1186         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
1187         CFRetain(validAttributes);
1188     }
1189     LOG(TextInput, "validAttributesForMarkedText -> (...)");
1190     return validAttributes;
1191 }
1192
1193 static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result)
1194 {
1195     int length = [[string string] length];
1196     
1197     int i = 0;
1198     while (i < length) {
1199         NSRange range;
1200         NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)];
1201         
1202         if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
1203             Color color = Color::black;
1204             if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName])
1205                 color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
1206             result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1));
1207         }
1208         
1209         i = range.location + range.length;
1210     }
1211 }
1212
1213 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
1214 {
1215     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; // Otherwise, NSString
1216     
1217     LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelRange.location, newSelRange.length);
1218     
1219     NSString *text = string;
1220     
1221     if (isAttributedString) {
1222         text = [string string];
1223         extractUnderlines(string, _data->_underlines);
1224     }
1225     
1226     // We'd need a different code path here if we wanted to be able to handle this
1227     // outside of interpretKeyEvents.
1228     ASSERT(_data->_isInInterpretKeyEvents);
1229
1230     _data->_commandsList.append(KeypressCommand("setMarkedText", text));
1231     _data->_selectionStart = newSelRange.location;
1232     _data->_selectionEnd = NSMaxRange(newSelRange);
1233 }
1234
1235 - (NSRange)markedRange
1236 {
1237     uint64_t location;
1238     uint64_t length;
1239
1240     _data->_page->getMarkedRange(location, length);
1241     LOG(TextInput, "markedRange -> (%u, %u)", location, length);
1242     return NSMakeRange(location, length);
1243 }
1244
1245 - (NSAttributedString *)attributedSubstringFromRange:(NSRange)nsRange
1246 {
1247     // This is not implemented for now. Need to figure out how to serialize the attributed string across processes.
1248     LOG(TextInput, "attributedSubstringFromRange");
1249     return nil;
1250 }
1251
1252 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1253 {
1254     NSWindow *window = [self window];
1255     
1256     if (window)
1257         thePoint = [window convertScreenToBase:thePoint];
1258     thePoint = [self convertPoint:thePoint fromView:nil];  // the point is relative to the main frame 
1259     
1260     uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint));
1261     LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result);
1262     return result;
1263 }
1264
1265 - (NSRect)firstRectForCharacterRange:(NSRange)theRange
1266
1267     // Just to match NSTextView's behavior. Regression tests cannot detect this;
1268     // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
1269     // (type something; try ranges (1, -1) and (2, -1).
1270     if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
1271         theRange.length = 0;
1272     
1273     NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange.location, theRange.length);
1274     resultRect = [self convertRect:resultRect toView:nil];
1275     
1276     NSWindow *window = [self window];
1277     if (window)
1278         resultRect.origin = [window convertBaseToScreen:resultRect.origin];
1279     
1280     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);
1281     return resultRect;
1282 }
1283
1284 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
1285 {
1286     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
1287     NSPoint windowMouseLoc = windowImageLoc;
1288    
1289     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
1290     _data->_ignoringMouseDraggedEvents = YES;
1291     
1292     _data->_page->dragEnded(IntPoint(windowMouseLoc), globalPoint(windowMouseLoc, [self window]), operation);
1293 }
1294
1295 - (DragApplicationFlags)applicationFlags:(id <NSDraggingInfo>)draggingInfo
1296 {
1297     uint32_t flags = 0;
1298     if ([NSApp modalWindow])
1299         flags = DragApplicationIsModal;
1300     if ([[self window] attachedSheet])
1301         flags |= DragApplicationHasAttachedSheet;
1302     if ([draggingInfo draggingSource] == self)
1303         flags |= DragApplicationIsSource;
1304     if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1305         flags |= DragApplicationIsCopyKeyDown;
1306     return static_cast<DragApplicationFlags>(flags);
1307 }
1308
1309 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
1310 {
1311     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1312     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1313     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1314
1315     _data->_page->resetDragOperation();
1316     _data->_page->performDragControllerAction(DragControllerActionEntered, &dragData, [[draggingInfo draggingPasteboard] name]);
1317     return NSDragOperationCopy;
1318 }
1319
1320 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
1321 {
1322     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1323     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1324     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1325     _data->_page->performDragControllerAction(DragControllerActionUpdated, &dragData, [[draggingInfo draggingPasteboard] name]);
1326     return _data->_page->dragOperation();
1327 }
1328
1329 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
1330 {
1331     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1332     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1333     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1334     _data->_page->performDragControllerAction(DragControllerActionExited, &dragData, [[draggingInfo draggingPasteboard] name]);
1335     _data->_page->resetDragOperation();
1336 }
1337
1338 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
1339 {
1340     return YES;
1341 }
1342
1343 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
1344 {
1345     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1346     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1347     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1348     _data->_page->performDragControllerAction(DragControllerActionPerformDrag, &dragData, [[draggingInfo draggingPasteboard] name]);
1349     return YES;
1350 }
1351
1352 - (void)_updateWindowVisibility
1353 {
1354     _data->_page->updateWindowIsVisible(![[self window] isMiniaturized]);
1355 }
1356
1357 - (BOOL)_ownsWindowGrowBox
1358 {
1359     NSWindow* window = [self window];
1360     if (!window)
1361         return NO;
1362
1363     NSView *superview = [self superview];
1364     if (!superview)
1365         return NO;
1366
1367     NSRect growBoxRect = [window _growBoxRect];
1368     if (NSIsEmptyRect(growBoxRect))
1369         return NO;
1370
1371     NSRect visibleRect = [self visibleRect];
1372     if (NSIsEmptyRect(visibleRect))
1373         return NO;
1374
1375     NSRect visibleRectInWindowCoords = [self convertRect:visibleRect toView:nil];
1376     if (!NSIntersectsRect(growBoxRect, visibleRectInWindowCoords))
1377         return NO;
1378
1379     return YES;
1380 }
1381
1382 - (BOOL)_updateGrowBoxForWindowFrameChange
1383 {
1384     // Temporarily enable the resize indicator to make a the _ownsWindowGrowBox calculation work.
1385     BOOL wasShowingIndicator = [[self window] showsResizeIndicator];
1386     if (!wasShowingIndicator)
1387         [[self window] setShowsResizeIndicator:YES];
1388
1389     BOOL ownsGrowBox = [self _ownsWindowGrowBox];
1390     _data->_page->setWindowResizerSize(ownsGrowBox ? enclosingIntRect([[self window] _growBoxRect]).size() : IntSize());
1391
1392     if (ownsGrowBox)
1393         [[self window] _setShowOpaqueGrowBoxForOwner:(_data->_page->hasHorizontalScrollbar() || _data->_page->hasVerticalScrollbar() ? self : nil)];
1394     else
1395         [[self window] _setShowOpaqueGrowBoxForOwner:nil];
1396
1397     // Once WebCore can draw the window resizer, this should read:
1398     // if (wasShowingIndicator)
1399     //     [[self window] setShowsResizeIndicator:!ownsGrowBox];
1400     if (!wasShowingIndicator)
1401         [[self window] setShowsResizeIndicator:NO];
1402
1403     return ownsGrowBox;
1404 }
1405
1406 - (void)addWindowObserversForWindow:(NSWindow *)window
1407 {
1408     if (window) {
1409         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
1410                                                      name:NSWindowDidBecomeKeyNotification object:nil];
1411         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
1412                                                      name:NSWindowDidResignKeyNotification object:nil];
1413         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) 
1414                                                      name:NSWindowDidMiniaturizeNotification object:window];
1415         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
1416                                                      name:NSWindowDidDeminiaturizeNotification object:window];
1417         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:)
1418                                                      name:NSWindowDidMoveNotification object:window];
1419         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:) 
1420                                                      name:NSWindowDidResizeNotification object:window];
1421     }
1422 }
1423
1424 - (void)removeWindowObservers
1425 {
1426     NSWindow *window = [self window];
1427     if (!window)
1428         return;
1429
1430     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
1431     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
1432     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
1433     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
1434     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
1435     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
1436 }
1437
1438 - (void)viewWillMoveToWindow:(NSWindow *)window
1439 {
1440     NSWindow *currentWindow = [self window];
1441     if (window == currentWindow)
1442         return;
1443     
1444     [self removeWindowObservers];
1445     [self addWindowObserversForWindow:window];
1446     
1447     if ([currentWindow _growBoxOwner] == self)
1448         [currentWindow _setShowOpaqueGrowBoxForOwner:nil];
1449 }
1450
1451 - (void)viewDidMoveToWindow
1452 {
1453     // We want to make sure to update the active state while hidden, so if the view is about to become visible, we
1454     // update the active state first and then make it visible. If the view is about to be hidden, we hide it first and then
1455     // update the active state.
1456     if ([self window]) {
1457         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1458         _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible | WebPageProxy::ViewIsInWindow);
1459         [self _updateWindowVisibility];
1460         [self _updateWindowAndViewFrames];
1461         
1462         // Initialize remote accessibility when the window connection has been established.
1463 #if !defined(BUILDING_ON_SNOW_LEOPARD)
1464         NSData *remoteElementToken = WKAXRemoteTokenForElement(self);
1465         NSData *remoteWindowToken = WKAXRemoteTokenForElement([self window]);
1466         CoreIPC::DataReference elementToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteElementToken bytes]), [remoteElementToken length]);
1467         CoreIPC::DataReference windowToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteWindowToken bytes]), [remoteWindowToken length]);
1468         _data->_page->registerUIProcessAccessibilityTokens(elementToken, windowToken);
1469 #endif    
1470             
1471     } else {
1472         _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1473         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive | WebPageProxy::ViewIsInWindow);
1474
1475 #if ENABLE(GESTURE_EVENTS)
1476         if (_data->_endGestureMonitor) {
1477             [NSEvent removeMonitor:_data->_endGestureMonitor];
1478             _data->_endGestureMonitor = nil;
1479         }
1480 #endif
1481 #if !defined(BUILDING_ON_SNOW_LEOPARD)
1482         WKHideWordDefinitionWindow();
1483 #endif
1484     }
1485 }
1486
1487 - (void)_windowDidBecomeKey:(NSNotification *)notification
1488 {
1489     NSWindow *keyWindow = [notification object];
1490     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
1491         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1492 }
1493
1494 - (void)_windowDidResignKey:(NSNotification *)notification
1495 {
1496     NSWindow *formerKeyWindow = [notification object];
1497     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet])
1498         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1499 }
1500
1501 - (void)_windowDidMiniaturize:(NSNotification *)notification
1502 {
1503     [self _updateWindowVisibility];
1504 }
1505
1506 - (void)_windowDidDeminiaturize:(NSNotification *)notification
1507 {
1508     [self _updateWindowVisibility];
1509 }
1510
1511 - (void)_windowFrameDidChange:(NSNotification *)notification
1512 {
1513     [self _updateWindowAndViewFrames];
1514 }
1515
1516 static void drawPageBackground(CGContextRef context, WebPageProxy* page, const IntRect& rect)
1517 {
1518     if (!page->drawsBackground())
1519         return;
1520
1521     CGContextSaveGState(context);
1522     CGContextSetBlendMode(context, kCGBlendModeCopy);
1523
1524     CGColorRef backgroundColor;
1525     if (page->drawsTransparentBackground())
1526         backgroundColor = CGColorGetConstantColor(kCGColorClear);
1527     else
1528         backgroundColor = CGColorGetConstantColor(kCGColorWhite);
1529
1530     CGContextSetFillColorWithColor(context, backgroundColor);
1531     CGContextFillRect(context, rect);
1532
1533     CGContextRestoreGState(context);
1534 }
1535
1536 - (void)drawRect:(NSRect)rect
1537 {
1538     LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1539     _data->_page->endPrinting();
1540     CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
1541
1542     if (DrawingAreaProxyImpl* drawingArea = static_cast<DrawingAreaProxyImpl*>(_data->_page->drawingArea())) {
1543         const NSRect *rectsBeingDrawn;
1544         NSInteger numRectsBeingDrawn;
1545         [self getRectsBeingDrawn:&rectsBeingDrawn count:&numRectsBeingDrawn];
1546         for (NSInteger i = 0; i < numRectsBeingDrawn; ++i) {
1547             Region unpaintedRegion;
1548             IntRect rect = enclosingIntRect(rectsBeingDrawn[i]);
1549             drawingArea->paint(context, rect, unpaintedRegion);
1550
1551             Vector<IntRect> unpaintedRects = unpaintedRegion.rects();
1552             for (size_t i = 0; i < unpaintedRects.size(); ++i)
1553                 drawPageBackground(context, _data->_page.get(), unpaintedRects[i]);
1554         }
1555     } else 
1556         drawPageBackground(context, _data->_page.get(), enclosingIntRect(rect));
1557
1558     _data->_page->didDraw();
1559 }
1560
1561 - (BOOL)isOpaque
1562 {
1563     return _data->_page->drawsBackground();
1564 }
1565
1566 - (BOOL)mouseDownCanMoveWindow
1567 {
1568     // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent,
1569     // but we don't want a drag in the NSView to move the window, even if it's transparent.
1570     return NO;
1571 }
1572
1573 - (void)viewDidHide
1574 {
1575     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1576 }
1577
1578 - (void)viewDidUnhide
1579 {
1580     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1581 }
1582
1583 - (id)accessibilityFocusedUIElement
1584 {
1585     if (_data->_pdfViewController)
1586         return NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView());
1587
1588     return _data->_remoteAccessibilityChild.get();
1589 }
1590
1591 - (BOOL)accessibilityIsIgnored
1592 {
1593     return NO;
1594 }
1595
1596 - (id)accessibilityHitTest:(NSPoint)point
1597 {
1598     if (_data->_pdfViewController)
1599         return [_data->_pdfViewController->pdfView() accessibilityHitTest:point];
1600     
1601     return _data->_remoteAccessibilityChild.get();
1602 }
1603
1604 - (id)accessibilityAttributeValue:(NSString*)attribute
1605 {
1606     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
1607
1608         id child = nil;
1609         if (_data->_pdfViewController)
1610             child = NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView());
1611         else if (_data->_remoteAccessibilityChild)
1612             child = _data->_remoteAccessibilityChild.get();
1613         
1614         if (!child)
1615             return nil;
1616         return [NSArray arrayWithObject:child];
1617     }
1618     if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
1619         return NSAccessibilityGroupRole;
1620     if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
1621         return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil);
1622     if ([attribute isEqualToString:NSAccessibilityParentAttribute])
1623         return NSAccessibilityUnignoredAncestor([self superview]);
1624     if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
1625         return [NSNumber numberWithBool:YES];
1626     
1627     return [super accessibilityAttributeValue:attribute];
1628 }
1629
1630 - (NSView *)hitTest:(NSPoint)point
1631 {
1632     NSView *hitView = [super hitTest:point];
1633     if (hitView && _data && hitView == _data->_layerHostingView)
1634         hitView = self;
1635
1636     return hitView;
1637 }
1638
1639 - (NSInteger)conversationIdentifier
1640 {
1641     return (NSInteger)self;
1642 }
1643
1644
1645 - (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef
1646 {
1647     // PDF documents are already paginated, so we can't change them to add headers and footers.
1648     return !toImpl(frameRef)->isMainFrame() || !_data->_pdfViewController;
1649 }
1650
1651 - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef
1652 {
1653     LOG(View, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data());
1654
1655     // Only the top frame can currently contain a PDF view.
1656     if (_data->_pdfViewController) {
1657         if (!toImpl(frameRef)->isMainFrame())
1658             return 0;
1659         return _data->_pdfViewController->makePrintOperation(printInfo);
1660     } else {
1661         RetainPtr<WKPrintingView> printingView(AdoptNS, [[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef) view:self]);
1662         // NSPrintOperation takes ownership of the view.
1663         NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get()];
1664         [printOperation setCanSpawnSeparateThread:YES];
1665         printingView->_printOperation = printOperation;
1666         return printOperation;
1667     }
1668 }
1669
1670 @end
1671
1672 @implementation WKView (Internal)
1673
1674 - (PassOwnPtr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy
1675 {
1676     return DrawingAreaProxyImpl::create(_data->_page.get());
1677 }
1678
1679 - (BOOL)_isFocused
1680 {
1681     if (_data->_inBecomeFirstResponder)
1682         return YES;
1683     if (_data->_inResignFirstResponder)
1684         return NO;
1685     return [[self window] firstResponder] == self;
1686 }
1687
1688 - (void)_processDidCrash
1689 {
1690     [self setNeedsDisplay:YES];
1691     [self _updateRemoteAccessibilityRegistration:NO];
1692 }
1693
1694 - (void)_pageClosed
1695 {
1696     [self _updateRemoteAccessibilityRegistration:NO];
1697 }
1698
1699 - (void)_didRelaunchProcess
1700 {
1701     [self setNeedsDisplay:YES];
1702 }
1703
1704 - (void)_takeFocus:(BOOL)forward
1705 {
1706     if (forward)
1707         [[self window] selectKeyViewFollowingView:self];
1708     else
1709         [[self window] selectKeyViewPrecedingView:self];
1710 }
1711
1712 - (void)_setCursor:(NSCursor *)cursor
1713 {
1714     if ([NSCursor currentCursor] == cursor)
1715         return;
1716     [cursor set];
1717 }
1718
1719 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
1720 {
1721     ValidationVector items = _data->_validationMap.take(commandName);
1722     size_t size = items.size();
1723     for (size_t i = 0; i < size; ++i) {
1724         ValidationItem item = items[i].get();
1725         [menuItem(item) setState:newState];
1726         [menuItem(item) setEnabled:isEnabled];
1727         [toolbarItem(item) setEnabled:isEnabled];
1728         // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
1729     }
1730 }
1731
1732 - (void)_resendKeyDownEvent:(NSEvent *)event
1733 {
1734     ASSERT(!_data->_keyDownEventBeingResent);
1735     _data->_keyDownEventBeingResent = event;
1736     [NSApp _setCurrentEvent:event];
1737     [NSApp sendEvent:event];
1738
1739     _data->_keyDownEventBeingResent = nullptr;
1740 }
1741
1742 - (Vector<KeypressCommand>&)_interceptKeyEvent:(NSEvent *)theEvent 
1743 {
1744     ASSERT(!_data->_isInInterpretKeyEvents);
1745
1746     _data->_isInInterpretKeyEvents = true;
1747     _data->_commandsList.clear();
1748
1749     // Calling interpretKeyEvents will trigger one or more calls to doCommandBySelector and insertText
1750     // that will populate the commandsList vector.
1751     [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
1752
1753     _data->_isInInterpretKeyEvents = false;
1754
1755     return _data->_commandsList;
1756 }
1757
1758 - (void)_getTextInputState:(unsigned)start selectionEnd:(unsigned)end underlines:(Vector<WebCore::CompositionUnderline>&)lines
1759 {
1760     start = _data->_selectionStart;
1761     end = _data->_selectionEnd;
1762     lines = _data->_underlines;
1763 }
1764
1765 - (NSRect)_convertToDeviceSpace:(NSRect)rect
1766 {
1767     return toDeviceSpace(rect, [self window]);
1768 }
1769
1770 - (NSRect)_convertToUserSpace:(NSRect)rect
1771 {
1772     return toUserSpace(rect, [self window]);
1773 }
1774
1775 // Any non-zero value will do, but using something recognizable might help us debug some day.
1776 #define TRACKING_RECT_TAG 0xBADFACE
1777
1778 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
1779 {
1780     ASSERT(_data->_trackingRectOwner == nil);
1781     _data->_trackingRectOwner = owner;
1782     _data->_trackingRectUserData = data;
1783     return TRACKING_RECT_TAG;
1784 }
1785
1786 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
1787 {
1788     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
1789     ASSERT(_data->_trackingRectOwner == nil);
1790     _data->_trackingRectOwner = owner;
1791     _data->_trackingRectUserData = data;
1792     return TRACKING_RECT_TAG;
1793 }
1794
1795 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
1796 {
1797     ASSERT(count == 1);
1798     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
1799     ASSERT(_data->_trackingRectOwner == nil);
1800     _data->_trackingRectOwner = owner;
1801     _data->_trackingRectUserData = userDataList[0];
1802     trackingNums[0] = TRACKING_RECT_TAG;
1803 }
1804
1805 - (void)removeTrackingRect:(NSTrackingRectTag)tag
1806 {
1807     if (tag == 0)
1808         return;
1809     
1810     if (_data && (tag == TRACKING_RECT_TAG)) {
1811         _data->_trackingRectOwner = nil;
1812         return;
1813     }
1814     
1815     if (_data && (tag == _data->_lastToolTipTag)) {
1816         [super removeTrackingRect:tag];
1817         _data->_lastToolTipTag = 0;
1818         return;
1819     }
1820     
1821     // If any other tracking rect is being removed, we don't know how it was created
1822     // and it's possible there's a leak involved (see 3500217)
1823     ASSERT_NOT_REACHED();
1824 }
1825
1826 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
1827 {
1828     int i;
1829     for (i = 0; i < count; ++i) {
1830         int tag = tags[i];
1831         if (tag == 0)
1832             continue;
1833         ASSERT(tag == TRACKING_RECT_TAG);
1834         if (_data != nil) {
1835             _data->_trackingRectOwner = nil;
1836         }
1837     }
1838 }
1839
1840 - (void)_sendToolTipMouseExited
1841 {
1842     // Nothing matters except window, trackingNumber, and userData.
1843     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
1844         location:NSMakePoint(0, 0)
1845         modifierFlags:0
1846         timestamp:0
1847         windowNumber:[[self window] windowNumber]
1848         context:NULL
1849         eventNumber:0
1850         trackingNumber:TRACKING_RECT_TAG
1851         userData:_data->_trackingRectUserData];
1852     [_data->_trackingRectOwner mouseExited:fakeEvent];
1853 }
1854
1855 - (void)_sendToolTipMouseEntered
1856 {
1857     // Nothing matters except window, trackingNumber, and userData.
1858     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
1859         location:NSMakePoint(0, 0)
1860         modifierFlags:0
1861         timestamp:0
1862         windowNumber:[[self window] windowNumber]
1863         context:NULL
1864         eventNumber:0
1865         trackingNumber:TRACKING_RECT_TAG
1866         userData:_data->_trackingRectUserData];
1867     [_data->_trackingRectOwner mouseEntered:fakeEvent];
1868 }
1869
1870 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
1871 {
1872     return nsStringFromWebCoreString(_data->_page->toolTip());
1873 }
1874
1875 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
1876 {
1877     if (oldToolTip)
1878         [self _sendToolTipMouseExited];
1879
1880     if (newToolTip && [newToolTip length] > 0) {
1881         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
1882         [self removeAllToolTips];
1883         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
1884         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
1885         [self _sendToolTipMouseEntered];
1886     }
1887 }
1888
1889 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut
1890 {
1891     if (!findIndicator) {
1892         _data->_findIndicatorWindow = 0;
1893         return;
1894     }
1895
1896     if (!_data->_findIndicatorWindow)
1897         _data->_findIndicatorWindow = FindIndicatorWindow::create(self);
1898
1899     _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut);
1900 }
1901
1902 - (void)_enterAcceleratedCompositingMode:(const LayerTreeContext&)layerTreeContext
1903 {
1904     ASSERT(!_data->_layerHostingView);
1905     ASSERT(!layerTreeContext.isEmpty());
1906
1907     // Create an NSView that will host our layer tree.
1908     _data->_layerHostingView.adoptNS([[NSView alloc] initWithFrame:[self bounds]]);
1909     [_data->_layerHostingView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1910
1911     [CATransaction begin];
1912     [CATransaction setDisableActions:YES];
1913     [self addSubview:_data->_layerHostingView.get()];
1914
1915     // Create a root layer that will back the NSView.
1916     RetainPtr<CALayer> rootLayer(AdoptNS, [[CALayer alloc] init]);
1917 #ifndef NDEBUG
1918     [rootLayer.get() setName:@"Hosting root layer"];
1919 #endif
1920
1921     CALayer *renderLayer = WKMakeRenderLayer(layerTreeContext.contextID);
1922     [rootLayer.get() addSublayer:renderLayer];
1923
1924     [_data->_layerHostingView.get() setLayer:rootLayer.get()];
1925     [_data->_layerHostingView.get() setWantsLayer:YES];
1926
1927     [CATransaction commit];
1928 }
1929
1930 - (void)_exitAcceleratedCompositingMode
1931 {
1932     ASSERT(_data->_layerHostingView);
1933
1934     [_data->_layerHostingView.get() removeFromSuperview];
1935     [_data->_layerHostingView.get() setLayer:nil];
1936     [_data->_layerHostingView.get() setWantsLayer:NO];
1937     
1938     _data->_layerHostingView = nullptr;
1939 }
1940
1941 - (void)_setAccessibilityWebProcessToken:(NSData *)data
1942 {
1943 #if !defined(BUILDING_ON_SNOW_LEOPARD)
1944     _data->_remoteAccessibilityChild = WKAXRemoteElementForToken(data);
1945     [self _updateRemoteAccessibilityRegistration:YES];
1946 #endif
1947 }
1948
1949 - (void)_setComplexTextInputEnabled:(BOOL)complexTextInputEnabled pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
1950 {
1951     BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
1952
1953     if (complexTextInputEnabled) {
1954         // Check if we're already allowing text input for this plug-in.
1955         if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
1956             return;
1957
1958         _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
1959
1960     } else {
1961         // Check if we got a request to disable complex text input for a plug-in that is not the current plug-in.
1962         if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
1963             return;
1964
1965         _data->_pluginComplexTextInputIdentifier = 0;
1966     }
1967
1968     if (inputSourceChanged) {
1969         // Inform the out of line window that the input source changed.
1970         [[WKTextInputWindowController sharedTextInputWindowController] keyboardInputSourceChanged];
1971     }
1972 }
1973
1974 - (void)_setPageHasCustomRepresentation:(BOOL)pageHasCustomRepresentation
1975 {
1976     _data->_pdfViewController = nullptr;
1977
1978     if (pageHasCustomRepresentation)
1979         _data->_pdfViewController = PDFViewController::create(self);
1980 }
1981
1982 - (void)_didFinishLoadingDataForCustomRepresentationWithSuggestedFilename:(const String&)suggestedFilename dataReference:(const CoreIPC::DataReference&)dataReference
1983 {
1984     ASSERT(_data->_pdfViewController);
1985
1986     _data->_pdfViewController->setPDFDocumentData(_data->_page->mainFrame()->mimeType(), suggestedFilename, dataReference);
1987 }
1988
1989 - (double)_customRepresentationZoomFactor
1990 {
1991     if (!_data->_pdfViewController)
1992         return 1;
1993
1994     return _data->_pdfViewController->zoomFactor();
1995 }
1996
1997 - (void)_setCustomRepresentationZoomFactor:(double)zoomFactor
1998 {
1999     if (!_data->_pdfViewController)
2000         return;
2001
2002     _data->_pdfViewController->setZoomFactor(zoomFactor);
2003 }
2004
2005 - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag
2006 {
2007     // We need to prevent re-entering this call to avoid crashing in AppKit.
2008     // Given the asynchronous nature of WebKit2 this can now happen.
2009     if (_data->_dragHasStarted)
2010         return;
2011     
2012     _data->_dragHasStarted = YES;
2013     [super dragImage:image
2014                   at:clientPoint
2015               offset:NSZeroSize
2016                event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent
2017           pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
2018               source:self
2019            slideBack:YES];
2020     _data->_dragHasStarted = NO;
2021 }
2022
2023 - (void)_setDrawingAreaSize:(NSSize)size
2024 {
2025     if (!_data->_page->drawingArea())
2026         return;
2027     
2028     _data->_page->drawingArea()->setSize(IntSize(size), IntSize(_data->_resizeScrollOffset));
2029     _data->_resizeScrollOffset = NSZeroSize;
2030 }
2031
2032 - (void)_didChangeScrollbarsForMainFrame
2033 {
2034     [self _updateGrowBoxForWindowFrameChange];
2035 }
2036
2037 #if ENABLE(FULLSCREEN_API)
2038 - (WKFullScreenWindowController*)fullScreenWindowController
2039 {
2040     if (!_data->_fullScreenWindowController) {
2041         _data->_fullScreenWindowController.adoptNS([[WKFullScreenWindowController alloc] init]);
2042         [_data->_fullScreenWindowController.get() setWebView:self];
2043     }
2044     return _data->_fullScreenWindowController.get();
2045 }
2046 #endif
2047
2048 @end
2049
2050 @implementation WKView (Private)
2051
2052 - (void)disableFrameSizeUpdates
2053 {
2054     _frameSizeUpdatesDisabledCount++;
2055 }
2056
2057 - (void)enableFrameSizeUpdates
2058 {
2059     if (!_frameSizeUpdatesDisabledCount)
2060         return;
2061     
2062     if (!(--_frameSizeUpdatesDisabledCount))
2063         [self _setDrawingAreaSize:[self frame].size];
2064 }
2065
2066 - (BOOL)frameSizeUpdatesDisabled
2067 {
2068     return _frameSizeUpdatesDisabledCount > 0;
2069 }
2070
2071 - (void)performDictionaryLookupAtCurrentMouseLocation
2072 {
2073     NSPoint thePoint = [NSEvent mouseLocation];
2074     thePoint = [[self window] convertScreenToBase:thePoint];
2075     thePoint = [self convertPoint:thePoint fromView:nil];
2076
2077     _data->_page->performDictionaryLookupAtLocation(FloatPoint(thePoint.x, thePoint.y));
2078 }
2079
2080 @end
2081