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