Disable window occlusion notifications for App Store on Mac.
[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 #if USE(DICTATION_ALTERNATIVES)
30 #import <AppKit/NSTextAlternatives.h>
31 #import <AppKit/NSAttributedString.h>
32 #endif
33
34 #import "AttributedString.h"
35 #import "ColorSpaceData.h"
36 #import "DataReference.h"
37 #import "DrawingAreaProxyImpl.h"
38 #import "EditorState.h"
39 #import "FindIndicator.h"
40 #import "FindIndicatorWindow.h"
41 #import "LayerTreeContext.h"
42 #import "Logging.h"
43 #import "NativeWebKeyboardEvent.h"
44 #import "NativeWebMouseEvent.h"
45 #import "NativeWebWheelEvent.h"
46 #import "PDFViewController.h"
47 #import "PageClientImpl.h"
48 #import "PasteboardTypes.h"
49 #import "RemoteLayerTreeDrawingAreaProxy.h"
50 #import "StringUtilities.h"
51 #import "TextChecker.h"
52 #import "TextCheckerState.h"
53 #import "TiledCoreAnimationDrawingAreaProxy.h"
54 #import "WKAPICast.h"
55 #import "WKFullScreenWindowController.h"
56 #import "WKPrintingView.h"
57 #import "WKStringCF.h"
58 #import "WKTextInputWindowController.h"
59 #import "WKViewInternal.h"
60 #import "WKViewPrivate.h"
61 #import "WebContext.h"
62 #import "WebEventFactory.h"
63 #import "WebFullScreenManagerProxy.h"
64 #import "WebPage.h"
65 #import "WebPageProxy.h"
66 #import "WebProcessProxy.h"
67 #import "WebSystemInterface.h"
68 #import <QuartzCore/QuartzCore.h>
69 #import <WebCore/ColorMac.h>
70 #import <WebCore/DragController.h>
71 #import <WebCore/DragData.h>
72 #import <WebCore/DragSession.h>
73 #import <WebCore/FloatRect.h>
74 #import <WebCore/Image.h>
75 #import <WebCore/IntRect.h>
76 #import <WebCore/KeyboardEvent.h>
77 #import <WebCore/LocalizedStrings.h>
78 #import <WebCore/PlatformEventFactoryMac.h>
79 #import <WebCore/PlatformScreen.h>
80 #import <WebCore/Region.h>
81 #import <WebCore/RunLoop.h>
82 #import <WebCore/SharedBuffer.h>
83 #import <WebCore/TextAlternativeWithRange.h>
84 #import <WebCore/WebCoreNSStringExtras.h>
85 #import <WebCore/WebCoreFullScreenPlaceholderView.h>
86 #import <WebCore/FileSystem.h>
87 #import <WebKitSystemInterface.h>
88 #import <sys/stat.h>
89 #import <wtf/RefPtr.h>
90 #import <wtf/RetainPtr.h>
91
92 /* API internals. */
93 #import "WKBrowsingContextControllerInternal.h"
94 #import "WKBrowsingContextGroupInternal.h"
95 #import "WKProcessGroupInternal.h"
96
97 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
98 static BOOL windowOcclusionNotificationsAreRegistered = NO;
99 #endif
100
101 @interface NSApplication (WKNSApplicationDetails)
102 - (void)speakString:(NSString *)string;
103 - (void)_setCurrentEvent:(NSEvent *)event;
104 @end
105
106 @interface NSObject (WKNSTextInputContextDetails)
107 - (BOOL)wantsToHandleMouseEvents;
108 - (BOOL)handleMouseEvent:(NSEvent *)event;
109 @end
110
111 @interface NSWindow (WKNSWindowDetails)
112 - (NSRect)_intersectBottomCornersWithRect:(NSRect)viewRect;
113 - (void)_maskRoundedBottomCorners:(NSRect)clipRect;
114 @end
115
116 using namespace WebKit;
117 using namespace WebCore;
118
119 namespace WebKit {
120
121 typedef id <NSValidatedUserInterfaceItem> ValidationItem;
122 typedef Vector<RetainPtr<ValidationItem> > ValidationVector;
123 typedef HashMap<String, ValidationVector> ValidationMap;
124
125 }
126
127 struct WKViewInterpretKeyEventsParameters {
128     bool eventInterpretationHadSideEffects;
129     bool consumedByIM;
130     bool executingSavedKeypressCommands;
131     Vector<KeypressCommand>* commands;
132 };
133
134 @interface WKView ()
135 - (void)_accessibilityRegisterUIProcessTokens;
136 - (void)_disableComplexTextInputIfNecessary;
137 - (float)_intrinsicDeviceScaleFactor;
138 - (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent;
139 - (void)_setDrawingAreaSize:(NSSize)size;
140 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState;
141 - (BOOL)_shouldUseTiledDrawingArea;
142 - (void)_setIsWindowOccluded:(BOOL)isWindowOccluded;
143 - (void)_enableWindowOcclusionNotifications;
144 - (void)_disableWindowOcclusionNotifications;
145 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
146 + (BOOL)_registerWindowOcclusionNotificationHandlers;
147 + (BOOL)_unregisterWindowOcclusionNotificationHandlers;
148 #endif
149 + (Vector<WKView *>&)_allViews;
150 @end
151
152 @interface WKViewData : NSObject {
153 @public
154     OwnPtr<PageClientImpl> _pageClient;
155     RefPtr<WebPageProxy> _page;
156     
157     // Cache of the associated WKBrowsingContextController.
158     RetainPtr<WKBrowsingContextController> _browsingContextController;
159
160     // For ToolTips.
161     NSToolTipTag _lastToolTipTag;
162     id _trackingRectOwner;
163     void* _trackingRectUserData;
164
165     RetainPtr<NSView> _layerHostingView;
166
167     RetainPtr<id> _remoteAccessibilityChild;
168     
169     // For asynchronous validation.
170     ValidationMap _validationMap;
171
172     OwnPtr<PDFViewController> _pdfViewController;
173
174     OwnPtr<FindIndicatorWindow> _findIndicatorWindow;
175     // We keep here the event when resending it to
176     // the application to distinguish the case of a new event from one 
177     // that has been already sent to WebCore.
178     RetainPtr<NSEvent> _keyDownEventBeingResent;
179     WKViewInterpretKeyEventsParameters* _interpretKeyEventsParameters;
180
181     NSSize _resizeScrollOffset;
182
183     // The identifier of the plug-in we want to send complex text input to, or 0 if there is none.
184     uint64_t _pluginComplexTextInputIdentifier;
185
186     // The state of complex text input for the plug-in.
187     PluginComplexTextInputState _pluginComplexTextInputState;
188
189     bool _inBecomeFirstResponder;
190     bool _inResignFirstResponder;
191     NSEvent *_mouseDownEvent;
192     BOOL _ignoringMouseDraggedEvents;
193
194     id _flagsChangedEventMonitor;
195 #if ENABLE(GESTURE_EVENTS)
196     id _endGestureMonitor;
197 #endif
198     
199 #if ENABLE(FULLSCREEN_API)
200     RetainPtr<WKFullScreenWindowController> _fullScreenWindowController;
201 #endif
202
203     BOOL _hasSpellCheckerDocumentTag;
204     NSInteger _spellCheckerDocumentTag;
205
206     BOOL _inSecureInputState;
207
208     NSRect _windowBottomCornerIntersectionRect;
209     
210     unsigned _frameSizeUpdatesDisabledCount;
211
212     // Whether the containing window of the WKView has a valid backing store.
213     // The window server invalidates the backing store whenever the window is resized or minimized.
214     // We use this flag to determine when we need to paint the background (white or clear)
215     // when the web process is unresponsive or takes too long to paint.
216     BOOL _windowHasValidBackingStore;
217
218     RetainPtr<NSColorSpace> _colorSpace;
219
220     RefPtr<WebCore::Image> _promisedImage;
221     String _promisedFilename;
222     String _promisedURL;
223
224     NSSize _intrinsicContentSize;
225     BOOL _expandsToFitContentViaAutoLayout;
226     BOOL _isWindowOccluded;
227 }
228
229 @end
230
231 @implementation WKViewData
232 @end
233
234
235 @interface WKResponderChainSink : NSResponder {
236     NSResponder *_lastResponderInChain;
237     bool _didReceiveUnhandledCommand;
238 }
239 - (id)initWithResponderChain:(NSResponder *)chain;
240 - (void)detach;
241 - (bool)didReceiveUnhandledCommand;
242 @end
243
244 @interface WKFlippedView : NSView
245 @end
246
247 @implementation WKFlippedView
248
249 - (BOOL)isFlipped
250 {
251     return YES;
252 }
253
254 @end
255
256 @implementation WKView
257
258 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup
259 {
260     return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:nil];
261 }
262
263 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup relatedToView:(WKView *)relatedView
264 {
265     return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:relatedView ? toAPI(relatedView->_data->_page.get()) : nil];
266 }
267
268 - (void)dealloc
269 {
270     _data->_page->close();
271
272     ASSERT(!_data->_inSecureInputState);
273
274     [_data release];
275     _data = nil;
276
277     Vector<WKView *>& allViews = [WKView _allViews];
278     allViews.remove(allViews.find(self));
279
280     WebContext::statistics().wkViewCount--;
281
282     [super dealloc];
283 }
284
285 - (WKBrowsingContextController *)browsingContextController
286 {
287     if (!_data->_browsingContextController)
288         _data->_browsingContextController.adoptNS([[WKBrowsingContextController alloc] _initWithPageRef:[self pageRef]]);
289     return _data->_browsingContextController.get();
290 }
291
292 - (void)setDrawsBackground:(BOOL)drawsBackground
293 {
294     _data->_page->setDrawsBackground(drawsBackground);
295 }
296
297 - (BOOL)drawsBackground
298 {
299     return _data->_page->drawsBackground();
300 }
301
302 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
303 {
304     _data->_page->setDrawsTransparentBackground(drawsTransparentBackground);
305 }
306
307 - (BOOL)drawsTransparentBackground
308 {
309     return _data->_page->drawsTransparentBackground();
310 }
311
312 - (BOOL)acceptsFirstResponder
313 {
314     return YES;
315 }
316
317 - (BOOL)becomeFirstResponder
318 {
319     NSSelectionDirection direction = [[self window] keyViewSelectionDirection];
320
321     _data->_inBecomeFirstResponder = true;
322     
323     [self _updateSecureInputState];
324     _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
325
326     _data->_inBecomeFirstResponder = false;
327     
328     if (direction != NSDirectSelection) {
329         NSEvent *event = [NSApp currentEvent];
330         NSEvent *keyboardEvent = nil;
331         if ([event type] == NSKeyDown || [event type] == NSKeyUp)
332             keyboardEvent = event;
333         _data->_page->setInitialFocus(direction == NSSelectingNext, keyboardEvent != nil, NativeWebKeyboardEvent(keyboardEvent, self));
334     }
335     return YES;
336 }
337
338 - (BOOL)resignFirstResponder
339 {
340     _data->_inResignFirstResponder = true;
341
342     if (_data->_page->editorState().hasComposition && !_data->_page->editorState().shouldIgnoreCompositionSelectionChange)
343         _data->_page->cancelComposition();
344     [self _resetTextInputState];
345     
346     if (!_data->_page->maintainsInactiveSelection())
347         _data->_page->clearSelection();
348     
349     _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused);
350
351     _data->_inResignFirstResponder = false;
352
353     return YES;
354 }
355
356 - (void)viewWillStartLiveResize
357 {
358     _data->_page->viewWillStartLiveResize();
359 }
360
361 - (void)viewDidEndLiveResize
362 {
363     _data->_page->viewWillEndLiveResize();
364 }
365
366 - (BOOL)isFlipped
367 {
368     return YES;
369 }
370
371 - (NSSize)intrinsicContentSize
372 {
373     return _data->_intrinsicContentSize;
374 }
375
376 - (void)setFrameSize:(NSSize)size
377 {
378     if (!NSEqualSizes(size, [self frame].size))
379         _data->_windowHasValidBackingStore = NO;
380
381     [super setFrameSize:size];
382
383     if (![self frameSizeUpdatesDisabled]) {
384         if (_data->_expandsToFitContentViaAutoLayout)
385             _data->_page->viewExposedRectChanged([self visibleRect]);
386         [self _setDrawingAreaSize:size];
387     }
388 }
389
390 - (void)_updateWindowAndViewFrames
391 {
392     NSWindow *window = [self window];
393     ASSERT(window);
394     
395     NSRect windowFrameInScreenCoordinates = [window frame];
396     NSRect viewFrameInWindowCoordinates = [self convertRect:[self frame] toView:nil];
397     NSPoint accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue];
398     
399     _data->_page->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates), IntPoint(accessibilityPosition));
400     if (_data->_expandsToFitContentViaAutoLayout)
401         _data->_page->viewExposedRectChanged([self visibleRect]);
402 }
403
404 - (void)renewGState
405 {
406     // Hide the find indicator.
407     _data->_findIndicatorWindow = nullptr;
408
409     // Update the view frame.
410     if ([self window])
411         [self _updateWindowAndViewFrames];
412
413     [super renewGState];
414 }
415
416 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState
417 {
418     _data->_pluginComplexTextInputState = pluginComplexTextInputState;
419     
420     if (_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled)
421         return;
422
423     // Send back an empty string to the plug-in. This will disable text input.
424     _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, String());
425 }
426
427 typedef HashMap<SEL, String> SelectorNameMap;
428
429 // Map selectors into Editor command names.
430 // This is not needed for any selectors that have the same name as the Editor command.
431 static const SelectorNameMap* createSelectorExceptionMap()
432 {
433     SelectorNameMap* map = new HashMap<SEL, String>;
434     
435     map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
436     map->add(@selector(insertParagraphSeparator:), "InsertNewline");
437     map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
438     map->add(@selector(pageDown:), "MovePageDown");
439     map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
440     map->add(@selector(pageUp:), "MovePageUp");
441     map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
442     map->add(@selector(scrollPageDown:), "ScrollPageForward");
443     map->add(@selector(scrollPageUp:), "ScrollPageBackward");
444     
445     return map;
446 }
447
448 static String commandNameForSelector(SEL selector)
449 {
450     // Check the exception map first.
451     static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
452     SelectorNameMap::const_iterator it = exceptionMap->find(selector);
453     if (it != exceptionMap->end())
454         return it->value;
455     
456     // Remove the trailing colon.
457     // No need to capitalize the command name since Editor command names are
458     // not case sensitive.
459     const char* selectorName = sel_getName(selector);
460     size_t selectorNameLength = strlen(selectorName);
461     if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
462         return String();
463     return String(selectorName, selectorNameLength - 1);
464 }
465
466 // Editing commands
467
468 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
469
470 WEBCORE_COMMAND(alignCenter)
471 WEBCORE_COMMAND(alignJustified)
472 WEBCORE_COMMAND(alignLeft)
473 WEBCORE_COMMAND(alignRight)
474 WEBCORE_COMMAND(copy)
475 WEBCORE_COMMAND(cut)
476 WEBCORE_COMMAND(delete)
477 WEBCORE_COMMAND(deleteBackward)
478 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
479 WEBCORE_COMMAND(deleteForward)
480 WEBCORE_COMMAND(deleteToBeginningOfLine)
481 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
482 WEBCORE_COMMAND(deleteToEndOfLine)
483 WEBCORE_COMMAND(deleteToEndOfParagraph)
484 WEBCORE_COMMAND(deleteToMark)
485 WEBCORE_COMMAND(deleteWordBackward)
486 WEBCORE_COMMAND(deleteWordForward)
487 WEBCORE_COMMAND(ignoreSpelling)
488 WEBCORE_COMMAND(indent)
489 WEBCORE_COMMAND(insertBacktab)
490 WEBCORE_COMMAND(insertLineBreak)
491 WEBCORE_COMMAND(insertNewline)
492 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
493 WEBCORE_COMMAND(insertParagraphSeparator)
494 WEBCORE_COMMAND(insertTab)
495 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
496 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
497 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
498 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
499 WEBCORE_COMMAND(moveBackward)
500 WEBCORE_COMMAND(moveBackwardAndModifySelection)
501 WEBCORE_COMMAND(moveDown)
502 WEBCORE_COMMAND(moveDownAndModifySelection)
503 WEBCORE_COMMAND(moveForward)
504 WEBCORE_COMMAND(moveForwardAndModifySelection)
505 WEBCORE_COMMAND(moveLeft)
506 WEBCORE_COMMAND(moveLeftAndModifySelection)
507 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
508 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
509 WEBCORE_COMMAND(moveRight)
510 WEBCORE_COMMAND(moveRightAndModifySelection)
511 WEBCORE_COMMAND(moveToBeginningOfDocument)
512 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
513 WEBCORE_COMMAND(moveToBeginningOfLine)
514 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
515 WEBCORE_COMMAND(moveToBeginningOfParagraph)
516 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
517 WEBCORE_COMMAND(moveToBeginningOfSentence)
518 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
519 WEBCORE_COMMAND(moveToEndOfDocument)
520 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
521 WEBCORE_COMMAND(moveToEndOfLine)
522 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
523 WEBCORE_COMMAND(moveToEndOfParagraph)
524 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
525 WEBCORE_COMMAND(moveToEndOfSentence)
526 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
527 WEBCORE_COMMAND(moveToLeftEndOfLine)
528 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
529 WEBCORE_COMMAND(moveToRightEndOfLine)
530 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
531 WEBCORE_COMMAND(moveUp)
532 WEBCORE_COMMAND(moveUpAndModifySelection)
533 WEBCORE_COMMAND(moveWordBackward)
534 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
535 WEBCORE_COMMAND(moveWordForward)
536 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
537 WEBCORE_COMMAND(moveWordLeft)
538 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
539 WEBCORE_COMMAND(moveWordRight)
540 WEBCORE_COMMAND(moveWordRightAndModifySelection)
541 WEBCORE_COMMAND(outdent)
542 WEBCORE_COMMAND(pageDown)
543 WEBCORE_COMMAND(pageDownAndModifySelection)
544 WEBCORE_COMMAND(pageUp)
545 WEBCORE_COMMAND(pageUpAndModifySelection)
546 WEBCORE_COMMAND(paste)
547 WEBCORE_COMMAND(pasteAsPlainText)
548 WEBCORE_COMMAND(scrollPageDown)
549 WEBCORE_COMMAND(scrollPageUp)
550 WEBCORE_COMMAND(scrollLineDown)
551 WEBCORE_COMMAND(scrollLineUp)
552 WEBCORE_COMMAND(scrollToBeginningOfDocument)
553 WEBCORE_COMMAND(scrollToEndOfDocument)
554 WEBCORE_COMMAND(selectAll)
555 WEBCORE_COMMAND(selectLine)
556 WEBCORE_COMMAND(selectParagraph)
557 WEBCORE_COMMAND(selectSentence)
558 WEBCORE_COMMAND(selectToMark)
559 WEBCORE_COMMAND(selectWord)
560 WEBCORE_COMMAND(setMark)
561 WEBCORE_COMMAND(subscript)
562 WEBCORE_COMMAND(superscript)
563 WEBCORE_COMMAND(swapWithMark)
564 WEBCORE_COMMAND(takeFindStringFromSelection)
565 WEBCORE_COMMAND(transpose)
566 WEBCORE_COMMAND(underline)
567 WEBCORE_COMMAND(unscript)
568 WEBCORE_COMMAND(yank)
569 WEBCORE_COMMAND(yankAndSelect)
570
571 #undef WEBCORE_COMMAND
572
573 // This method is needed to support Mac OS X services.
574
575 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
576 {
577     size_t numTypes = [types count];
578     [pasteboard declareTypes:types owner:nil];
579     for (size_t i = 0; i < numTypes; ++i) {
580         if ([[types objectAtIndex:i] isEqualTo:NSStringPboardType])
581             [pasteboard setString:_data->_page->stringSelectionForPasteboard() forType:NSStringPboardType];
582         else {
583             RefPtr<SharedBuffer> buffer = _data->_page->dataSelectionForPasteboard([types objectAtIndex:i]);
584             [pasteboard setData:buffer ? [buffer->createNSData() autorelease] : nil forType:[types objectAtIndex:i]];
585        }
586     }
587     return YES;
588 }
589
590 - (void)centerSelectionInVisibleArea:(id)sender 
591
592     _data->_page->centerSelectionInVisibleArea();
593 }
594
595 // This method is needed to support Mac OS X services.
596
597 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
598 {
599     BOOL isValidSendType = !sendType || ([PasteboardTypes::forSelection() containsObject:sendType] && !_data->_page->editorState().selectionIsNone);
600     BOOL isValidReturnType = NO;
601     if (!returnType)
602         isValidReturnType = YES;
603     else if ([PasteboardTypes::forEditing() containsObject:returnType] && _data->_page->editorState().isContentEditable) {
604         // We can insert strings in any editable context.  We can insert other types, like images, only in rich edit contexts.
605         isValidReturnType = _data->_page->editorState().isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType];
606     }
607     if (isValidSendType && isValidReturnType)
608         return self;
609     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
610 }
611
612 // This method is needed to support Mac OS X services.
613
614 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard 
615 {
616     return _data->_page->readSelectionFromPasteboard([pasteboard name]);
617 }
618
619 /*
620
621 When possible, editing-related methods should be implemented in WebCore with the
622 EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing
623 individual methods here with Mac-specific code.
624
625 Editing-related methods still unimplemented that are implemented in WebKit1:
626
627 - (void)capitalizeWord:(id)sender;
628 - (void)changeFont:(id)sender;
629 - (void)complete:(id)sender;
630 - (void)copyFont:(id)sender;
631 - (void)lowercaseWord:(id)sender;
632 - (void)makeBaseWritingDirectionLeftToRight:(id)sender;
633 - (void)makeBaseWritingDirectionNatural:(id)sender;
634 - (void)makeBaseWritingDirectionRightToLeft:(id)sender;
635 - (void)pasteFont:(id)sender;
636 - (void)scrollLineDown:(id)sender;
637 - (void)scrollLineUp:(id)sender;
638 - (void)showGuessPanel:(id)sender;
639 - (void)uppercaseWord:(id)sender;
640
641 Some other editing-related methods still unimplemented:
642
643 - (void)changeCaseOfLetter:(id)sender;
644 - (void)copyRuler:(id)sender;
645 - (void)insertContainerBreak:(id)sender;
646 - (void)insertDoubleQuoteIgnoringSubstitution:(id)sender;
647 - (void)insertSingleQuoteIgnoringSubstitution:(id)sender;
648 - (void)pasteRuler:(id)sender;
649 - (void)toggleRuler:(id)sender;
650 - (void)transposeWords:(id)sender;
651
652 */
653
654 // Menu items validation
655
656 static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item)
657 {
658     if (![(NSObject *)item isKindOfClass:[NSMenuItem class]])
659         return nil;
660     return (NSMenuItem *)item;
661 }
662
663 static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item)
664 {
665     if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]])
666         return nil;
667     return (NSToolbarItem *)item;
668 }
669
670 static void validateCommandCallback(WKStringRef commandName, bool isEnabled, int32_t state, WKErrorRef error, void* context)
671 {
672     // If the process exits before the command can be validated, we'll be called back with an error.
673     if (error)
674         return;
675     
676     WKView* wkView = static_cast<WKView*>(context);
677     ASSERT(wkView);
678     
679     [wkView _setUserInterfaceItemState:nsStringFromWebCoreString(toImpl(commandName)->string()) enabled:isEnabled state:state];
680 }
681
682 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
683 {
684     SEL action = [item action];
685
686     if (action == @selector(showGuessPanel:)) {
687         if (NSMenuItem *menuItem = ::menuItem(item))
688             [menuItem setTitle:contextMenuItemTagShowSpellingPanel(![[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible])];
689         return _data->_page->editorState().isContentEditable;
690     }
691
692     if (action == @selector(checkSpelling:) || action == @selector(changeSpelling:))
693         return _data->_page->editorState().isContentEditable;
694
695     if (action == @selector(toggleContinuousSpellChecking:)) {
696         bool enabled = TextChecker::isContinuousSpellCheckingAllowed();
697         bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled;
698         [menuItem(item) setState:checked ? NSOnState : NSOffState];
699         return enabled;
700     }
701
702     if (action == @selector(toggleGrammarChecking:)) {
703         bool checked = TextChecker::state().isGrammarCheckingEnabled;
704         [menuItem(item) setState:checked ? NSOnState : NSOffState];
705         return YES;
706     }
707
708     if (action == @selector(toggleAutomaticSpellingCorrection:)) {
709         bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled;
710         [menuItem(item) setState:checked ? NSOnState : NSOffState];
711         return _data->_page->editorState().isContentEditable;
712     }
713
714     if (action == @selector(orderFrontSubstitutionsPanel:)) {
715         if (NSMenuItem *menuItem = ::menuItem(item))
716             [menuItem setTitle:contextMenuItemTagShowSubstitutions(![[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible])];
717         return _data->_page->editorState().isContentEditable;
718     }
719
720     if (action == @selector(toggleSmartInsertDelete:)) {
721         bool checked = _data->_page->isSmartInsertDeleteEnabled();
722         [menuItem(item) setState:checked ? NSOnState : NSOffState];
723         return _data->_page->editorState().isContentEditable;
724     }
725
726     if (action == @selector(toggleAutomaticQuoteSubstitution:)) {
727         bool checked = TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
728         [menuItem(item) setState:checked ? NSOnState : NSOffState];
729         return _data->_page->editorState().isContentEditable;
730     }
731
732     if (action == @selector(toggleAutomaticDashSubstitution:)) {
733         bool checked = TextChecker::state().isAutomaticDashSubstitutionEnabled;
734         [menuItem(item) setState:checked ? NSOnState : NSOffState];
735         return _data->_page->editorState().isContentEditable;
736     }
737
738     if (action == @selector(toggleAutomaticLinkDetection:)) {
739         bool checked = TextChecker::state().isAutomaticLinkDetectionEnabled;
740         [menuItem(item) setState:checked ? NSOnState : NSOffState];
741         return _data->_page->editorState().isContentEditable;
742     }
743
744     if (action == @selector(toggleAutomaticTextReplacement:)) {
745         bool checked = TextChecker::state().isAutomaticTextReplacementEnabled;
746         [menuItem(item) setState:checked ? NSOnState : NSOffState];
747         return _data->_page->editorState().isContentEditable;
748     }
749
750     if (action == @selector(uppercaseWord:) || action == @selector(lowercaseWord:) || action == @selector(capitalizeWord:))
751         return _data->_page->editorState().selectionIsRange && _data->_page->editorState().isContentEditable;
752     
753     if (action == @selector(stopSpeaking:))
754         return [NSApp isSpeaking];
755     
756     // The centerSelectionInVisibleArea: selector is enabled if there's a selection range or if there's an insertion point in an editable area.
757     if (action == @selector(centerSelectionInVisibleArea:))
758         return _data->_page->editorState().selectionIsRange || (_data->_page->editorState().isContentEditable && !_data->_page->editorState().selectionIsNone);
759
760     // Next, handle editor commands. Start by returning YES for anything that is not an editor command.
761     // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized.
762     String commandName = commandNameForSelector([item action]);
763     if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName))
764         return YES;
765
766     // Add this item to the vector of items for a given command that are awaiting validation.
767     ValidationMap::AddResult addResult = _data->_validationMap.add(commandName, ValidationVector());
768     addResult.iterator->value.append(item);
769     if (addResult.isNewEntry) {
770         // If we are not already awaiting validation for this command, start the asynchronous validation process.
771         // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
772         // we asked for the same command; there is no guarantee the answer is still valid.
773         _data->_page->validateCommand(commandName, ValidateCommandCallback::create(self, validateCommandCallback));
774     }
775
776     // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called.
777     // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment.
778     // But returning NO here would be worse; that would make keyboard commands such as command-C fail.
779     return YES;
780 }
781
782 static void speakString(WKStringRef string, WKErrorRef error, void*)
783 {
784     if (error)
785         return;
786     if (!string)
787         return;
788
789     NSString *convertedString = toImpl(string)->string();
790     [NSApp speakString:convertedString];
791 }
792
793 - (IBAction)startSpeaking:(id)sender
794 {
795     _data->_page->getSelectionOrContentsAsString(StringCallback::create(0, speakString));
796 }
797
798 - (IBAction)stopSpeaking:(id)sender
799 {
800     [NSApp stopSpeaking:sender];
801 }
802
803 - (IBAction)showGuessPanel:(id)sender
804 {
805     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
806     if (!checker) {
807         LOG_ERROR("No NSSpellChecker");
808         return;
809     }
810     
811     NSPanel *spellingPanel = [checker spellingPanel];
812     if ([spellingPanel isVisible]) {
813         [spellingPanel orderOut:sender];
814         return;
815     }
816     
817     _data->_page->advanceToNextMisspelling(true);
818     [spellingPanel orderFront:sender];
819 }
820
821 - (IBAction)checkSpelling:(id)sender
822 {
823     _data->_page->advanceToNextMisspelling(false);
824 }
825
826 - (void)changeSpelling:(id)sender
827 {
828     NSString *word = [[sender selectedCell] stringValue];
829
830     _data->_page->changeSpellingToWord(word);
831 }
832
833 - (IBAction)toggleContinuousSpellChecking:(id)sender
834 {
835     bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled;
836     TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled);
837
838     _data->_page->process()->updateTextCheckerState();
839 }
840
841 - (BOOL)isGrammarCheckingEnabled
842 {
843     return TextChecker::state().isGrammarCheckingEnabled;
844 }
845
846 - (void)setGrammarCheckingEnabled:(BOOL)flag
847 {
848     if (static_cast<bool>(flag) == TextChecker::state().isGrammarCheckingEnabled)
849         return;
850     
851     TextChecker::setGrammarCheckingEnabled(flag);
852     _data->_page->process()->updateTextCheckerState();
853 }
854
855 - (IBAction)toggleGrammarChecking:(id)sender
856 {
857     bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled;
858     TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled);
859
860     _data->_page->process()->updateTextCheckerState();
861 }
862
863 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
864 {
865     TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
866
867     _data->_page->process()->updateTextCheckerState();
868 }
869
870 - (void)orderFrontSubstitutionsPanel:(id)sender
871 {
872     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
873     if (!checker) {
874         LOG_ERROR("No NSSpellChecker");
875         return;
876     }
877     
878     NSPanel *substitutionsPanel = [checker substitutionsPanel];
879     if ([substitutionsPanel isVisible]) {
880         [substitutionsPanel orderOut:sender];
881         return;
882     }
883     [substitutionsPanel orderFront:sender];
884 }
885
886 - (IBAction)toggleSmartInsertDelete:(id)sender
887 {
888     _data->_page->setSmartInsertDeleteEnabled(!_data->_page->isSmartInsertDeleteEnabled());
889 }
890
891 - (BOOL)isAutomaticQuoteSubstitutionEnabled
892 {
893     return TextChecker::state().isAutomaticQuoteSubstitutionEnabled;
894 }
895
896 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
897 {
898     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticQuoteSubstitutionEnabled)
899         return;
900
901     TextChecker::setAutomaticQuoteSubstitutionEnabled(flag);
902     _data->_page->process()->updateTextCheckerState();
903 }
904
905 - (void)toggleAutomaticQuoteSubstitution:(id)sender
906 {
907     TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled);
908     _data->_page->process()->updateTextCheckerState();
909 }
910
911 - (BOOL)isAutomaticDashSubstitutionEnabled
912 {
913     return TextChecker::state().isAutomaticDashSubstitutionEnabled;
914 }
915
916 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
917 {
918     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticDashSubstitutionEnabled)
919         return;
920
921     TextChecker::setAutomaticDashSubstitutionEnabled(flag);
922     _data->_page->process()->updateTextCheckerState();
923 }
924
925 - (void)toggleAutomaticDashSubstitution:(id)sender
926 {
927     TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled);
928     _data->_page->process()->updateTextCheckerState();
929 }
930
931 - (BOOL)isAutomaticLinkDetectionEnabled
932 {
933     return TextChecker::state().isAutomaticLinkDetectionEnabled;
934 }
935
936 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
937 {
938     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticLinkDetectionEnabled)
939         return;
940
941     TextChecker::setAutomaticLinkDetectionEnabled(flag);
942     _data->_page->process()->updateTextCheckerState();
943 }
944
945 - (void)toggleAutomaticLinkDetection:(id)sender
946 {
947     TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled);
948     _data->_page->process()->updateTextCheckerState();
949 }
950
951 - (BOOL)isAutomaticTextReplacementEnabled
952 {
953     return TextChecker::state().isAutomaticTextReplacementEnabled;
954 }
955
956 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
957 {
958     if (static_cast<bool>(flag) == TextChecker::state().isAutomaticTextReplacementEnabled)
959         return;
960
961     TextChecker::setAutomaticTextReplacementEnabled(flag);
962     _data->_page->process()->updateTextCheckerState();
963 }
964
965 - (void)toggleAutomaticTextReplacement:(id)sender
966 {
967     TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled);
968     _data->_page->process()->updateTextCheckerState();
969 }
970
971 - (void)uppercaseWord:(id)sender
972 {
973     _data->_page->uppercaseWord();
974 }
975
976 - (void)lowercaseWord:(id)sender
977 {
978     _data->_page->lowercaseWord();
979 }
980
981 - (void)capitalizeWord:(id)sender
982 {
983     _data->_page->capitalizeWord();
984 }
985
986 - (void)displayIfNeeded
987 {
988     // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. In the meantime,
989     // it is necessary to disable scren updates so we get a chance to redraw the corners before this 
990     // display is visible.
991     NSWindow *window = [self window];
992     BOOL shouldMaskWindow = window && !NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect);
993     if (shouldMaskWindow)
994         NSDisableScreenUpdates();
995
996     [super displayIfNeeded];
997
998     if (shouldMaskWindow) {
999         [window _maskRoundedBottomCorners:_data->_windowBottomCornerIntersectionRect];
1000         NSEnableScreenUpdates();
1001         _data->_windowBottomCornerIntersectionRect = NSZeroRect;
1002     }
1003 }
1004
1005 // Events
1006
1007 // Override this so that AppKit will send us arrow keys as key down events so we can
1008 // support them via the key bindings mechanism.
1009 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
1010 {
1011     return YES;
1012 }
1013
1014 - (void)_setMouseDownEvent:(NSEvent *)event
1015 {
1016     ASSERT(!event || [event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
1017     
1018     if (event == _data->_mouseDownEvent)
1019         return;
1020     
1021     [_data->_mouseDownEvent release];
1022     _data->_mouseDownEvent = [event retain];
1023 }
1024
1025 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
1026     - (void)Selector:(NSEvent *)theEvent \
1027     { \
1028         if ([[self inputContext] handleEvent:theEvent]) { \
1029             LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
1030             return; \
1031         } \
1032         NativeWebMouseEvent webEvent(theEvent, self); \
1033         _data->_page->handleMouseEvent(webEvent); \
1034     }
1035
1036 NATIVE_MOUSE_EVENT_HANDLER(mouseEntered)
1037 NATIVE_MOUSE_EVENT_HANDLER(mouseExited)
1038 NATIVE_MOUSE_EVENT_HANDLER(mouseMovedInternal)
1039 NATIVE_MOUSE_EVENT_HANDLER(mouseDownInternal)
1040 NATIVE_MOUSE_EVENT_HANDLER(mouseUpInternal)
1041 NATIVE_MOUSE_EVENT_HANDLER(mouseDraggedInternal)
1042 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDown)
1043 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDragged)
1044 NATIVE_MOUSE_EVENT_HANDLER(otherMouseMoved)
1045 NATIVE_MOUSE_EVENT_HANDLER(otherMouseUp)
1046 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDown)
1047 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDragged)
1048 NATIVE_MOUSE_EVENT_HANDLER(rightMouseUp)
1049
1050 #undef NATIVE_MOUSE_EVENT_HANDLER
1051
1052 #define NATIVE_EVENT_HANDLER(Selector, Type) \
1053     - (void)Selector:(NSEvent *)theEvent \
1054     { \
1055         NativeWeb##Type##Event webEvent = NativeWeb##Type##Event(theEvent, self); \
1056         _data->_page->handle##Type##Event(webEvent); \
1057     }
1058
1059 NATIVE_EVENT_HANDLER(scrollWheel, Wheel)
1060
1061 #undef NATIVE_EVENT_HANDLER
1062
1063 - (void)mouseMoved:(NSEvent *)event
1064 {
1065     // When a view is first responder, it gets mouse moved events even when the mouse is outside its visible rect.
1066     if (self == [[self window] firstResponder] && !NSPointInRect([self convertPoint:[event locationInWindow] fromView:nil], [self visibleRect]))
1067         return;
1068
1069     [self mouseMovedInternal:event];
1070 }
1071
1072 - (void)mouseDown:(NSEvent *)event
1073 {
1074     [self _setMouseDownEvent:event];
1075     _data->_ignoringMouseDraggedEvents = NO;
1076     [self mouseDownInternal:event];
1077 }
1078
1079 - (void)mouseUp:(NSEvent *)event
1080 {
1081     [self _setMouseDownEvent:nil];
1082     [self mouseUpInternal:event];
1083 }
1084
1085 - (void)mouseDragged:(NSEvent *)event
1086 {
1087     if (_data->_ignoringMouseDraggedEvents)
1088         return;
1089     [self mouseDraggedInternal:event];
1090 }
1091
1092 - (BOOL)acceptsFirstMouse:(NSEvent *)event
1093 {
1094     // There's a chance that responding to this event will run a nested event loop, and
1095     // fetching a new event might release the old one. Retaining and then autoreleasing
1096     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1097     [[event retain] autorelease];
1098     
1099     if (![self hitTest:[event locationInWindow]])
1100         return NO;
1101     
1102     [self _setMouseDownEvent:event];
1103     bool result = _data->_page->acceptsFirstMouse([event eventNumber], WebEventFactory::createWebMouseEvent(event, self));
1104     [self _setMouseDownEvent:nil];
1105     return result;
1106 }
1107
1108 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
1109 {
1110     // If this is the active window or we don't have a range selection, there is no need to perform additional checks
1111     // and we can avoid making a synchronous call to the WebProcess.
1112     if ([[self window] isKeyWindow] || _data->_page->editorState().selectionIsNone || !_data->_page->editorState().selectionIsRange)
1113         return NO;
1114
1115     // There's a chance that responding to this event will run a nested event loop, and
1116     // fetching a new event might release the old one. Retaining and then autoreleasing
1117     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1118     [[event retain] autorelease];
1119     
1120     if (![self hitTest:[event locationInWindow]])
1121         return NO;
1122     
1123     [self _setMouseDownEvent:event];
1124     bool result = _data->_page->shouldDelayWindowOrderingForEvent(WebEventFactory::createWebMouseEvent(event, self));
1125     [self _setMouseDownEvent:nil];
1126     return result;
1127 }
1128
1129 #if ENABLE(GESTURE_EVENTS)
1130
1131 static const short kIOHIDEventTypeScroll = 6;
1132
1133 - (void)shortCircuitedEndGestureWithEvent:(NSEvent *)event
1134 {
1135     if ([event subtype] != kIOHIDEventTypeScroll)
1136         return;
1137
1138     WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
1139     _data->_page->handleGestureEvent(webEvent);
1140
1141     if (_data->_endGestureMonitor) {
1142         [NSEvent removeMonitor:_data->_endGestureMonitor];
1143         _data->_endGestureMonitor = nil;
1144     }
1145 }
1146
1147 - (void)beginGestureWithEvent:(NSEvent *)event
1148 {
1149     if ([event subtype] != kIOHIDEventTypeScroll)
1150         return;
1151
1152     WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self);
1153     _data->_page->handleGestureEvent(webEvent);
1154
1155     if (!_data->_endGestureMonitor) {
1156         _data->_endGestureMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskEndGesture handler:^(NSEvent *blockEvent) {
1157             [self shortCircuitedEndGestureWithEvent:blockEvent];
1158             return blockEvent;
1159         }];
1160     }
1161 }
1162 #endif
1163
1164 - (void)doCommandBySelector:(SEL)selector
1165 {
1166     LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector));
1167
1168     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1169     if (parameters)
1170         parameters->consumedByIM = false;
1171
1172     // As in insertText:replacementRange:, we assume that the call comes from an input method if there is marked text.
1173     bool isFromInputMethod = _data->_page->editorState().hasComposition;
1174
1175     if (parameters && !isFromInputMethod) {
1176         KeypressCommand command(NSStringFromSelector(selector));
1177         parameters->commands->append(command);
1178         _data->_page->registerKeypressCommandName(command.commandName);
1179     } else {
1180         // FIXME: Send the command to Editor synchronously and only send it along the
1181         // responder chain if it's a selector that does not correspond to an editing command.
1182         [super doCommandBySelector:selector];
1183     }
1184 }
1185
1186 - (void)insertText:(id)string
1187 {
1188     // Unlike and NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context,
1189     // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText
1190     // command ensures that a keypress event is dispatched as appropriate.
1191     [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)];
1192 }
1193
1194 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
1195 {
1196     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1197     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1198
1199     if (replacementRange.location != NSNotFound)
1200         LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length);
1201     else
1202         LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
1203     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1204     if (parameters)
1205         parameters->consumedByIM = false;
1206
1207     NSString *text;
1208     bool isFromInputMethod = _data->_page->editorState().hasComposition;
1209
1210     Vector<TextAlternativeWithRange> dictationAlternatives;
1211
1212     if (isAttributedString) {
1213 #if USE(DICTATION_ALTERNATIVES)
1214         collectDictationTextAlternatives(string, dictationAlternatives);
1215 #endif
1216         // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data.
1217         text = [string string];
1218     } else
1219         text = string;
1220
1221     // insertText can be called for several reasons:
1222     // - If it's from normal key event processing (including key bindings), we may need to save the action to perform it later.
1223     // - 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.
1224     // 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.
1225     // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse),
1226     // then we also execute it immediately, as there will be no other chance.
1227     if (parameters && !isFromInputMethod) {
1228         // FIXME: Handle replacementRange in this case, too. It's known to occur in practice when canceling Press and Hold (see <rdar://11940670>).
1229         ASSERT(replacementRange.location == NSNotFound);
1230         KeypressCommand command("insertText:", text);
1231         parameters->commands->append(command);
1232         _data->_page->registerKeypressCommandName(command.commandName);
1233         return;
1234     }
1235
1236     String eventText = text;
1237     eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
1238     bool eventHandled;
1239     if (!dictationAlternatives.isEmpty())
1240         eventHandled = _data->_page->insertDictatedText(eventText, replacementRange.location, NSMaxRange(replacementRange), dictationAlternatives);
1241     else
1242         eventHandled = _data->_page->insertText(eventText, replacementRange.location, NSMaxRange(replacementRange));
1243
1244     if (parameters)
1245         parameters->eventInterpretationHadSideEffects |= eventHandled;
1246 }
1247
1248 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
1249 {
1250     if (!_data->_page->editorState().isContentEditable)
1251         return NO;
1252
1253     if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) != NSCommandKeyMask)
1254         return NO;
1255     
1256     // Here we special case cmd+b and cmd+i but not cmd+u, for historic reason.
1257     // This should not be changed, since it could break some Mac applications that
1258     // rely on this inherent behavior.
1259     // See https://bugs.webkit.org/show_bug.cgi?id=24943
1260     
1261     NSString *string = [event characters];
1262     if ([string caseInsensitiveCompare:@"b"] == NSOrderedSame) {
1263         _data->_page->executeEditCommand("ToggleBold");
1264         return YES;
1265     }
1266     if ([string caseInsensitiveCompare:@"i"] == NSOrderedSame) {
1267         _data->_page->executeEditCommand("ToggleItalic");
1268         return YES;
1269     }
1270     
1271     return NO;
1272 }
1273
1274 - (BOOL)performKeyEquivalent:(NSEvent *)event
1275 {
1276     // There's a chance that responding to this event will run a nested event loop, and
1277     // fetching a new event might release the old one. Retaining and then autoreleasing
1278     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1279     [[event retain] autorelease];
1280     
1281     BOOL eventWasSentToWebCore = (_data->_keyDownEventBeingResent == event);
1282
1283     if (!eventWasSentToWebCore)
1284         [self _disableComplexTextInputIfNecessary];
1285
1286     // Pass key combos through WebCore if there is a key binding available for
1287     // this event. This lets web pages have a crack at intercepting key-modified keypresses.
1288     // But don't do it if we have already handled the event.
1289     // Pressing Esc results in a fake event being sent - don't pass it to WebCore.
1290     if (!eventWasSentToWebCore && event == [NSApp currentEvent] && self == [[self window] firstResponder]) {
1291         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, self));
1292         return YES;
1293     }
1294     
1295     return [self _handleStyleKeyEquivalent:event] || [super performKeyEquivalent:event];
1296 }
1297
1298 - (void)keyUp:(NSEvent *)theEvent
1299 {
1300     LOG(TextInput, "keyUp:%p %@", theEvent, theEvent);
1301     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1302 }
1303
1304 - (void)_disableComplexTextInputIfNecessary
1305 {
1306     if (!_data->_pluginComplexTextInputIdentifier)
1307         return;
1308
1309     if (_data->_pluginComplexTextInputState != PluginComplexTextInputEnabled)
1310         return;
1311
1312     // Check if the text input window has been dismissed.
1313     if (![[WKTextInputWindowController sharedTextInputWindowController] hasMarkedText])
1314         [self _setPluginComplexTextInputState:PluginComplexTextInputDisabled];
1315 }
1316
1317 - (BOOL)_handlePluginComplexTextInputKeyDown:(NSEvent *)event
1318 {
1319     ASSERT(_data->_pluginComplexTextInputIdentifier);
1320     ASSERT(_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled);
1321
1322     BOOL usingLegacyCocoaTextInput = _data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy;
1323
1324     NSString *string = nil;
1325     BOOL didHandleEvent = [[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:event usingLegacyCocoaTextInput:usingLegacyCocoaTextInput string:&string];
1326
1327     if (string) {
1328         _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string);
1329
1330         if (!usingLegacyCocoaTextInput)
1331             _data->_pluginComplexTextInputState = PluginComplexTextInputDisabled;
1332     }
1333
1334     return didHandleEvent;
1335 }
1336
1337 - (BOOL)_tryHandlePluginComplexTextInputKeyDown:(NSEvent *)event
1338 {
1339     if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
1340         return NO;
1341
1342     // Check if the text input window has been dismissed and let the plug-in process know.
1343     // This is only valid with the updated Cocoa text input spec.
1344     [self _disableComplexTextInputIfNecessary];
1345
1346     // Try feeding the keyboard event directly to the plug-in.
1347     if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
1348         return [self _handlePluginComplexTextInputKeyDown:event];
1349
1350     return NO;
1351 }
1352
1353 - (void)keyDown:(NSEvent *)theEvent
1354 {
1355     LOG(TextInput, "keyDown:%p %@%s", theEvent, theEvent, (theEvent == _data->_keyDownEventBeingResent) ? " (re-sent)" : "");
1356
1357     // There's a chance that responding to this event will run a nested event loop, and
1358     // fetching a new event might release the old one. Retaining and then autoreleasing
1359     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1360     [[theEvent retain] autorelease];
1361
1362     if ([self _tryHandlePluginComplexTextInputKeyDown:theEvent]) {
1363         LOG(TextInput, "...handled by plug-in");
1364         return;
1365     }
1366
1367     // We could be receiving a key down from AppKit if we have re-sent an event
1368     // that maps to an action that is currently unavailable (for example a copy when
1369     // there is no range selection).
1370     // If this is the case we should ignore the key down.
1371     if (_data->_keyDownEventBeingResent == theEvent) {
1372         [super keyDown:theEvent];
1373         return;
1374     }
1375     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1376 }
1377
1378 - (void)flagsChanged:(NSEvent *)theEvent
1379 {
1380     LOG(TextInput, "flagsChanged:%p %@", theEvent, theEvent);
1381
1382     // There's a chance that responding to this event will run a nested event loop, and
1383     // fetching a new event might release the old one. Retaining and then autoreleasing
1384     // the current event prevents that from causing a problem inside WebKit or AppKit code.
1385     [[theEvent retain] autorelease];
1386
1387     unsigned short keyCode = [theEvent keyCode];
1388
1389     // Don't make an event from the num lock and function keys
1390     if (!keyCode || keyCode == 10 || keyCode == 63)
1391         return;
1392
1393     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
1394 }
1395
1396 - (void)_executeSavedKeypressCommands
1397 {
1398     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1399     if (!parameters || parameters->commands->isEmpty())
1400         return;
1401
1402     // We could be called again if the execution of one command triggers a call to selectedRange.
1403     // In this case, the state is up to date, and we don't need to execute any more saved commands to return a result.
1404     if (parameters->executingSavedKeypressCommands)
1405         return;
1406
1407     LOG(TextInput, "Executing %u saved keypress commands...", parameters->commands->size());
1408
1409     parameters->executingSavedKeypressCommands = true;
1410     parameters->eventInterpretationHadSideEffects |= _data->_page->executeKeypressCommands(*parameters->commands);
1411     parameters->commands->clear();
1412     parameters->executingSavedKeypressCommands = false;
1413
1414     LOG(TextInput, "...done executing saved keypress commands.");
1415 }
1416
1417 - (void)_notifyInputContextAboutDiscardedComposition
1418 {
1419     // <rdar://problem/9359055>: -discardMarkedText can only be called for active contexts.
1420     // FIXME: We fail to ever notify the input context if something (e.g. a navigation) happens while the window is not key.
1421     // This is not a problem when the window is key, because we discard marked text on resigning first responder.
1422     if (![[self window] isKeyWindow] || self != [[self window] firstResponder])
1423         return;
1424
1425     LOG(TextInput, "-> discardMarkedText");
1426     [[super inputContext] discardMarkedText]; // Inform the input method that we won't have an inline input area despite having been asked to.
1427 }
1428
1429 - (NSTextInputContext *)inputContext
1430 {
1431     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1432
1433     if (_data->_pluginComplexTextInputIdentifier && !parameters)
1434         return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
1435
1436     // Disable text input machinery when in non-editable content. An invisible inline input area affects performance, and can prevent Expose from working.
1437     if (!_data->_page->editorState().isContentEditable)
1438         return nil;
1439
1440     return [super inputContext];
1441 }
1442
1443 - (NSRange)selectedRange
1444 {
1445     [self _executeSavedKeypressCommands];
1446
1447     uint64_t selectionStart;
1448     uint64_t selectionLength;
1449     _data->_page->getSelectedRange(selectionStart, selectionLength);
1450
1451     NSRange result = NSMakeRange(selectionStart, selectionLength);
1452     if (result.location == NSNotFound)
1453         LOG(TextInput, "selectedRange -> (NSNotFound, %u)", result.length);
1454     else
1455         LOG(TextInput, "selectedRange -> (%u, %u)", result.location, result.length);
1456
1457     return result;
1458 }
1459
1460 - (BOOL)hasMarkedText
1461 {
1462     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1463
1464     BOOL result;
1465     if (parameters) {
1466         result = _data->_page->editorState().hasComposition;
1467         if (result) {
1468             // A saved command can confirm a composition, but it cannot start a new one.
1469             [self _executeSavedKeypressCommands];
1470             result = _data->_page->editorState().hasComposition;
1471         }
1472     } else {
1473         uint64_t location;
1474         uint64_t length;
1475         _data->_page->getMarkedRange(location, length);
1476         result = location != NSNotFound;
1477     }
1478
1479     LOG(TextInput, "hasMarkedText -> %u", result);
1480     return result;
1481 }
1482
1483 - (void)unmarkText
1484 {
1485     [self _executeSavedKeypressCommands];
1486
1487     LOG(TextInput, "unmarkText");
1488
1489     // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
1490     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1491
1492     if (parameters) {
1493         parameters->eventInterpretationHadSideEffects = true;
1494         parameters->consumedByIM = false;
1495     }
1496
1497     _data->_page->confirmComposition();
1498 }
1499
1500 - (NSArray *)validAttributesForMarkedText
1501 {
1502     static NSArray *validAttributes;
1503     if (!validAttributes) {
1504         validAttributes = [[NSArray alloc] initWithObjects:
1505                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
1506                            NSMarkedClauseSegmentAttributeName,
1507 #if USE(DICTATION_ALTERNATIVES)
1508                            NSTextAlternativesAttributeName,
1509 #endif
1510                            nil];
1511         // NSText also supports the following attributes, but it's
1512         // hard to tell which are really required for text input to
1513         // work well; I have not seen any input method make use of them yet.
1514         //     NSFontAttributeName, NSForegroundColorAttributeName,
1515         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
1516         CFRetain(validAttributes);
1517     }
1518     LOG(TextInput, "validAttributesForMarkedText -> (...)");
1519     return validAttributes;
1520 }
1521
1522 static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result)
1523 {
1524     int length = [[string string] length];
1525     
1526     int i = 0;
1527     while (i < length) {
1528         NSRange range;
1529         NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)];
1530         
1531         if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
1532             Color color = Color::black;
1533             if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName])
1534                 color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
1535             result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1));
1536         }
1537         
1538         i = range.location + range.length;
1539     }
1540 }
1541
1542 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange replacementRange:(NSRange)replacementRange
1543 {
1544     [self _executeSavedKeypressCommands];
1545
1546     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
1547     ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]);
1548
1549     LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelRange.location, newSelRange.length);
1550
1551     // Use pointer to get parameters passed to us by the caller of interpretKeyEvents.
1552     WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters;
1553
1554     if (parameters) {
1555         parameters->eventInterpretationHadSideEffects = true;
1556         parameters->consumedByIM = false;
1557     }
1558     
1559     Vector<CompositionUnderline> underlines;
1560     NSString *text;
1561
1562     if (isAttributedString) {
1563         // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation.
1564         text = [string string];
1565         extractUnderlines(string, underlines);
1566     } else
1567         text = string;
1568
1569     if (_data->_page->editorState().isInPasswordField) {
1570         // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField.
1571         // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard.
1572         ASSERT(!_data->_page->editorState().hasComposition);
1573         [self _notifyInputContextAboutDiscardedComposition];
1574         if ([text length] == 1 && [[text decomposedStringWithCanonicalMapping] characterAtIndex:0] < 0x80) {
1575             _data->_page->insertText(text, replacementRange.location, NSMaxRange(replacementRange));
1576         } else
1577             NSBeep();
1578         return;
1579     }
1580
1581     _data->_page->setComposition(text, underlines, newSelRange.location, NSMaxRange(newSelRange), replacementRange.location, NSMaxRange(replacementRange));
1582 }
1583
1584 - (NSRange)markedRange
1585 {
1586     [self _executeSavedKeypressCommands];
1587
1588     uint64_t location;
1589     uint64_t length;
1590     _data->_page->getMarkedRange(location, length);
1591
1592     LOG(TextInput, "markedRange -> (%u, %u)", location, length);
1593     return NSMakeRange(location, length);
1594 }
1595
1596 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
1597 {
1598     [self _executeSavedKeypressCommands];
1599
1600     if (!_data->_page->editorState().isContentEditable) {
1601         LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> nil", nsRange.location, nsRange.length);
1602         return nil;
1603     }
1604
1605     if (_data->_page->editorState().isInPasswordField)
1606         return nil;
1607
1608     AttributedString result;
1609     _data->_page->getAttributedSubstringFromRange(nsRange.location, NSMaxRange(nsRange), result);
1610
1611     if (actualRange) {
1612         *actualRange = nsRange;
1613         actualRange->length = [result.string.get() length];
1614     }
1615
1616     LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> \"%@\"", nsRange.location, nsRange.length, [result.string.get() string]);
1617     return [[result.string.get() retain] autorelease];
1618 }
1619
1620 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1621 {
1622     [self _executeSavedKeypressCommands];
1623
1624     NSWindow *window = [self window];
1625     
1626     if (window)
1627         thePoint = [window convertScreenToBase:thePoint];
1628     thePoint = [self convertPoint:thePoint fromView:nil];  // the point is relative to the main frame 
1629     
1630     uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint));
1631     LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result);
1632     return result;
1633 }
1634
1635 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
1636
1637     [self _executeSavedKeypressCommands];
1638
1639     // Just to match NSTextView's behavior. Regression tests cannot detect this;
1640     // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
1641     // (type something; try ranges (1, -1) and (2, -1).
1642     if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
1643         theRange.length = 0;
1644     
1645     NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange.location, theRange.length);
1646     resultRect = [self convertRect:resultRect toView:nil];
1647     
1648     NSWindow *window = [self window];
1649     if (window)
1650         resultRect.origin = [window convertBaseToScreen:resultRect.origin];
1651
1652     if (actualRange) {
1653         // FIXME: Update actualRange to match the range of first rect.
1654         *actualRange = theRange;
1655     }
1656
1657     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);
1658     return resultRect;
1659 }
1660
1661 #if ENABLE(DRAG_SUPPORT)
1662 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
1663 {
1664     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
1665     NSPoint windowMouseLoc = windowImageLoc;
1666    
1667     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
1668     _data->_ignoringMouseDraggedEvents = YES;
1669     
1670     _data->_page->dragEnded(IntPoint(windowMouseLoc), globalPoint(windowMouseLoc, [self window]), operation);
1671 }
1672
1673 - (DragApplicationFlags)applicationFlags:(id <NSDraggingInfo>)draggingInfo
1674 {
1675     uint32_t flags = 0;
1676     if ([NSApp modalWindow])
1677         flags = DragApplicationIsModal;
1678     if ([[self window] attachedSheet])
1679         flags |= DragApplicationHasAttachedSheet;
1680     if ([draggingInfo draggingSource] == self)
1681         flags |= DragApplicationIsSource;
1682     if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1683         flags |= DragApplicationIsCopyKeyDown;
1684     return static_cast<DragApplicationFlags>(flags);
1685 }
1686
1687 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
1688 {
1689     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1690     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1691     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1692
1693     _data->_page->resetDragOperation();
1694     _data->_page->dragEntered(&dragData, [[draggingInfo draggingPasteboard] name]);
1695     return NSDragOperationCopy;
1696 }
1697
1698 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
1699 {
1700     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1701     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1702     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1703     _data->_page->dragUpdated(&dragData, [[draggingInfo draggingPasteboard] name]);
1704     
1705     WebCore::DragSession dragSession = _data->_page->dragSession();
1706     NSInteger numberOfValidItemsForDrop = dragSession.numberOfItemsToBeAccepted;
1707     NSDraggingFormation draggingFormation = NSDraggingFormationNone;
1708     if (dragSession.mouseIsOverFileInput && numberOfValidItemsForDrop > 0)
1709         draggingFormation = NSDraggingFormationList;
1710
1711     if ([draggingInfo numberOfValidItemsForDrop] != numberOfValidItemsForDrop)
1712         [draggingInfo setNumberOfValidItemsForDrop:numberOfValidItemsForDrop];
1713     if ([draggingInfo draggingFormation] != draggingFormation)
1714         [draggingInfo setDraggingFormation:draggingFormation];
1715
1716     return dragSession.operation;
1717 }
1718
1719 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
1720 {
1721     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1722     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1723     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1724     _data->_page->dragExited(&dragData, [[draggingInfo draggingPasteboard] name]);
1725     _data->_page->resetDragOperation();
1726 }
1727
1728 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
1729 {
1730     return YES;
1731 }
1732
1733 // FIXME: This code is more or less copied from Pasteboard::getBestURL.
1734 // It would be nice to be able to share the code somehow.
1735 static bool maybeCreateSandboxExtensionFromPasteboard(NSPasteboard *pasteboard, SandboxExtension::Handle& sandboxExtensionHandle)
1736 {
1737     NSArray *types = [pasteboard types];
1738     if (![types containsObject:NSFilenamesPboardType])
1739         return false;
1740
1741     NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
1742     if ([files count] != 1)
1743         return false;
1744
1745     NSString *file = [files objectAtIndex:0];
1746     BOOL isDirectory;
1747     if (![[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory])
1748         return false;
1749
1750     if (isDirectory)
1751         return false;
1752
1753     SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle);
1754     return true;
1755 }
1756
1757 static void createSandboxExtensionsForFileUpload(NSPasteboard *pasteboard, SandboxExtension::HandleArray& handles)
1758 {
1759     NSArray *types = [pasteboard types];
1760     if (![types containsObject:NSFilenamesPboardType])
1761         return;
1762
1763     NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
1764     handles.allocate([files count]);
1765     for (unsigned i = 0; i < [files count]; i++) {
1766         NSString *file = [files objectAtIndex:i];
1767         if (![[NSFileManager defaultManager] fileExistsAtPath:file])
1768             continue;
1769         SandboxExtension::Handle handle;
1770         SandboxExtension::createHandle(file, SandboxExtension::ReadOnly, handles[i]);
1771     }
1772 }
1773
1774 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
1775 {
1776     IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]);
1777     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
1778     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
1779
1780     SandboxExtension::Handle sandboxExtensionHandle;
1781     bool createdExtension = maybeCreateSandboxExtensionFromPasteboard([draggingInfo draggingPasteboard], sandboxExtensionHandle);
1782     if (createdExtension)
1783         _data->_page->process()->willAcquireUniversalFileReadSandboxExtension();
1784
1785     SandboxExtension::HandleArray sandboxExtensionForUpload;
1786     createSandboxExtensionsForFileUpload([draggingInfo draggingPasteboard], sandboxExtensionForUpload);
1787
1788     _data->_page->performDrag(&dragData, [[draggingInfo draggingPasteboard] name], sandboxExtensionHandle, sandboxExtensionForUpload);
1789
1790     return YES;
1791 }
1792
1793 // This code is needed to support drag and drop when the drag types cannot be matched.
1794 // This is the case for elements that do not place content
1795 // in the drag pasteboard automatically when the drag start (i.e. dragging a DIV element).
1796 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
1797 {
1798     if ([[self superview] mouse:*point inRect:[self frame]])
1799         return self;
1800     return nil;
1801 }
1802 #endif // ENABLE(DRAG_SUPPORT)
1803
1804 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)loc
1805 {
1806     NSPoint localPoint = [self convertPoint:loc fromView:nil];
1807     NSRect visibleThumbRect = NSRect(_data->_page->visibleScrollerThumbRect());
1808     return NSMouseInRect(localPoint, visibleThumbRect, [self isFlipped]);
1809 }
1810
1811 - (void)_updateWindowVisibility
1812 {
1813     _data->_page->updateWindowIsVisible([[self window] isVisible]);
1814 }
1815
1816
1817 // FIXME: Use AppKit constants for these when they are available.
1818 static NSString * const windowDidChangeBackingPropertiesNotification = @"NSWindowDidChangeBackingPropertiesNotification";
1819 static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOldScaleFactorKey";
1820
1821 - (void)addWindowObserversForWindow:(NSWindow *)window
1822 {
1823     if (window) {
1824         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
1825                                                      name:NSWindowDidBecomeKeyNotification object:nil];
1826         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
1827                                                      name:NSWindowDidResignKeyNotification object:nil];
1828         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) 
1829                                                      name:NSWindowDidMiniaturizeNotification object:window];
1830         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
1831                                                      name:NSWindowDidDeminiaturizeNotification object:window];
1832         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMove:)
1833                                                      name:NSWindowDidMoveNotification object:window];
1834         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResize:) 
1835                                                      name:NSWindowDidResizeNotification object:window];
1836         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillOrderOffScreen:)
1837                                                      name:@"NSWindowWillOrderOffScreenNotification" object:window];
1838         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOffScreen:) 
1839                                                      name:@"NSWindowDidOrderOffScreenNotification" object:window];
1840         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOnScreen:) 
1841                                                      name:@"_NSWindowDidBecomeVisible" object:window];
1842         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeBackingProperties:)
1843                                                      name:windowDidChangeBackingPropertiesNotification object:window];
1844         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeScreen:)
1845                                                      name:NSWindowDidChangeScreenNotification object:window];
1846     }
1847 }
1848
1849 - (void)removeWindowObservers
1850 {
1851     NSWindow *window = [self window];
1852     if (!window)
1853         return;
1854
1855     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
1856     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
1857     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
1858     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
1859     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
1860     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
1861     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowWillOrderOffScreenNotification" object:window];
1862     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowDidOrderOffScreenNotification" object:window];
1863     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"_NSWindowDidBecomeVisible" object:window];
1864     [[NSNotificationCenter defaultCenter] removeObserver:self name:windowDidChangeBackingPropertiesNotification object:window];
1865     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeScreenNotification object:window];
1866 }
1867
1868 - (void)viewWillMoveToWindow:(NSWindow *)window
1869 {
1870     NSWindow *currentWindow = [self window];
1871     if (window == currentWindow)
1872         return;
1873
1874 #if __MAC_OS_X_VERSION_MIN_REQUIRED == 1070
1875     // Avoid calling the code added in 121482 that ensures that the undo stack is cleaned up
1876     // before the WKView is moved from one window to another when the WKView is being moved
1877     // out of a popover window. This avoids a bug in OS X 10.7 that was fixed in 10.8.
1878     // While this technically reopens a potentially crashing code path that 121482 closed,
1879     // it only reopens it for WKViews that are used for text editing and that are removed
1880     // from an NSPopover at some time earlier than tear-down of the NSPopover.
1881     if (![currentWindow isKindOfClass:NSClassFromString(@"_NSPopoverWindow")])
1882 #endif
1883         _data->_pageClient->viewWillMoveToAnotherWindow();
1884     
1885     [self removeWindowObservers];
1886     [self addWindowObserversForWindow:window];
1887     [self _disableWindowOcclusionNotifications];
1888 }
1889
1890 - (void)viewDidMoveToWindow
1891 {
1892     [self _enableWindowOcclusionNotifications];
1893
1894     // We want to make sure to update the active state while hidden, so if the view is about to become visible, we
1895     // update the active state first and then make it visible. If the view is about to be hidden, we hide it first and then
1896     // update the active state.
1897     if ([self window]) {
1898         _data->_windowHasValidBackingStore = NO;
1899         [self _updateWindowVisibility];
1900         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1901         _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible | WebPageProxy::ViewIsInWindow);
1902         [self _updateWindowAndViewFrames];
1903
1904         if (!_data->_flagsChangedEventMonitor) {
1905             _data->_flagsChangedEventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSFlagsChangedMask handler:^(NSEvent *flagsChangedEvent) {
1906                 [self _postFakeMouseMovedEventForFlagsChangedEvent:flagsChangedEvent];
1907                 return flagsChangedEvent;
1908             }];
1909         }
1910
1911         [self _accessibilityRegisterUIProcessTokens];
1912     } else {
1913         [self _updateWindowVisibility];
1914         _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1915         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive | WebPageProxy::ViewIsInWindow);
1916
1917         [NSEvent removeMonitor:_data->_flagsChangedEventMonitor];
1918         _data->_flagsChangedEventMonitor = nil;
1919
1920 #if ENABLE(GESTURE_EVENTS)
1921         if (_data->_endGestureMonitor) {
1922             [NSEvent removeMonitor:_data->_endGestureMonitor];
1923             _data->_endGestureMonitor = nil;
1924         }
1925 #endif
1926         WKHideWordDefinitionWindow();
1927     }
1928
1929     _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]);
1930 }
1931
1932 - (void)doWindowDidChangeScreen
1933 {
1934     _data->_page->windowScreenDidChange((PlatformDisplayID)[[[[[self window] screen] deviceDescription] objectForKey:@"NSScreenNumber"] intValue]);
1935 }
1936
1937 - (void)_windowDidBecomeKey:(NSNotification *)notification
1938 {
1939     NSWindow *keyWindow = [notification object];
1940     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet]) {
1941         [self _updateSecureInputState];
1942         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1943     }
1944
1945     // Send a change screen to make sure the initial displayID is set
1946     [self doWindowDidChangeScreen];
1947 }
1948
1949 - (void)_windowDidChangeScreen:(NSNotification *)notification
1950 {
1951     [self doWindowDidChangeScreen];
1952 }
1953
1954 - (void)_windowDidResignKey:(NSNotification *)notification
1955 {
1956     NSWindow *formerKeyWindow = [notification object];
1957     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) {
1958         [self _updateSecureInputState];
1959         _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
1960     }
1961 }
1962
1963 - (void)_windowDidMiniaturize:(NSNotification *)notification
1964 {
1965     _data->_windowHasValidBackingStore = NO;
1966
1967     [self _updateWindowVisibility];
1968 }
1969
1970 - (void)_windowDidDeminiaturize:(NSNotification *)notification
1971 {
1972     [self _updateWindowVisibility];
1973 }
1974
1975 - (void)_windowDidMove:(NSNotification *)notification
1976 {
1977     [self _updateWindowAndViewFrames];    
1978 }
1979
1980 - (void)_windowDidResize:(NSNotification *)notification
1981 {
1982     _data->_windowHasValidBackingStore = NO;
1983
1984     [self _updateWindowAndViewFrames];
1985 }
1986
1987 - (void)_windowWillOrderOffScreen:(NSNotification *)notification
1988 {
1989     [self _disableWindowOcclusionNotifications];
1990 }
1991
1992 - (void)_windowDidOrderOffScreen:(NSNotification *)notification
1993 {
1994     [self _updateWindowVisibility];
1995
1996     // We want to make sure to update the active state while hidden, so since the view is about to be hidden,
1997     // we hide it first and then update the active state.
1998     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
1999     _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
2000 }
2001
2002 - (void)_windowDidOrderOnScreen:(NSNotification *)notification
2003 {
2004     [self _updateWindowVisibility];
2005     [self _enableWindowOcclusionNotifications];
2006
2007     // We want to make sure to update the active state while hidden, so since the view is about to become visible,
2008     // we update the active state first and then make it visible.
2009     _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive);
2010     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
2011 }
2012
2013 - (void)_windowDidChangeBackingProperties:(NSNotification *)notification
2014 {
2015     CGFloat oldBackingScaleFactor = [[notification.userInfo objectForKey:backingPropertyOldScaleFactorKey] doubleValue];
2016     CGFloat newBackingScaleFactor = [self _intrinsicDeviceScaleFactor]; 
2017     if (oldBackingScaleFactor == newBackingScaleFactor)
2018         return; 
2019
2020     _data->_windowHasValidBackingStore = NO;
2021     _data->_page->setIntrinsicDeviceScaleFactor(newBackingScaleFactor);
2022 }
2023
2024 static void drawPageBackground(CGContextRef context, WebPageProxy* page, const IntRect& rect)
2025 {
2026     if (!page->drawsBackground())
2027         return;
2028
2029     CGContextSaveGState(context);
2030     CGContextSetBlendMode(context, kCGBlendModeCopy);
2031
2032     CGColorRef backgroundColor;
2033     if (page->drawsTransparentBackground())
2034         backgroundColor = CGColorGetConstantColor(kCGColorClear);
2035     else
2036         backgroundColor = CGColorGetConstantColor(kCGColorWhite);
2037
2038     CGContextSetFillColorWithColor(context, backgroundColor);
2039     CGContextFillRect(context, rect);
2040
2041     CGContextRestoreGState(context);
2042 }
2043
2044 - (void)drawRect:(NSRect)rect
2045 {
2046     LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
2047     _data->_page->endPrinting();
2048
2049     if ([self _shouldUseTiledDrawingArea]) {
2050         // Nothing to do here.
2051         return;
2052     }
2053
2054     CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
2055
2056     if (DrawingAreaProxyImpl* drawingArea = static_cast<DrawingAreaProxyImpl*>(_data->_page->drawingArea())) {
2057         const NSRect *rectsBeingDrawn;
2058         NSInteger numRectsBeingDrawn;
2059         [self getRectsBeingDrawn:&rectsBeingDrawn count:&numRectsBeingDrawn];
2060         for (NSInteger i = 0; i < numRectsBeingDrawn; ++i) {
2061             Region unpaintedRegion;
2062             drawingArea->paint(context, enclosingIntRect(rectsBeingDrawn[i]), unpaintedRegion);
2063
2064             // If the window doesn't have a valid backing store, we need to fill the parts of the page that we
2065             // didn't paint with the background color (white or clear), to avoid garbage in those areas.
2066             if (!_data->_windowHasValidBackingStore) {
2067                 Vector<IntRect> unpaintedRects = unpaintedRegion.rects();
2068                 for (size_t i = 0; i < unpaintedRects.size(); ++i)
2069                     drawPageBackground(context, _data->_page.get(), unpaintedRects[i]);
2070
2071                 _data->_windowHasValidBackingStore = YES;
2072             }
2073         }
2074     } else 
2075         drawPageBackground(context, _data->_page.get(), enclosingIntRect(rect));
2076
2077     _data->_page->didDraw();
2078 }
2079
2080 - (BOOL)isOpaque
2081 {
2082     return _data->_page->drawsBackground();
2083 }
2084
2085 - (BOOL)mouseDownCanMoveWindow
2086 {
2087     // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent,
2088     // but we don't want a drag in the NSView to move the window, even if it's transparent.
2089     return NO;
2090 }
2091
2092 - (void)viewDidHide
2093 {
2094     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
2095 }
2096
2097 - (void)viewDidUnhide
2098 {
2099     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
2100 }
2101
2102 - (void)viewDidChangeBackingProperties
2103 {
2104     NSColorSpace *colorSpace = [[self window] colorSpace];
2105     if ([colorSpace isEqualTo:_data->_colorSpace.get()])
2106         return;
2107
2108     _data->_colorSpace = nullptr;
2109     if (DrawingAreaProxy *drawingArea = _data->_page->drawingArea())
2110         drawingArea->colorSpaceDidChange();
2111 }
2112
2113 - (void)_accessibilityRegisterUIProcessTokens
2114 {
2115     // Initialize remote accessibility when the window connection has been established.
2116     NSData *remoteElementToken = WKAXRemoteTokenForElement(self);
2117     NSData *remoteWindowToken = WKAXRemoteTokenForElement([self accessibilityAttributeValue:NSAccessibilityWindowAttribute]);
2118     CoreIPC::DataReference elementToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteElementToken bytes]), [remoteElementToken length]);
2119     CoreIPC::DataReference windowToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteWindowToken bytes]), [remoteWindowToken length]);
2120     _data->_page->registerUIProcessAccessibilityTokens(elementToken, windowToken);
2121 }
2122
2123 - (void)_updateRemoteAccessibilityRegistration:(BOOL)registerProcess
2124 {
2125     // When the tree is connected/disconnected, the remote accessibility registration
2126     // needs to be updated with the pid of the remote process. If the process is going
2127     // away, that information is not present in WebProcess
2128     pid_t pid = 0;
2129     if (registerProcess && _data->_page->process())
2130         pid = _data->_page->process()->processIdentifier();
2131     else if (!registerProcess) {
2132         pid = WKAXRemoteProcessIdentifier(_data->_remoteAccessibilityChild.get());
2133         _data->_remoteAccessibilityChild = nil;
2134     }
2135     if (pid)
2136         WKAXRegisterRemoteProcess(registerProcess, pid); 
2137 }
2138
2139 - (id)accessibilityFocusedUIElement
2140 {
2141     if (_data->_pdfViewController)
2142         return NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView());
2143
2144     return _data->_remoteAccessibilityChild.get();
2145 }
2146
2147 - (BOOL)accessibilityIsIgnored
2148 {
2149     return NO;
2150 }
2151
2152 - (id)accessibilityHitTest:(NSPoint)point
2153 {
2154     if (_data->_pdfViewController)
2155         return [_data->_pdfViewController->pdfView() accessibilityHitTest:point];
2156     
2157     return _data->_remoteAccessibilityChild.get();
2158 }
2159
2160 - (id)accessibilityAttributeValue:(NSString*)attribute
2161 {
2162     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
2163
2164         id child = nil;
2165         if (_data->_pdfViewController)
2166             child = NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView());
2167         else if (_data->_remoteAccessibilityChild)
2168             child = _data->_remoteAccessibilityChild.get();
2169         
2170         if (!child)
2171             return nil;
2172         return [NSArray arrayWithObject:child];
2173     }
2174     if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
2175         return NSAccessibilityGroupRole;
2176     if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
2177         return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil);
2178     if ([attribute isEqualToString:NSAccessibilityParentAttribute])
2179         return NSAccessibilityUnignoredAncestor([self superview]);
2180     if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
2181         return [NSNumber numberWithBool:YES];
2182     
2183     return [super accessibilityAttributeValue:attribute];
2184 }
2185
2186 - (NSView *)hitTest:(NSPoint)point
2187 {
2188     NSView *hitView = [super hitTest:point];
2189     if (hitView && _data && hitView == _data->_layerHostingView)
2190         hitView = self;
2191
2192     return hitView;
2193 }
2194
2195 - (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent
2196 {
2197     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
2198         modifierFlags:[flagsChangedEvent modifierFlags] timestamp:[flagsChangedEvent timestamp] windowNumber:[flagsChangedEvent windowNumber]
2199         context:[flagsChangedEvent context] eventNumber:0 clickCount:0 pressure:0];
2200     NativeWebMouseEvent webEvent(fakeEvent, self);
2201     _data->_page->handleMouseEvent(webEvent);
2202 }
2203
2204 - (NSInteger)conversationIdentifier
2205 {
2206     return (NSInteger)self;
2207 }
2208
2209 - (float)_intrinsicDeviceScaleFactor
2210 {
2211     NSWindow *window = [self window];
2212     if (window)
2213         return [window backingScaleFactor];
2214     return [[NSScreen mainScreen] backingScaleFactor];
2215 }
2216
2217 - (void)_setDrawingAreaSize:(NSSize)size
2218 {
2219     if (!_data->_page->drawingArea())
2220         return;
2221     
2222     _data->_page->drawingArea()->setSize(IntSize(size), IntSize(_data->_resizeScrollOffset));
2223     _data->_resizeScrollOffset = NSZeroSize;
2224 }
2225
2226 - (BOOL)_shouldUseTiledDrawingArea
2227 {
2228     return NO;
2229 }
2230
2231 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
2232 - (void)quickLookWithEvent:(NSEvent *)event
2233 {
2234     NSPoint locationInViewCoordinates = [self convertPoint:[event locationInWindow] fromView:nil];
2235     _data->_page->performDictionaryLookupAtLocation(FloatPoint(locationInViewCoordinates.x, locationInViewCoordinates.y));
2236 }
2237 #endif
2238
2239 - (void)_setIsWindowOccluded:(BOOL)isWindowOccluded
2240 {
2241     if (_data->_isWindowOccluded == isWindowOccluded)
2242         return;
2243     
2244     _data->_isWindowOccluded = isWindowOccluded;
2245     _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible);
2246 }
2247
2248 - (void)_enableWindowOcclusionNotifications
2249 {
2250 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2251     NSWindow *window = [self window];
2252     if (!window)
2253         return;
2254
2255     NSInteger windowID = [window windowNumber];
2256     if (windowID <= 0)
2257         return;
2258
2259     if (![WKView _registerWindowOcclusionNotificationHandlers])
2260         return;
2261
2262     bool isWindowOccluded = false;
2263     if (!WKEnableWindowOcclusionNotifications(windowID, &isWindowOccluded)) {
2264         WTFLogAlways("Enabling window occlusion notifications for window %ld failed.\n", windowID);
2265         return;
2266     }
2267
2268     if (isWindowOccluded)
2269         [self _setIsWindowOccluded:YES];
2270 #endif
2271 }
2272
2273 - (void)_disableWindowOcclusionNotifications
2274 {
2275 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2276     [self _setIsWindowOccluded:NO];
2277
2278     // Occlusion notifications for a given window might also be used else where in the
2279     // application, hence unregister notification handlers instead.
2280     Vector<WKView *>& allViews = [WKView _allViews];
2281     if ((allViews.size() == 1) && (allViews[0] == self))
2282         [WKView _unregisterWindowOcclusionNotificationHandlers];
2283 #endif
2284 }
2285
2286 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2287
2288 static void windowBecameVisible(uint32_t, void* data, uint32_t dataLength, void*, uint32_t)
2289 {
2290     ASSERT(dataLength == sizeof(WKWindowID));
2291     NSInteger windowID = *(WKWindowID *)data;
2292
2293     Vector<WKView *>& allViews = [WKView _allViews];
2294     for (size_t i = 0, size = allViews.size(); i < size; ++i) {
2295         WKView *view = allViews[i];
2296         if ([[view window] windowNumber] == windowID)
2297             [view _setIsWindowOccluded:NO];
2298     }
2299 }
2300
2301 static void windowBecameOccluded(uint32_t, void* data, uint32_t dataLength, void*, uint32_t)
2302 {
2303     ASSERT(dataLength == sizeof(WKWindowID));
2304     NSInteger windowID = *(WKWindowID *)data;
2305
2306     Vector<WKView *>& allViews = [WKView _allViews];
2307     for (size_t i = 0, size = allViews.size(); i < size; ++i) {
2308         WKView *view = allViews[i];
2309         if ([[view window] windowNumber] == windowID)
2310             [view _setIsWindowOccluded:YES];
2311     }
2312 }
2313
2314 + (BOOL)_registerWindowOcclusionNotificationHandlers
2315 {
2316     // Disable window occlusion notifications for App Store until <rdar://problem/13255270> is resolved.
2317     static bool isAppStore = [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.appstore"];
2318     if (isAppStore)
2319         return NO;
2320
2321     if (windowOcclusionNotificationsAreRegistered)
2322         return YES;
2323
2324     if (!WKRegisterOcclusionNotificationHandler(WKOcclusionNotificationTypeWindowBecameVisible, windowBecameVisible)) {
2325         WTFLogAlways("Registeration of \"Window Became Visible\" notification handler failed.\n");
2326         return NO;
2327     }
2328     
2329     if (!WKRegisterOcclusionNotificationHandler(WKOcclusionNotificationTypeWindowBecameOccluded, windowBecameOccluded)) {
2330         WTFLogAlways("Registeration of \"Window Became Occluded\" notification handler failed.\n");
2331         return NO;
2332     }
2333
2334     windowOcclusionNotificationsAreRegistered = YES;
2335     return YES;
2336 }
2337
2338 + (BOOL)_unregisterWindowOcclusionNotificationHandlers
2339 {
2340     if (!windowOcclusionNotificationsAreRegistered)
2341         return YES;
2342
2343     if (!WKUnregisterOcclusionNotificationHandler(WKOcclusionNotificationTypeWindowBecameOccluded, windowBecameOccluded)) {
2344         WTFLogAlways("Unregisteration of \"Window Became Occluded\" notification handler failed.\n");
2345         return NO;
2346     }
2347
2348     if (!WKUnregisterOcclusionNotificationHandler(WKOcclusionNotificationTypeWindowBecameVisible, windowBecameVisible)) {
2349         WTFLogAlways("Unregisteration of \"Window Became Visible\" notification handler failed.\n");
2350         return NO;
2351     }
2352
2353     windowOcclusionNotificationsAreRegistered = NO;
2354     return YES;
2355 }
2356 #endif
2357
2358 + (Vector<WKView *>&)_allViews
2359 {
2360     DEFINE_STATIC_LOCAL(Vector<WKView *>, vector, ());
2361     return vector;
2362 }
2363
2364 @end
2365
2366 @implementation WKView (Internal)
2367
2368 - (PassOwnPtr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy
2369 {
2370 #if ENABLE(THREADED_SCROLLING)
2371     if ([self _shouldUseTiledDrawingArea]) {
2372         if (getenv("WK_USE_REMOTE_LAYER_TREE_DRAWING_AREA"))
2373             return RemoteLayerTreeDrawingAreaProxy::create(_data->_page.get());
2374
2375         return TiledCoreAnimationDrawingAreaProxy::create(_data->_page.get());
2376     }
2377 #endif
2378
2379     return DrawingAreaProxyImpl::create(_data->_page.get());
2380 }
2381
2382 - (BOOL)_isFocused
2383 {
2384     if (_data->_inBecomeFirstResponder)
2385         return YES;
2386     if (_data->_inResignFirstResponder)
2387         return NO;
2388     return [[self window] firstResponder] == self;
2389 }
2390
2391 - (WebKit::ColorSpaceData)_colorSpace
2392 {
2393     if (!_data->_colorSpace) {
2394         if ([self window])
2395             _data->_colorSpace = [[self window] colorSpace];
2396         else
2397             _data->_colorSpace = [[NSScreen mainScreen] colorSpace];
2398     }
2399         
2400     ColorSpaceData colorSpaceData;
2401     colorSpaceData.cgColorSpace = [_data->_colorSpace.get() CGColorSpace];
2402
2403     return colorSpaceData;    
2404 }
2405
2406 - (void)_processDidCrash
2407 {
2408     if (_data->_layerHostingView)
2409         [self _setAcceleratedCompositingModeRootLayer:nil];
2410
2411     [self _updateRemoteAccessibilityRegistration:NO];
2412 }
2413
2414 - (void)_pageClosed
2415 {
2416     [self _updateRemoteAccessibilityRegistration:NO];
2417 }
2418
2419 - (void)_didRelaunchProcess
2420 {
2421     [self _accessibilityRegisterUIProcessTokens];
2422 }
2423
2424 - (void)_setCursor:(NSCursor *)cursor
2425 {
2426     if ([NSCursor currentCursor] == cursor)
2427         return;
2428     [cursor set];
2429 }
2430
2431 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
2432 {
2433     ValidationVector items = _data->_validationMap.take(commandName);
2434     size_t size = items.size();
2435     for (size_t i = 0; i < size; ++i) {
2436         ValidationItem item = items[i].get();
2437         [menuItem(item) setState:newState];
2438         [menuItem(item) setEnabled:isEnabled];
2439         [toolbarItem(item) setEnabled:isEnabled];
2440         // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
2441     }
2442 }
2443
2444 - (BOOL)_tryPostProcessPluginComplexTextInputKeyDown:(NSEvent *)event
2445 {
2446     if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled)
2447         return NO;
2448
2449     // In the legacy text input model, the event has already been sent to the input method.
2450     if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy)
2451         return NO;
2452
2453     return [self _handlePluginComplexTextInputKeyDown:event];
2454 }
2455
2456 - (void)_doneWithKeyEvent:(NSEvent *)event eventWasHandled:(BOOL)eventWasHandled
2457 {
2458     if ([event type] != NSKeyDown)
2459         return;
2460
2461     if ([self _tryPostProcessPluginComplexTextInputKeyDown:event])
2462         return;
2463     
2464     if (eventWasHandled) {
2465         [NSCursor setHiddenUntilMouseMoves:YES];
2466         return;
2467     }
2468
2469     // resending the event may destroy this WKView
2470     RetainPtr<WKView> protector(self);
2471
2472     ASSERT(!_data->_keyDownEventBeingResent);
2473     _data->_keyDownEventBeingResent = event;
2474     [NSApp _setCurrentEvent:event];
2475     [NSApp sendEvent:event];
2476
2477     _data->_keyDownEventBeingResent = nullptr;
2478 }
2479
2480 - (BOOL)_interpretKeyEvent:(NSEvent *)event savingCommandsTo:(Vector<WebCore::KeypressCommand>&)commands
2481 {
2482     ASSERT(!_data->_interpretKeyEventsParameters);
2483     ASSERT(commands.isEmpty());
2484
2485     if ([event type] == NSFlagsChanged)
2486         return NO;
2487
2488     WKViewInterpretKeyEventsParameters parameters;
2489     parameters.eventInterpretationHadSideEffects = false;
2490     parameters.executingSavedKeypressCommands = false;
2491     // We assume that an input method has consumed the event, and only change this assumption if one of the NSTextInput methods is called.
2492     // We assume the IM will *not* consume hotkey sequences.
2493     parameters.consumedByIM = !([event modifierFlags] & NSCommandKeyMask);
2494     parameters.commands = &commands;
2495     _data->_interpretKeyEventsParameters = &parameters;
2496
2497     LOG(TextInput, "-> interpretKeyEvents:%p %@", event, event);
2498     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2499
2500     _data->_interpretKeyEventsParameters = 0;
2501
2502     // An input method may consume an event and not tell us (e.g. when displaying a candidate window),
2503     // in which case we should not bubble the event up the DOM.
2504     if (parameters.consumedByIM) {
2505         LOG(TextInput, "...event %p was consumed by an input method", event);
2506         return YES;
2507     }
2508
2509     LOG(TextInput, "...interpretKeyEvents for event %p done, returns %d", event, parameters.eventInterpretationHadSideEffects);
2510
2511     // 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.
2512     return parameters.eventInterpretationHadSideEffects;
2513 }
2514
2515 - (NSRect)_convertToDeviceSpace:(NSRect)rect
2516 {
2517     return toDeviceSpace(rect, [self window]);
2518 }
2519
2520 - (NSRect)_convertToUserSpace:(NSRect)rect
2521 {
2522     return toUserSpace(rect, [self window]);
2523 }
2524
2525 // Any non-zero value will do, but using something recognizable might help us debug some day.
2526 #define TRACKING_RECT_TAG 0xBADFACE
2527
2528 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
2529 {
2530     ASSERT(_data->_trackingRectOwner == nil);
2531     _data->_trackingRectOwner = owner;
2532     _data->_trackingRectUserData = data;
2533     return TRACKING_RECT_TAG;
2534 }
2535
2536 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
2537 {
2538     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
2539     ASSERT(_data->_trackingRectOwner == nil);
2540     _data->_trackingRectOwner = owner;
2541     _data->_trackingRectUserData = data;
2542     return TRACKING_RECT_TAG;
2543 }
2544
2545 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
2546 {
2547     ASSERT(count == 1);
2548     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
2549     ASSERT(_data->_trackingRectOwner == nil);
2550     _data->_trackingRectOwner = owner;
2551     _data->_trackingRectUserData = userDataList[0];
2552     trackingNums[0] = TRACKING_RECT_TAG;
2553 }
2554
2555 - (void)removeTrackingRect:(NSTrackingRectTag)tag
2556 {
2557     if (!_data)
2558         return;
2559
2560     if (tag == 0)
2561         return;
2562     
2563     if (tag == TRACKING_RECT_TAG) {
2564         _data->_trackingRectOwner = nil;
2565         return;
2566     }
2567     
2568     if (tag == _data->_lastToolTipTag) {
2569         [super removeTrackingRect:tag];
2570         _data->_lastToolTipTag = 0;
2571         return;
2572     }
2573
2574     // If any other tracking rect is being removed, we don't know how it was created
2575     // and it's possible there's a leak involved (see 3500217)
2576     ASSERT_NOT_REACHED();
2577 }
2578
2579 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
2580 {
2581     int i;
2582     for (i = 0; i < count; ++i) {
2583         int tag = tags[i];
2584         if (tag == 0)
2585             continue;
2586         ASSERT(tag == TRACKING_RECT_TAG);
2587         if (_data != nil) {
2588             _data->_trackingRectOwner = nil;
2589         }
2590     }
2591 }
2592
2593 - (void)_sendToolTipMouseExited
2594 {
2595     // Nothing matters except window, trackingNumber, and userData.
2596     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
2597         location:NSMakePoint(0, 0)
2598         modifierFlags:0
2599         timestamp:0
2600         windowNumber:[[self window] windowNumber]
2601         context:NULL
2602         eventNumber:0
2603         trackingNumber:TRACKING_RECT_TAG
2604         userData:_data->_trackingRectUserData];
2605     [_data->_trackingRectOwner mouseExited:fakeEvent];
2606 }
2607
2608 - (void)_sendToolTipMouseEntered
2609 {
2610     // Nothing matters except window, trackingNumber, and userData.
2611     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
2612         location:NSMakePoint(0, 0)
2613         modifierFlags:0
2614         timestamp:0
2615         windowNumber:[[self window] windowNumber]
2616         context:NULL
2617         eventNumber:0
2618         trackingNumber:TRACKING_RECT_TAG
2619         userData:_data->_trackingRectUserData];
2620     [_data->_trackingRectOwner mouseEntered:fakeEvent];
2621 }
2622
2623 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
2624 {
2625     return nsStringFromWebCoreString(_data->_page->toolTip());
2626 }
2627
2628 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
2629 {
2630     if (oldToolTip)
2631         [self _sendToolTipMouseExited];
2632
2633     if (newToolTip && [newToolTip length] > 0) {
2634         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
2635         [self removeAllToolTips];
2636         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
2637         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
2638         [self _sendToolTipMouseEntered];
2639     }
2640 }
2641
2642 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut animate:(BOOL)animate
2643 {
2644     if (!findIndicator) {
2645         _data->_findIndicatorWindow = nullptr;
2646         return;
2647     }
2648
2649     if (!_data->_findIndicatorWindow)
2650         _data->_findIndicatorWindow = FindIndicatorWindow::create(self);
2651
2652     _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut, animate);
2653 }
2654
2655
2656 - (void)_setAcceleratedCompositingModeRootLayer:(CALayer *)rootLayer
2657 {
2658     [CATransaction begin];
2659     [CATransaction setDisableActions:YES];
2660
2661     if (rootLayer) {
2662         if (!_data->_layerHostingView) {
2663             // Create an NSView that will host our layer tree.
2664             _data->_layerHostingView.adoptNS([[WKFlippedView alloc] initWithFrame:[self bounds]]);
2665             [_data->_layerHostingView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
2666
2667
2668             [self addSubview:_data->_layerHostingView.get() positioned:NSWindowBelow relativeTo:nil];
2669
2670             // Create a root layer that will back the NSView.
2671             RetainPtr<CALayer> layer = adoptNS([[CALayer alloc] init]);
2672 #ifndef NDEBUG
2673             [layer setName:@"Hosting root layer"];
2674 #endif
2675
2676             [_data->_layerHostingView setLayer:layer.get()];
2677             [_data->_layerHostingView setWantsLayer:YES];
2678         }
2679
2680         [_data->_layerHostingView layer].sublayers = [NSArray arrayWithObject:rootLayer];
2681     } else {
2682         if (_data->_layerHostingView) {
2683             [_data->_layerHostingView removeFromSuperview];
2684             [_data->_layerHostingView setLayer:nil];
2685             [_data->_layerHostingView setWantsLayer:NO];
2686
2687             _data->_layerHostingView = nullptr;
2688         }
2689     }
2690
2691     [CATransaction commit];
2692 }
2693
2694 - (void)_setAccessibilityWebProcessToken:(NSData *)data
2695 {
2696     _data->_remoteAccessibilityChild = WKAXRemoteElementForToken(data);
2697     [self _updateRemoteAccessibilityRegistration:YES];
2698 }
2699
2700 - (void)_pluginFocusOrWindowFocusChanged:(BOOL)pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
2701 {
2702     BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
2703
2704     if (pluginHasFocusAndWindowHasFocus) {
2705         // Check if we're already allowing text input for this plug-in.
2706         if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
2707             return;
2708
2709         _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
2710
2711     } else {
2712         // Check if we got a request to unfocus a plug-in that isn't focused.
2713         if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
2714             return;
2715
2716         _data->_pluginComplexTextInputIdentifier = 0;
2717     }
2718
2719     if (inputSourceChanged) {
2720         // The input source changed, go ahead and discard any entered text.
2721         [[WKTextInputWindowController sharedTextInputWindowController] unmarkText];
2722     }
2723
2724     // This will force the current input context to be updated to its correct value.
2725     [NSApp updateWindows];
2726 }
2727
2728 - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
2729 {
2730     if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier) {
2731         // We're asked to update the state for a plug-in that doesn't have focus.
2732         return;
2733     }
2734
2735     [self _setPluginComplexTextInputState:pluginComplexTextInputState];
2736 }
2737
2738 - (void)_setPageHasCustomRepresentation:(BOOL)pageHasCustomRepresentation
2739 {
2740     bool hadPDFView = _data->_pdfViewController;
2741     _data->_pdfViewController = nullptr;
2742
2743     if (pageHasCustomRepresentation)
2744         _data->_pdfViewController = PDFViewController::create(self);
2745
2746     if (pageHasCustomRepresentation != hadPDFView)
2747         _data->_page->drawingArea()->pageCustomRepresentationChanged();
2748 }
2749
2750 - (void)_didFinishLoadingDataForCustomRepresentationWithSuggestedFilename:(const String&)suggestedFilename dataReference:(const CoreIPC::DataReference&)dataReference
2751 {
2752     ASSERT(_data->_pdfViewController);
2753
2754     _data->_pdfViewController->setPDFDocumentData(_data->_page->mainFrame()->mimeType(), suggestedFilename, dataReference);
2755 }
2756
2757 - (double)_customRepresentationZoomFactor
2758 {
2759     if (!_data->_pdfViewController)
2760         return 1;
2761
2762     return _data->_pdfViewController->zoomFactor();
2763 }
2764
2765 - (void)_setCustomRepresentationZoomFactor:(double)zoomFactor
2766 {
2767     if (!_data->_pdfViewController)
2768         return;
2769
2770     _data->_pdfViewController->setZoomFactor(zoomFactor);
2771 }
2772
2773 - (void)_findStringInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count
2774 {
2775     if (!_data->_pdfViewController)
2776         return;
2777
2778     _data->_pdfViewController->findString(string, options, count);
2779 }
2780
2781 - (void)_countStringMatchesInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count
2782 {
2783     if (!_data->_pdfViewController)
2784         return;
2785
2786     _data->_pdfViewController->countStringMatches(string, options, count);
2787 }
2788
2789 - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag
2790 {
2791     IntSize size([image size]);
2792     size.scale(1.0 / _data->_page->deviceScaleFactor());
2793     [image setSize:size];
2794     
2795     // The call to super could release this WKView.
2796     RetainPtr<WKView> protector(self);
2797     
2798     [super dragImage:image
2799                   at:clientPoint
2800               offset:NSZeroSize
2801                event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent
2802           pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
2803               source:self
2804            slideBack:YES];
2805 }
2806
2807 static bool matchesExtensionOrEquivalent(NSString *filename, NSString *extension)
2808 {
2809     NSString *extensionAsSuffix = [@"." stringByAppendingString:extension];
2810     return hasCaseInsensitiveSuffix(filename, extensionAsSuffix) || (stringIsCaseInsensitiveEqualToString(extension, @"jpeg")
2811                                                                      && hasCaseInsensitiveSuffix(filename, @".jpg"));
2812 }
2813
2814 - (void)_setPromisedData:(WebCore::Image *)image withFileName:(NSString *)filename withExtension:(NSString *)extension withTitle:(NSString *)title withURL:(NSString *)url withVisibleURL:(NSString *)visibleUrl withArchive:(WebCore::SharedBuffer*) archiveBuffer forPasteboard:(NSString *)pasteboardName
2815
2816 {
2817     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName];
2818     RetainPtr<NSMutableArray> types(AdoptNS, [[NSMutableArray alloc] initWithObjects:NSFilesPromisePboardType, nil]);
2819     
2820     [types.get() addObjectsFromArray:archiveBuffer ? PasteboardTypes::forImagesWithArchive() : PasteboardTypes::forImages()];
2821     [pasteboard declareTypes:types.get() owner:self];
2822     if (!matchesExtensionOrEquivalent(filename, extension))
2823         filename = [[filename stringByAppendingString:@"."] stringByAppendingString:extension];
2824
2825     [pasteboard setString:visibleUrl forType:NSStringPboardType];
2826     [pasteboard setString:visibleUrl forType:PasteboardTypes::WebURLPboardType];
2827     [pasteboard setString:title forType:PasteboardTypes::WebURLNamePboardType];
2828     [pasteboard setPropertyList:[NSArray arrayWithObjects:[NSArray arrayWithObject:visibleUrl], [NSArray arrayWithObject:title], nil] forType:PasteboardTypes::WebURLsWithTitlesPboardType];
2829     [pasteboard setPropertyList:[NSArray arrayWithObject:extension] forType:NSFilesPromisePboardType];
2830
2831     if (archiveBuffer)
2832         [pasteboard setData:[archiveBuffer->createNSData() autorelease] forType:PasteboardTypes::WebArchivePboardType];
2833
2834     _data->_promisedImage = image;
2835     _data->_promisedFilename = filename;
2836     _data->_promisedURL = url;
2837 }
2838
2839 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
2840 {
2841     _data->_promisedImage = 0;
2842     _data->_promisedFilename = "";
2843     _data->_promisedURL = "";
2844 }
2845
2846 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
2847 {
2848     // FIXME: need to support NSRTFDPboardType
2849
2850     if ([type isEqual:NSTIFFPboardType] && _data->_promisedImage) {
2851         [pasteboard setData:(NSData *)_data->_promisedImage->getTIFFRepresentation() forType:NSTIFFPboardType];
2852         _data->_promisedImage = 0;
2853     }
2854 }
2855
2856 static BOOL fileExists(NSString *path)
2857 {
2858     struct stat statBuffer;
2859     return !lstat([path fileSystemRepresentation], &statBuffer);
2860 }
2861
2862 static NSString *pathWithUniqueFilenameForPath(NSString *path)
2863 {
2864     // "Fix" the filename of the path.
2865     NSString *filename = filenameByFixingIllegalCharacters([path lastPathComponent]);
2866     path = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:filename];
2867     
2868     if (fileExists(path)) {
2869         // Don't overwrite existing file by appending "-n", "-n.ext" or "-n.ext.ext" to the filename.
2870         NSString *extensions = nil;
2871         NSString *pathWithoutExtensions;
2872         NSString *lastPathComponent = [path lastPathComponent];
2873         NSRange periodRange = [lastPathComponent rangeOfString:@"."];
2874         
2875         if (periodRange.location == NSNotFound) {
2876             pathWithoutExtensions = path;
2877         } else {
2878             extensions = [lastPathComponent substringFromIndex:periodRange.location + 1];
2879             lastPathComponent = [lastPathComponent substringToIndex:periodRange.location];
2880             pathWithoutExtensions = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:lastPathComponent];
2881         }
2882         
2883         for (unsigned i = 1; ; i++) {
2884             NSString *pathWithAppendedNumber = [NSString stringWithFormat:@"%@-%d", pathWithoutExtensions, i];
2885             path = [extensions length] ? [pathWithAppendedNumber stringByAppendingPathExtension:extensions] : pathWithAppendedNumber;
2886             if (!fileExists(path))
2887                 break;
2888         }
2889     }
2890     
2891     return path;
2892 }
2893
2894 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2895 {
2896     RetainPtr<NSFileWrapper> wrapper;
2897     RetainPtr<NSData> data;
2898     
2899     if (_data->_promisedImage) {
2900         data.adoptNS(_data->_promisedImage->data()->createNSData());
2901         wrapper.adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:data.get()]);
2902         [wrapper.get() setPreferredFilename:_data->_promisedFilename];
2903     }
2904     
2905     if (!wrapper) {
2906         LOG_ERROR("Failed to create image file.");
2907         return nil;
2908     }
2909     
2910     // FIXME: Report an error if we fail to create a file.
2911     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper.get() preferredFilename]];
2912     path = pathWithUniqueFilenameForPath(path);
2913     if (![wrapper.get() writeToFile:path atomically:NO updateFilenames:YES])
2914         LOG_ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2915     
2916     if (!_data->_promisedURL.isEmpty())
2917         WebCore::setMetadataURL(_data->_promisedURL, "", String(path));
2918     
2919     return [NSArray arrayWithObject:[path lastPathComponent]];
2920 }
2921
2922 - (void)_updateSecureInputState
2923 {
2924     if (![[self window] isKeyWindow] || ![self _isFocused]) {
2925         if (_data->_inSecureInputState) {
2926             DisableSecureEventInput();
2927             _data->_inSecureInputState = NO;
2928         }
2929         return;
2930     }
2931     // WKView has a single input context for all editable areas (except for plug-ins).
2932     NSTextInputContext *context = [super inputContext];
2933     bool isInPasswordField = _data->_page->editorState().isInPasswordField;
2934
2935     if (isInPasswordField) {
2936         if (!_data->_inSecureInputState)
2937             EnableSecureEventInput();
2938         static NSArray *romanInputSources = [[NSArray alloc] initWithObjects:&NSAllRomanInputSourcesLocaleIdentifier count:1];
2939         LOG(TextInput, "-> setAllowedInputSourceLocales:romanInputSources");
2940         [context setAllowedInputSourceLocales:romanInputSources];
2941     } else {
2942         if (_data->_inSecureInputState)
2943             DisableSecureEventInput();
2944         LOG(TextInput, "-> setAllowedInputSourceLocales:nil");
2945         [context setAllowedInputSourceLocales:nil];
2946     }
2947     _data->_inSecureInputState = isInPasswordField;
2948 }
2949
2950 - (void)_updateTextInputStateIncludingSecureInputState:(BOOL)updateSecureInputState
2951 {
2952     const EditorState& editorState = _data->_page->editorState();
2953     if (updateSecureInputState) {
2954         // This is a temporary state when editing. Flipping secure input state too quickly can expose race conditions.
2955         if (!editorState.selectionIsNone)
2956             [self _updateSecureInputState];
2957     }
2958
2959     if (!editorState.hasComposition || editorState.shouldIgnoreCompositionSelectionChange)
2960         return;
2961
2962     _data->_page->cancelComposition();
2963
2964     [self _notifyInputContextAboutDiscardedComposition];
2965 }
2966
2967 - (void)_resetTextInputState
2968 {
2969     [self _notifyInputContextAboutDiscardedComposition];
2970
2971     if (_data->_inSecureInputState) {
2972         DisableSecureEventInput();
2973         _data->_inSecureInputState = NO;
2974     }
2975 }
2976
2977 #if ENABLE(FULLSCREEN_API)
2978 - (BOOL)hasFullScreenWindowController
2979 {
2980     return (bool)_data->_fullScreenWindowController;
2981 }
2982
2983 - (WKFullScreenWindowController*)fullScreenWindowController
2984 {
2985     if (!_data->_fullScreenWindowController) {
2986         _data->_fullScreenWindowController.adoptNS([[WKFullScreenWindowController alloc] init]);
2987         [_data->_fullScreenWindowController.get() setWebView:self];
2988     }
2989     return _data->_fullScreenWindowController.get();
2990 }
2991
2992 - (void)closeFullScreenWindowController
2993 {
2994     if (!_data->_fullScreenWindowController)
2995         return;
2996     [_data->_fullScreenWindowController.get() close];
2997     _data->_fullScreenWindowController = nullptr;
2998 }
2999 #endif
3000
3001 - (bool)_executeSavedCommandBySelector:(SEL)selector
3002 {
3003     // The sink does two things: 1) Tells us if the responder went unhandled, and
3004     // 2) prevents any NSBeep; we don't ever want to beep here.
3005     RetainPtr<WKResponderChainSink> sink(AdoptNS, [[WKResponderChainSink alloc] initWithResponderChain:self]);
3006     [super doCommandBySelector:selector];
3007     [sink.get() detach];
3008     return ![sink.get() didReceiveUnhandledCommand];
3009 }
3010
3011 - (void)_setIntrinsicContentSize:(NSSize)intrinsicContentSize
3012 {
3013     // If the intrinsic content size is less than the minimum layout width, the content flowed to fit,
3014     // so we can report that that dimension is flexible. If not, we need to report our intrinsic width
3015     // so that autolayout will know to provide space for us.
3016
3017     NSSize intrinsicContentSizeAcknowledgingFlexibleWidth = intrinsicContentSize;
3018     if (intrinsicContentSize.width < _data->_page->minimumLayoutWidth())
3019         intrinsicContentSizeAcknowledgingFlexibleWidth.width = NSViewNoInstrinsicMetric;
3020
3021     _data->_intrinsicContentSize = intrinsicContentSizeAcknowledgingFlexibleWidth;
3022     [self invalidateIntrinsicContentSize];
3023 }
3024
3025 - (void)_cacheWindowBottomCornerRect
3026 {
3027     // FIXME: We should remove this code when <rdar://problem/9362085> is resolved.
3028     NSWindow *window = [self window];
3029     if (!window)
3030         return;
3031
3032     _data->_windowBottomCornerIntersectionRect = [window _intersectBottomCornersWithRect:[self convertRect:[self visibleRect] toView:nil]];
3033     if (!NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect))
3034         [self setNeedsDisplayInRect:[self convertRect:_data->_windowBottomCornerIntersectionRect fromView:nil]];
3035 }
3036
3037 - (NSInteger)spellCheckerDocumentTag
3038 {
3039     if (!_data->_hasSpellCheckerDocumentTag) {
3040         _data->_spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
3041         _data->_hasSpellCheckerDocumentTag = YES;
3042     }
3043     return _data->_spellCheckerDocumentTag;
3044 }
3045
3046 - (void)handleAcceptedAlternativeText:(NSString*)text
3047 {
3048     _data->_page->handleAlternativeTextUIResult(text);
3049 }
3050
3051 - (void)_setSuppressVisibilityUpdates:(BOOL)suppressVisibilityUpdates
3052 {
3053     _data->_page->setSuppressVisibilityUpdates(suppressVisibilityUpdates);
3054 }
3055
3056 - (BOOL)_suppressVisibilityUpdates
3057 {
3058     return _data->_page->suppressVisibilityUpdates();
3059 }
3060
3061 - (BOOL)_isWindowOccluded
3062 {
3063     return _data->_isWindowOccluded;
3064 }
3065
3066 @end
3067
3068 @implementation WKView (Private)
3069
3070 - (void)_registerDraggedTypes
3071 {
3072     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:PasteboardTypes::forEditing()];
3073     [types addObjectsFromArray:PasteboardTypes::forURL()];
3074     [self registerForDraggedTypes:[types allObjects]];
3075     [types release];
3076 }
3077
3078 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef
3079 {
3080     return [self initWithFrame:frame contextRef:contextRef pageGroupRef:pageGroupRef relatedToPage:nil];
3081 }
3082
3083 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef relatedToPage:(WKPageRef)relatedPage
3084 {
3085     self = [super initWithFrame:frame];
3086     if (!self)
3087         return nil;
3088
3089     [NSApp registerServicesMenuSendTypes:PasteboardTypes::forSelection() returnTypes:PasteboardTypes::forEditing()];
3090
3091     InitWebCoreSystemInterface();
3092     RunLoop::initializeMainRunLoop();
3093
3094     // Legacy style scrollbars have design details that rely on tracking the mouse all the time.
3095     NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect;
3096     if (WKRecommendedScrollerStyle() == NSScrollerStyleLegacy)
3097         options |= NSTrackingActiveAlways;
3098     else
3099         options |= NSTrackingActiveInKeyWindow;
3100
3101     NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame
3102                                                                 options:options
3103                                                                   owner:self
3104                                                                userInfo:nil];
3105     [self addTrackingArea:trackingArea];
3106     [trackingArea release];
3107
3108     _data = [[WKViewData alloc] init];
3109
3110     _data->_pageClient = PageClientImpl::create(self);
3111     _data->_page = toImpl(contextRef)->createWebPage(_data->_pageClient.get(), toImpl(pageGroupRef), toImpl(relatedPage));
3112     _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]);
3113     _data->_page->initializeWebPage();
3114 #if ENABLE(FULLSCREEN_API)
3115     _data->_page->fullScreenManager()->setWebView(self);
3116 #endif
3117     _data->_mouseDownEvent = nil;
3118     _data->_ignoringMouseDraggedEvents = NO;
3119     _data->_expandsToFitContentViaAutoLayout = NO;
3120
3121     _data->_intrinsicContentSize = NSMakeSize(NSViewNoInstrinsicMetric, NSViewNoInstrinsicMetric);
3122
3123     [self _registerDraggedTypes];
3124
3125     if ([self _shouldUseTiledDrawingArea]) {
3126         self.wantsLayer = YES;
3127
3128         // Explicitly set the layer contents placement so AppKit will make sure that our layer has masksToBounds set to YES.
3129         self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft;
3130     }
3131
3132     [WKView _allViews].append(self);
3133
3134     WebContext::statistics().wkViewCount++;
3135
3136     return self;
3137 }
3138
3139 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
3140 - (BOOL)wantsUpdateLayer
3141 {
3142     return [self _shouldUseTiledDrawingArea];
3143 }
3144
3145 - (void)updateLayer
3146 {
3147     if ([self drawsBackground] && ![self drawsTransparentBackground])
3148         self.layer.backgroundColor = CGColorGetConstantColor(kCGColorWhite);
3149     else
3150         self.layer.backgroundColor = CGColorGetConstantColor(kCGColorClear);
3151
3152     if (DrawingAreaProxy* drawingArea = _data->_page->drawingArea())
3153         drawingArea->waitForPossibleGeometryUpdate();
3154 }
3155 #endif
3156
3157 - (WKPageRef)pageRef
3158 {
3159     return toAPI(_data->_page.get());
3160 }
3161
3162 - (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef
3163 {
3164     // PDF documents are already paginated, so we can't change them to add headers and footers.
3165     return !toImpl(frameRef)->isDisplayingPDFDocument();
3166 }
3167
3168 - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef
3169 {
3170     LOG(View, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data());
3171
3172     // Only the top frame can currently contain a PDF view.
3173     if (_data->_pdfViewController) {
3174         if (!toImpl(frameRef)->isMainFrame())
3175             return 0;
3176         return _data->_pdfViewController->makePrintOperation(printInfo);
3177     } else {
3178         // FIXME: If the frame cannot be printed (e.g. if it contains an encrypted PDF that disallows
3179         // printing), this function should return nil.
3180         RetainPtr<WKPrintingView> printingView(AdoptNS, [[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef) view:self]);
3181         // NSPrintOperation takes ownership of the view.
3182         NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get()];
3183         [printOperation setCanSpawnSeparateThread:YES];
3184         [printOperation setJobTitle:toImpl(frameRef)->title()];
3185         printingView->_printOperation = printOperation;
3186         return printOperation;
3187     }
3188 }
3189
3190 - (void)setFrame:(NSRect)rect andScrollBy:(NSSize)offset
3191 {
3192     ASSERT(NSEqualSizes(_data->_resizeScrollOffset, NSZeroSize));
3193
3194     _data->_resizeScrollOffset = offset;
3195     [self setFrame:rect];
3196 }
3197
3198 - (void)disableFrameSizeUpdates
3199 {
3200     _data->_frameSizeUpdatesDisabledCount++;
3201 }
3202
3203 - (void)enableFrameSizeUpdates
3204 {
3205     if (!_data->_frameSizeUpdatesDisabledCount)
3206         return;
3207     
3208     if (!(--_data->_frameSizeUpdatesDisabledCount)) {
3209         if (_data->_expandsToFitContentViaAutoLayout)
3210             _data->_page->viewExposedRectChanged([self visibleRect]);
3211         [self _setDrawingAreaSize:[self frame].size];
3212     }
3213 }
3214
3215 - (BOOL)frameSizeUpdatesDisabled
3216 {
3217     return _data->_frameSizeUpdatesDisabledCount > 0;
3218 }
3219
3220 - (void)performDictionaryLookupAtCurrentMouseLocation
3221 {
3222     NSPoint thePoint = [NSEvent mouseLocation];
3223     thePoint = [[self window] convertScreenToBase:thePoint];
3224     thePoint = [self convertPoint:thePoint fromView:nil];
3225
3226     _data->_page->performDictionaryLookupAtLocation(FloatPoint(thePoint.x, thePoint.y));
3227 }
3228
3229 + (void)hideWordDefinitionWindow
3230 {
3231     WKHideWordDefinitionWindow();
3232 }
3233
3234 - (CGFloat)minimumLayoutWidth
3235 {
3236     static BOOL loggedDeprecationWarning = NO;
3237
3238     if (!loggedDeprecationWarning) {
3239         NSLog(@"Please use minimumWidthForAutoLayout instead of minimumLayoutWidth.");
3240         loggedDeprecationWarning = YES;
3241     }
3242
3243     return _data->_page->minimumLayoutWidth();
3244 }
3245
3246 - (void)setMinimumLayoutWidth:(CGFloat)minimumLayoutWidth
3247 {
3248     static BOOL loggedDeprecationWarning = NO;
3249
3250     if (!loggedDeprecationWarning) {
3251         NSLog(@"Please use minimumWidthForAutoLayout instead of minimumLayoutWidth.");
3252         loggedDeprecationWarning = YES;
3253     }
3254
3255     [self setMinimumWidthForAutoLayout:minimumLayoutWidth];
3256 }
3257
3258 - (CGFloat)minimumWidthForAutoLayout
3259 {
3260     return _data->_page->minimumLayoutWidth();
3261 }
3262
3263 - (void)setMinimumWidthForAutoLayout:(CGFloat)minimumLayoutWidth
3264 {
3265     BOOL expandsToFit = minimumLayoutWidth > 0;
3266
3267     _data->_expandsToFitContentViaAutoLayout = expandsToFit;
3268     _data->_page->setMinimumLayoutWidth(minimumLayoutWidth);
3269
3270     if (expandsToFit)
3271         _data->_page->viewExposedRectChanged([self visibleRect]);
3272
3273     _data->_page->setMainFrameIsScrollable(!expandsToFit);
3274 }
3275
3276 - (NSView*)fullScreenPlaceholderView
3277 {
3278 #if ENABLE(FULLSCREEN_API)
3279     if (_data->_fullScreenWindowController && [_data->_fullScreenWindowController isFullScreen])
3280         return [_data->_fullScreenWindowController webViewPlaceholder];
3281 #endif
3282     return nil;
3283 }
3284
3285 @end
3286
3287 @implementation WKResponderChainSink
3288
3289 - (id)initWithResponderChain:(NSResponder *)chain
3290 {
3291     self = [super init];
3292     if (!self)
3293         return nil;
3294     _lastResponderInChain = chain;
3295     while (NSResponder *next = [_lastResponderInChain nextResponder])
3296         _lastResponderInChain = next;
3297     [_lastResponderInChain setNextResponder:self];
3298     return self;
3299 }
3300
3301 - (void)detach
3302 {
3303     // This assumes that the responder chain was either unmodified since
3304     // -initWithResponderChain: was called, or was modified in such a way
3305     // that _lastResponderInChain is still in the chain, and self was not
3306     // moved earlier in the chain than _lastResponderInChain.
3307     NSResponder *responderBeforeSelf = _lastResponderInChain;    
3308     NSResponder *next = [responderBeforeSelf nextResponder];
3309     for (; next && next != self; next = [next nextResponder])
3310         responderBeforeSelf = next;
3311     
3312     // Nothing to be done if we are no longer in the responder chain.
3313     if (next != self)
3314         return;
3315     
3316     [responderBeforeSelf setNextResponder:[self nextResponder]];
3317     _lastResponderInChain = nil;
3318 }
3319
3320 - (bool)didReceiveUnhandledCommand
3321 {
3322     return _didReceiveUnhandledCommand;
3323 }
3324
3325 - (void)noResponderFor:(SEL)selector
3326 {
3327     _didReceiveUnhandledCommand = true;
3328 }
3329
3330 - (void)doCommandBySelector:(SEL)selector
3331 {
3332     _didReceiveUnhandledCommand = true;
3333 }
3334
3335 - (BOOL)tryToPerform:(SEL)action with:(id)object
3336 {
3337     _didReceiveUnhandledCommand = true;
3338     return YES;
3339 }
3340
3341 @end