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