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