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