7fd26096c5a0b6bd3e5459b0a5510642e858bde8
[WebKit-https.git] / WebKit2 / UIProcess / API / mac / WKView.mm
1 /*
2  * Copyright (C) 2010 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 "WKView.h"
27
28 #import "ChunkedUpdateDrawingAreaProxy.h"
29 #import "FindIndicator.h"
30 #import "FindIndicatorWindow.h"
31 #import "LayerBackedDrawingAreaProxy.h"
32 #import "Logging.h"
33 #import "NativeWebKeyboardEvent.h"
34 #import "PDFViewController.h"
35 #import "PageClientImpl.h"
36 #import "RunLoop.h"
37 #import "TextChecker.h"
38 #import "TextCheckerState.h"
39 #import "WKAPICast.h"
40 #import "WKStringCF.h"
41 #import "WKTextInputWindowController.h"
42 #import "WebContext.h"
43 #import "WebEventFactory.h"
44 #import "WebPage.h"
45 #import "WebPageProxy.h"
46 #import "WebProcessManager.h"
47 #import "WebProcessProxy.h"
48 #import "WebSystemInterface.h"
49 #import <QuartzCore/QuartzCore.h>
50 #import <WebCore/ColorMac.h>
51 #import <WebCore/FloatRect.h>
52 #import <WebCore/IntRect.h>
53 #import <WebCore/KeyboardEvent.h>
54 #import <WebCore/PlatformScreen.h>
55 #import <wtf/RefPtr.h>
56 #import <wtf/RetainPtr.h>
57
58 // FIXME (WebKit2) <rdar://problem/8728860> WebKit2 needs to be localized
59 #define UI_STRING(__str, __desc) [NSString stringWithUTF8String:__str]
60
61 @interface NSApplication (Details)
62 - (void)speakString:(NSString *)string;
63 @end
64
65 @interface NSWindow (Details)
66 - (NSRect)_growBoxRect;
67 - (BOOL)_updateGrowBoxForWindowFrameChange;
68 @end
69
70 extern "C" {
71     // Need to declare this attribute name because AppKit exports it but does not make it available in API or SPI headers.
72     // <rdar://problem/8631468> tracks the request to make it available. This code should be removed when the bug is closed.
73     extern NSString *NSTextInputReplacementRangeAttributeName;
74 }
75
76 using namespace WebKit;
77 using namespace WebCore;
78
79 namespace WebKit {
80
81 typedef id <NSValidatedUserInterfaceItem> ValidationItem;
82 typedef Vector<RetainPtr<ValidationItem> > ValidationVector;
83 typedef HashMap<String, ValidationVector> ValidationMap;
84
85 }
86
87 @interface WKViewData : NSObject {
88 @public
89     OwnPtr<PageClientImpl> _pageClient;
90     RefPtr<WebPageProxy> _page;
91
92     // For ToolTips.
93     NSToolTipTag _lastToolTipTag;
94     id _trackingRectOwner;
95     void* _trackingRectUserData;
96
97 #if USE(ACCELERATED_COMPOSITING)
98     NSView *_layerHostingView;
99 #endif
100
101     // For asynchronous validation.
102     ValidationMap _validationMap;
103
104     OwnPtr<PDFViewController> _pdfViewController;
105
106     OwnPtr<FindIndicatorWindow> _findIndicatorWindow;
107     // We keep here the event when resending it to
108     // the application to distinguish the case of a new event from one 
109     // that has been already sent to WebCore.
110     NSEvent *_keyDownEventBeingResent;
111     Vector<KeypressCommand> _commandsList;
112
113     // The identifier of the plug-in we want to send complex text input to, or 0 if there is none.
114     uint64_t _pluginComplexTextInputIdentifier;
115
116     Vector<CompositionUnderline> _underlines;
117     unsigned _selectionStart;
118     unsigned _selectionEnd;
119 }
120 @end
121
122 @implementation WKViewData
123 @end
124
125 @interface NSObject (NSTextInputContextDetails)
126 - (BOOL)wantsToHandleMouseEvents;
127 - (BOOL)handleMouseEvent:(NSEvent *)event;
128 @end
129
130 @implementation WKView
131
132 - (id)initWithFrame:(NSRect)frame
133 {
134     return [self initWithFrame:frame contextRef:toAPI(WebContext::sharedProcessContext())];
135 }
136
137 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef
138 {   
139     return [self initWithFrame:frame contextRef:contextRef pageGroupRef:nil];
140 }
141
142 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef
143 {
144     self = [super initWithFrame:frame];
145     if (!self)
146         return nil;
147
148     InitWebCoreSystemInterface();
149     RunLoop::initializeMainRunLoop();
150
151     NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame
152                                                                 options:(NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect)
153                                                                   owner:self
154                                                                userInfo:nil];
155     [self addTrackingArea:trackingArea];
156     [trackingArea release];
157
158     _data = [[WKViewData alloc] init];
159
160     _data->_pageClient = PageClientImpl::create(self);
161     _data->_page = toImpl(contextRef)->createWebPage(toImpl(pageGroupRef));
162     _data->_page->setPageClient(_data->_pageClient.get());
163     _data->_page->setDrawingArea(ChunkedUpdateDrawingAreaProxy::create(self, _data->_page.get()));
164     _data->_page->initializeWebPage(IntSize(frame.size));
165     _data->_page->setIsInWindow([self window]);
166
167     WebContext::statistics().wkViewCount++;
168
169     return self;
170 }
171
172 - (void)dealloc
173 {
174     _data->_page->close();
175
176     [_data release];
177
178     WebContext::statistics().wkViewCount--;
179
180     [super dealloc];
181 }
182
183 - (WKPageRef)pageRef
184 {
185     return toAPI(_data->_page.get());
186 }
187
188 - (void)setDrawsBackground:(BOOL)drawsBackground
189 {
190     _data->_page->setDrawsBackground(drawsBackground);
191 }
192
193 - (BOOL)drawsBackground
194 {
195     return _data->_page->drawsBackground();
196 }
197
198 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
199 {
200     _data->_page->setDrawsTransparentBackground(drawsTransparentBackground);
201 }
202
203 - (BOOL)drawsTransparentBackground
204 {
205     return _data->_page->drawsTransparentBackground();
206 }
207
208 - (BOOL)acceptsFirstResponder
209 {
210     return YES;
211 }
212
213 - (BOOL)becomeFirstResponder
214 {
215     NSSelectionDirection direction = [[self window] keyViewSelectionDirection];
216
217     _data->_page->setFocused(true);
218
219     if (direction != NSDirectSelection)
220         _data->_page->setInitialFocus(direction == NSSelectingNext);
221
222     return YES;
223 }
224
225 - (BOOL)resignFirstResponder
226 {
227     _data->_page->setFocused(false);
228     return YES;
229 }
230
231 - (BOOL)isFlipped
232 {
233     return YES;
234 }
235
236 - (void)setFrameSize:(NSSize)size
237 {
238     [super setFrameSize:size];
239
240     _data->_page->drawingArea()->setSize(IntSize(size));
241 }
242
243 - (void)_updateWindowAndViewFrames
244 {
245     NSWindow *window = [self window];
246     ASSERT(window);
247     
248     NSRect windowFrameInScreenCoordinates = [window frame];
249     NSRect viewFrameInWindowCoordinates = [self convertRect:[self frame] toView:nil];
250     
251     _data->_page->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
252 }
253
254 - (void)renewGState
255 {
256     // Hide the find indicator.
257     _data->_findIndicatorWindow = nullptr;
258
259     // Update the view frame.
260     if ([self window])
261         [self _updateWindowAndViewFrames];
262
263     [super renewGState];
264 }
265
266 typedef HashMap<SEL, String> SelectorNameMap;
267
268 // Map selectors into Editor command names.
269 // This is not needed for any selectors that have the same name as the Editor command.
270 static const SelectorNameMap* createSelectorExceptionMap()
271 {
272     SelectorNameMap* map = new HashMap<SEL, String>;
273     
274     map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
275     map->add(@selector(insertParagraphSeparator:), "InsertNewline");
276     map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
277     map->add(@selector(pageDown:), "MovePageDown");
278     map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
279     map->add(@selector(pageUp:), "MovePageUp");
280     map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
281     
282     return map;
283 }
284
285 static String commandNameForSelector(SEL selector)
286 {
287     // Check the exception map first.
288     static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
289     SelectorNameMap::const_iterator it = exceptionMap->find(selector);
290     if (it != exceptionMap->end())
291         return it->second;
292     
293     // Remove the trailing colon.
294     // No need to capitalize the command name since Editor command names are
295     // not case sensitive.
296     const char* selectorName = sel_getName(selector);
297     size_t selectorNameLength = strlen(selectorName);
298     if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
299         return String();
300     return String(selectorName, selectorNameLength - 1);
301 }
302
303 // Editing commands
304
305 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
306
307 WEBCORE_COMMAND(copy)
308 WEBCORE_COMMAND(cut)
309 WEBCORE_COMMAND(paste)
310 WEBCORE_COMMAND(delete)
311 WEBCORE_COMMAND(pasteAsPlainText)
312 WEBCORE_COMMAND(selectAll)
313 WEBCORE_COMMAND(takeFindStringFromSelection)
314
315 #undef WEBCORE_COMMAND
316
317 // Menu items validation
318
319 static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item)
320 {
321     if (![(NSObject *)item isKindOfClass:[NSMenuItem class]])
322         return nil;
323     return (NSMenuItem *)item;
324 }
325
326 static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item)
327 {
328     if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]])
329         return nil;
330     return (NSToolbarItem *)item;
331 }
332
333 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
334 {
335     SEL action = [item action];
336
337     if (action == @selector(showGuessPanel:)) {
338         if (NSMenuItem *menuItem = ::menuItem(item)) {
339             BOOL panelShowing = [[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible];
340             [menuItem setTitle:panelShowing
341                 ? UI_STRING("Hide Spelling and Grammar", "menu item title")
342                 : UI_STRING("Show Spelling and Grammar", "menu item title")];
343         }
344         return _data->_page->selectionState().isContentEditable;
345     }
346
347     if (action == @selector(checkSpelling:))
348         return _data->_page->selectionState().isContentEditable;
349
350     if (action == @selector(toggleContinuousSpellChecking:)) {
351         bool enabled = TextChecker::isContinuousSpellCheckingAllowed();
352         bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled;
353         [menuItem(item) setState:checked ? NSOnState : NSOffState];
354         return enabled;
355     }
356
357     if (action == @selector(toggleGrammarChecking:)) {
358         bool checked = TextChecker::state().isGrammarCheckingEnabled;
359         [menuItem(item) setState:checked ? NSOnState : NSOffState];
360         return YES;
361     }
362
363     if (action == @selector(toggleAutomaticSpellingCorrection:)) {
364         bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled;
365         [menuItem(item) setState:checked ? NSOnState : NSOffState];
366         return _data->_page->selectionState().isContentEditable;
367     }
368
369     if (action == @selector(stopSpeaking:))
370         return [NSApp isSpeaking];
371
372     // Next, handle editor commands. Start by returning YES for anything that is not an editor command.
373     // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized.
374     String commandName = commandNameForSelector([item action]);
375     if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName))
376         return YES;
377
378     // Add this item to the vector of items for a given command that are awaiting validation.
379     pair<ValidationMap::iterator, bool> addResult = _data->_validationMap.add(commandName, ValidationVector());
380     addResult.first->second.append(item);
381     if (addResult.second) {
382         // If we are not already awaiting validation for this command, start the asynchronous validation process.
383         // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
384         // we asked for the same command; there is no guarantee the answer is still valid.
385         // FIXME: The function called here should be renamed validateCommand because it is not specific to menu items.
386         _data->_page->validateMenuItem(commandName);
387     }
388
389     // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called.
390     // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment.
391     // But returning NO here would be worse; that would make keyboard commands such as command-C fail.
392     return YES;
393 }
394
395 static void speakString(WKStringRef string, WKErrorRef error, void*)
396 {
397     if (error)
398         return;
399     if (!string)
400         return;
401
402     NSString *convertedString = toImpl(string)->string();
403     [NSApp speakString:convertedString];
404 }
405
406 - (IBAction)startSpeaking:(id)sender
407 {
408     _data->_page->getSelectionOrContentsAsString(StringCallback::create(0, speakString));
409 }
410
411 - (IBAction)stopSpeaking:(id)sender
412 {
413     [NSApp stopSpeaking:sender];
414 }
415
416 - (IBAction)showGuessPanel:(id)sender
417 {
418     // FIXME (WebKit2) <rdar://problem/8245958> Make Spelling/Grammar checking work in WebKit2
419 }
420
421 - (IBAction)checkSpelling:(id)sender
422 {
423     // FIXME (WebKit2) <rdar://problem/8245958> Make Spelling/Grammar checking work in WebKit2
424 }
425
426 - (IBAction)toggleContinuousSpellChecking:(id)sender
427 {
428     bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled;
429     TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled);
430
431     _data->_page->process()->updateTextCheckerState();
432
433     if (!spellCheckingEnabled)
434         _data->_page->unmarkAllMisspellings();
435 }
436
437 - (IBAction)toggleGrammarChecking:(id)sender
438 {
439     bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled;
440     TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled);
441
442     _data->_page->process()->updateTextCheckerState();
443
444     if (!grammarCheckingEnabled)
445         _data->_page->unmarkAllBadGrammar();
446 }
447
448 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
449 {
450     TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
451
452     _data->_page->process()->updateTextCheckerState();
453 }
454
455 // Events
456
457 // Override this so that AppKit will send us arrow keys as key down events so we can
458 // support them via the key bindings mechanism.
459 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
460 {
461     return YES;
462 }
463
464 #define EVENT_HANDLER(Selector, Type) \
465     - (void)Selector:(NSEvent *)theEvent \
466     { \
467         Web##Type##Event webEvent = WebEventFactory::createWeb##Type##Event(theEvent, self); \
468         _data->_page->handle##Type##Event(webEvent); \
469     }
470
471 EVENT_HANDLER(mouseEntered, Mouse)
472 EVENT_HANDLER(mouseExited, Mouse)
473 EVENT_HANDLER(mouseMoved, Mouse)
474 EVENT_HANDLER(otherMouseDown, Mouse)
475 EVENT_HANDLER(otherMouseDragged, Mouse)
476 EVENT_HANDLER(otherMouseMoved, Mouse)
477 EVENT_HANDLER(otherMouseUp, Mouse)
478 EVENT_HANDLER(rightMouseDown, Mouse)
479 EVENT_HANDLER(rightMouseDragged, Mouse)
480 EVENT_HANDLER(rightMouseMoved, Mouse)
481 EVENT_HANDLER(rightMouseUp, Mouse)
482 EVENT_HANDLER(scrollWheel, Wheel)
483
484 #undef EVENT_HANDLER
485
486 #define MOUSE_EVENT_HANDLER(Selector) \
487     - (void)Selector:(NSEvent *)theEvent \
488     { \
489         NSInputManager *currentInputManager = [NSInputManager currentInputManager]; \
490         if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:theEvent]) \
491             return; \
492         WebMouseEvent webEvent = WebEventFactory::createWebMouseEvent(theEvent, self); \
493         _data->_page->handleMouseEvent(webEvent); \
494     }
495
496 MOUSE_EVENT_HANDLER(mouseDown)
497 MOUSE_EVENT_HANDLER(mouseDragged)
498 MOUSE_EVENT_HANDLER(mouseUp)
499
500 #undef MOUSE_EVENT_HANDLER
501
502 - (void)doCommandBySelector:(SEL)selector
503 {
504     if (selector != @selector(noop:))
505         _data->_commandsList.append(KeypressCommand(commandNameForSelector(selector)));
506 }
507
508 - (void)insertText:(id)string
509 {
510     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; // Otherwise, NSString
511     
512     LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string);
513     NSString *text;
514     bool isFromInputMethod = _data->_page->selectionState().hasComposition;
515
516     if (isAttributedString) {
517         text = [string string];
518         // We deal with the NSTextInputReplacementRangeAttributeName attribute from NSAttributedString here
519         // simply because it is used by at least one Input Method -- it corresonds to the kEventParamTextInputSendReplaceRange
520         // event in TSM.  This behaviour matches that of -[WebHTMLView setMarkedText:selectedRange:] when it receives an
521         // NSAttributedString
522         NSString *rangeString = [string attribute:NSTextInputReplacementRangeAttributeName atIndex:0 longestEffectiveRange:NULL inRange:NSMakeRange(0, [text length])];
523         LOG(TextInput, "ReplacementRange: %@", rangeString);
524         if (rangeString)
525             isFromInputMethod = YES;
526     } else
527         text = string;
528     
529     String eventText = text;
530     
531     if (!isFromInputMethod)
532         _data->_commandsList.append(KeypressCommand("insertText", text));
533     else {
534         eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore
535         _data->_commandsList.append(KeypressCommand("insertText", eventText));
536     }
537 }
538
539 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
540 {
541     if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) != NSCommandKeyMask)
542         return NO;
543     
544     // Here we special case cmd+b and cmd+i but not cmd+u, for historic reason.
545     // This should not be changed, since it could break some Mac applications that
546     // rely on this inherent behavior.
547     // See https://bugs.webkit.org/show_bug.cgi?id=24943
548     
549     NSString *string = [event characters];
550     if ([string caseInsensitiveCompare:@"b"] == NSOrderedSame) {
551         _data->_page->executeEditCommand("ToggleBold");
552         return YES;
553     }
554     if ([string caseInsensitiveCompare:@"i"] == NSOrderedSame) {
555         _data->_page->executeEditCommand("ToggleItalic");
556         return YES;
557     }
558     
559     return NO;
560 }
561
562 - (BOOL)performKeyEquivalent:(NSEvent *)event
563 {
564     // There's a chance that responding to this event will run a nested event loop, and
565     // fetching a new event might release the old one. Retaining and then autoreleasing
566     // the current event prevents that from causing a problem inside WebKit or AppKit code.
567     [[event retain] autorelease];
568     
569     BOOL eventWasSentToWebCore = (_data->_keyDownEventBeingResent == event);
570
571     // Pass key combos through WebCore if there is a key binding available for
572     // this event. This lets web pages have a crack at intercepting key-modified keypresses.
573     // But don't do it if we have already handled the event.
574     // Pressing Esc results in a fake event being sent - don't pass it to WebCore.
575     if (!eventWasSentToWebCore && event == [NSApp currentEvent] && self == [[self window] firstResponder]) {
576         [_data->_keyDownEventBeingResent release];
577         _data->_keyDownEventBeingResent = nil;
578         
579         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, self));
580         return YES;
581     }
582     
583     return [self _handleStyleKeyEquivalent:event] || [super performKeyEquivalent:event];
584 }
585
586 - (void)_setEventBeingResent:(NSEvent *)event
587 {
588     _data->_keyDownEventBeingResent = [event retain];
589 }
590
591 - (Vector<KeypressCommand>&)_interceptKeyEvent:(NSEvent *)theEvent 
592 {
593     _data->_commandsList.clear();
594     // interpretKeyEvents will trigger one or more calls to doCommandBySelector or setText
595     // that will populate the commandsList vector.
596     [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
597     return _data->_commandsList;
598 }
599
600 - (void)_getTextInputState:(unsigned)start selectionEnd:(unsigned)end underlines:(Vector<WebCore::CompositionUnderline>&)lines
601 {
602     start = _data->_selectionStart;
603     end = _data->_selectionEnd;
604     lines = _data->_underlines;
605 }
606
607 - (void)keyUp:(NSEvent *)theEvent
608 {
609     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
610 }
611
612 - (void)keyDown:(NSEvent *)theEvent
613 {
614     if (_data->_pluginComplexTextInputIdentifier) {
615         // Try feeding the keyboard event directly to the plug-in.
616         NSString *string = nil;
617         if ([[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:theEvent string:&string]) {
618             if (string)
619                 _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string);
620             return;
621         }
622     }
623
624     _data->_underlines.clear();
625     _data->_selectionStart = 0;
626     _data->_selectionEnd = 0;
627     // We could be receiving a key down from AppKit if we have re-sent an event
628     // that maps to an action that is currently unavailable (for example a copy when
629     // there is no range selection).
630     // If this is the case we should ignore the key down.
631     if (_data->_keyDownEventBeingResent == theEvent) {
632         [_data->_keyDownEventBeingResent release];
633         _data->_keyDownEventBeingResent = nil;
634         [super keyDown:theEvent];
635         return;
636     }
637     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
638 }
639
640 - (NSTextInputContext *)inputContext {
641     if (_data->_pluginComplexTextInputIdentifier)
642         return [[WKTextInputWindowController sharedTextInputWindowController] inputContext];
643
644     return [super inputContext];
645 }
646
647 - (NSRange)selectedRange
648 {
649     if (_data->_page->selectionState().isNone || !_data->_page->selectionState().isContentEditable)
650         return NSMakeRange(NSNotFound, 0);
651     
652     LOG(TextInput, "selectedRange -> (%u, %u)", _data->_page->selectionState().selectedRangeStart, _data->_page->selectionState().selectedRangeLength);
653     return NSMakeRange(_data->_page->selectionState().selectedRangeStart, _data->_page->selectionState().selectedRangeLength);
654 }
655
656 - (BOOL)hasMarkedText
657 {
658     LOG(TextInput, "hasMarkedText -> %u", _data->_page->selectionState().hasComposition);
659     return _data->_page->selectionState().hasComposition;
660 }
661
662 - (void)unmarkText
663 {
664     LOG(TextInput, "unmarkText");
665     
666     _data->_commandsList.append(KeypressCommand("unmarkText"));
667 }
668
669 - (NSArray *)validAttributesForMarkedText
670 {
671     static NSArray *validAttributes;
672     if (!validAttributes) {
673         validAttributes = [[NSArray alloc] initWithObjects:
674                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
675                            NSMarkedClauseSegmentAttributeName, NSTextInputReplacementRangeAttributeName, nil];
676         // NSText also supports the following attributes, but it's
677         // hard to tell which are really required for text input to
678         // work well; I have not seen any input method make use of them yet.
679         //     NSFontAttributeName, NSForegroundColorAttributeName,
680         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
681         CFRetain(validAttributes);
682     }
683     LOG(TextInput, "validAttributesForMarkedText -> (...)");
684     return validAttributes;
685 }
686
687 static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result)
688 {
689     int length = [[string string] length];
690     
691     int i = 0;
692     while (i < length) {
693         NSRange range;
694         NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)];
695         
696         if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
697             Color color = Color::black;
698             if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName])
699                 color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
700             result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1));
701         }
702         
703         i = range.location + range.length;
704     }
705 }
706
707 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
708 {
709     BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; // Otherwise, NSString
710     
711     LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelRange.location, newSelRange.length);
712     
713     NSString *text = string;
714     
715     if (isAttributedString) {
716         text = [string string];
717         extractUnderlines(string, _data->_underlines);
718     }
719     
720     _data->_commandsList.append(KeypressCommand("setMarkedText", text));
721     _data->_selectionStart = newSelRange.location;
722     _data->_selectionEnd = NSMaxRange(newSelRange);
723 }
724
725 - (NSRange)markedRange
726 {
727     uint64_t location;
728     uint64_t length;
729
730     _data->_page->getMarkedRange(location, length);
731     LOG(TextInput, "markedRange -> (%u, %u)", location, length);
732     return NSMakeRange(location, length);
733 }
734
735 - (NSAttributedString *)attributedSubstringFromRange:(NSRange)nsRange
736 {
737     // This is not implemented for now. Need to figure out how to serialize the attributed string across processes.
738     LOG(TextInput, "attributedSubstringFromRange");
739     return nil;
740 }
741
742 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
743 {
744     NSWindow *window = [self window];
745     
746     if (window)
747         thePoint = [window convertScreenToBase:thePoint];
748     thePoint = [self convertPoint:thePoint fromView:nil];  // the point is relative to the main frame 
749     
750     uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint));
751     LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result);
752     return result;
753 }
754
755 - (NSRect)firstRectForCharacterRange:(NSRange)theRange
756
757     // Just to match NSTextView's behavior. Regression tests cannot detect this;
758     // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682
759     // (type something; try ranges (1, -1) and (2, -1).
760     if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0))
761         theRange.length = 0;
762     
763     NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange.location, theRange.length);
764     resultRect = [self convertRect:resultRect toView:nil];
765     
766     NSWindow *window = [self window];
767     if (window)
768         resultRect.origin = [window convertBaseToScreen:resultRect.origin];
769     
770     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);
771     return resultRect;
772 }
773
774 - (void)_updateActiveState
775 {
776     _data->_page->setActive([[self window] isKeyWindow]);
777 }
778
779 - (void)_updateWindowVisibility
780 {
781     _data->_page->updateWindowIsVisible(![[self window] isMiniaturized]);
782 }
783
784 - (BOOL)_ownsWindowGrowBox
785 {
786     NSWindow* window = [self window];
787     if (!window)
788         return NO;
789
790     NSView *superview = [self superview];
791     if (!superview)
792         return NO;
793
794     NSRect growBoxRect = [window _growBoxRect];
795     if (NSIsEmptyRect(growBoxRect))
796         return NO;
797
798     NSRect visibleRect = [self visibleRect];
799     if (NSIsEmptyRect(visibleRect))
800         return NO;
801
802     NSRect visibleRectInWindowCoords = [self convertRect:visibleRect toView:nil];
803     if (!NSIntersectsRect(growBoxRect, visibleRectInWindowCoords))
804         return NO;
805
806     return YES;
807 }
808
809 - (BOOL)_updateGrowBoxForWindowFrameChange
810 {
811     // Temporarily enable the resize indicator to make a the _ownsWindowGrowBox calculation work.
812     BOOL wasShowingIndicator = [[self window] showsResizeIndicator];
813     [[self window] setShowsResizeIndicator:YES];
814
815     BOOL ownsGrowBox = [self _ownsWindowGrowBox];
816     _data->_page->setWindowResizerSize(ownsGrowBox ? enclosingIntRect([[self window] _growBoxRect]).size() : IntSize());
817     
818     // Once WebCore can draw the window resizer, this should read:
819     // if (wasShowingIndicator)
820     //     [[self window] setShowsResizeIndicator:!ownsGrowBox];
821     [[self window] setShowsResizeIndicator:wasShowingIndicator];
822
823     return ownsGrowBox;
824 }
825
826 - (void)addWindowObserversForWindow:(NSWindow *)window
827 {
828     if (window) {
829         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
830                                                      name:NSWindowDidBecomeKeyNotification object:nil];
831         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
832                                                      name:NSWindowDidResignKeyNotification object:nil];
833         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) 
834                                                      name:NSWindowDidMiniaturizeNotification object:window];
835         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
836                                                      name:NSWindowDidDeminiaturizeNotification object:window];
837         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:)
838                                                      name:NSWindowDidMoveNotification object:window];
839         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:) 
840                                                      name:NSWindowDidResizeNotification object:window];
841     }
842 }
843
844 - (void)removeWindowObservers
845 {
846     NSWindow *window = [self window];
847     if (!window)
848         return;
849
850     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
851     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
852     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
853     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
854     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
855     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
856 }
857
858 static bool isViewVisible(NSView *view)
859 {
860     if (![view window])
861         return false;
862     
863     if ([view isHiddenOrHasHiddenAncestor])
864         return false;
865     
866     return true;
867 }
868
869 - (void)_updateVisibility
870 {
871     _data->_page->setIsInWindow([self window]);
872     if (DrawingAreaProxy* area = _data->_page->drawingArea())
873         area->setPageIsVisible(isViewVisible(self));
874 }
875
876 - (void)viewWillMoveToWindow:(NSWindow *)window
877 {
878     if (window != [self window]) {
879         [self removeWindowObservers];
880         [self addWindowObserversForWindow:window];
881     }
882 }
883
884 - (void)viewDidMoveToWindow
885 {
886     // We want to make sure to update the active state while hidden, so if the view is about to become visible, we
887     // update the active state first and then make it visible. If the view is about to be hidden, we hide it first and then
888     // update the active state.
889     if ([self window]) {
890         [self _updateActiveState];
891         [self _updateVisibility];
892         [self _updateWindowVisibility];
893         [self _updateWindowAndViewFrames];
894     } else {
895         [self _updateVisibility];
896         [self _updateActiveState];
897     }
898
899 }
900
901 - (void)_windowDidBecomeKey:(NSNotification *)notification
902 {
903     NSWindow *keyWindow = [notification object];
904     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
905         [self _updateActiveState];
906 }
907
908 - (void)_windowDidResignKey:(NSNotification *)notification
909 {
910     NSWindow *formerKeyWindow = [notification object];
911     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet])
912         [self _updateActiveState];
913 }
914
915 - (void)_windowDidMiniaturize:(NSNotification *)notification
916 {
917     [self _updateWindowVisibility];
918 }
919
920 - (void)_windowDidDeminiaturize:(NSNotification *)notification
921 {
922     [self _updateWindowVisibility];
923 }
924
925 - (void)_windowFrameDidChange:(NSNotification *)notification
926 {
927     [self _updateWindowAndViewFrames];
928 }
929
930 - (void)drawRect:(NSRect)rect
931 {
932     if (_data->_page->isValid() && _data->_page->drawingArea()) {
933         CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
934         _data->_page->drawingArea()->paint(IntRect(rect), context);
935         _data->_page->didDraw();
936     } else if (_data->_page->drawsBackground()) {
937         [_data->_page->drawsTransparentBackground() ? [NSColor clearColor] : [NSColor whiteColor] set];
938         NSRectFill(rect);
939     }
940 }
941
942 - (BOOL)isOpaque
943 {
944     return _data->_page->drawsBackground();
945 }
946
947 - (void)viewDidHide
948 {
949     [self _updateVisibility];
950 }
951
952 - (void)viewDidUnhide
953 {
954     [self _updateVisibility];
955 }
956
957 - (NSView *)hitTest:(NSPoint)point
958 {
959     NSView *hitView = [super hitTest:point];
960 #if USE(ACCELERATED_COMPOSITING)
961     if (hitView && _data && hitView == _data->_layerHostingView)
962         hitView = self;
963 #endif
964     return hitView;
965 }
966
967 - (NSInteger)conversationIdentifier
968 {
969     return (NSInteger)self;
970 }
971
972 @end
973
974 @implementation WKView (Internal)
975
976 - (void)_processDidCrash
977 {
978     [self setNeedsDisplay:YES];
979 }
980
981 - (void)_didRelaunchProcess
982 {
983     _data->_page->reinitializeWebPage(IntSize([self bounds].size));
984
985     _data->_page->setActive([[self window] isKeyWindow]);
986     _data->_page->setFocused([[self window] firstResponder] == self);
987     
988     [self setNeedsDisplay:YES];
989 }
990
991 - (void)_takeFocus:(BOOL)forward
992 {
993     if (forward)
994         [[self window] selectKeyViewFollowingView:self];
995     else
996         [[self window] selectKeyViewPrecedingView:self];
997 }
998
999 - (void)_setCursor:(NSCursor *)cursor
1000 {
1001     if ([NSCursor currentCursor] == cursor)
1002         return;
1003     [cursor set];
1004 }
1005
1006 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
1007 {
1008     ValidationVector items = _data->_validationMap.take(commandName);
1009     size_t size = items.size();
1010     for (size_t i = 0; i < size; ++i) {
1011         ValidationItem item = items[i].get();
1012         [menuItem(item) setState:newState];
1013         [menuItem(item) setEnabled:isEnabled];
1014         [toolbarItem(item) setEnabled:isEnabled];
1015         // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled.
1016     }
1017 }
1018
1019 - (NSRect)_convertToDeviceSpace:(NSRect)rect
1020 {
1021     return toDeviceSpace(rect, [self window]);
1022 }
1023
1024 - (NSRect)_convertToUserSpace:(NSRect)rect
1025 {
1026     return toUserSpace(rect, [self window]);
1027 }
1028
1029 // Any non-zero value will do, but using something recognizable might help us debug some day.
1030 #define TRACKING_RECT_TAG 0xBADFACE
1031
1032 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
1033 {
1034     ASSERT(_data->_trackingRectOwner == nil);
1035     _data->_trackingRectOwner = owner;
1036     _data->_trackingRectUserData = data;
1037     return TRACKING_RECT_TAG;
1038 }
1039
1040 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
1041 {
1042     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
1043     ASSERT(_data->_trackingRectOwner == nil);
1044     _data->_trackingRectOwner = owner;
1045     _data->_trackingRectUserData = data;
1046     return TRACKING_RECT_TAG;
1047 }
1048
1049 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
1050 {
1051     ASSERT(count == 1);
1052     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
1053     ASSERT(_data->_trackingRectOwner == nil);
1054     _data->_trackingRectOwner = owner;
1055     _data->_trackingRectUserData = userDataList[0];
1056     trackingNums[0] = TRACKING_RECT_TAG;
1057 }
1058
1059 - (void)removeTrackingRect:(NSTrackingRectTag)tag
1060 {
1061     if (tag == 0)
1062         return;
1063     
1064     if (_data && (tag == TRACKING_RECT_TAG)) {
1065         _data->_trackingRectOwner = nil;
1066         return;
1067     }
1068     
1069     if (_data && (tag == _data->_lastToolTipTag)) {
1070         [super removeTrackingRect:tag];
1071         _data->_lastToolTipTag = 0;
1072         return;
1073     }
1074     
1075     // If any other tracking rect is being removed, we don't know how it was created
1076     // and it's possible there's a leak involved (see 3500217)
1077     ASSERT_NOT_REACHED();
1078 }
1079
1080 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
1081 {
1082     int i;
1083     for (i = 0; i < count; ++i) {
1084         int tag = tags[i];
1085         if (tag == 0)
1086             continue;
1087         ASSERT(tag == TRACKING_RECT_TAG);
1088         if (_data != nil) {
1089             _data->_trackingRectOwner = nil;
1090         }
1091     }
1092 }
1093
1094 - (void)_sendToolTipMouseExited
1095 {
1096     // Nothing matters except window, trackingNumber, and userData.
1097     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
1098         location:NSMakePoint(0, 0)
1099         modifierFlags:0
1100         timestamp:0
1101         windowNumber:[[self window] windowNumber]
1102         context:NULL
1103         eventNumber:0
1104         trackingNumber:TRACKING_RECT_TAG
1105         userData:_data->_trackingRectUserData];
1106     [_data->_trackingRectOwner mouseExited:fakeEvent];
1107 }
1108
1109 - (void)_sendToolTipMouseEntered
1110 {
1111     // Nothing matters except window, trackingNumber, and userData.
1112     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
1113         location:NSMakePoint(0, 0)
1114         modifierFlags:0
1115         timestamp:0
1116         windowNumber:[[self window] windowNumber]
1117         context:NULL
1118         eventNumber:0
1119         trackingNumber:TRACKING_RECT_TAG
1120         userData:_data->_trackingRectUserData];
1121     [_data->_trackingRectOwner mouseEntered:fakeEvent];
1122 }
1123
1124 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
1125 {
1126     return nsStringFromWebCoreString(_data->_page->toolTip());
1127 }
1128
1129 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
1130 {
1131     if (oldToolTip)
1132         [self _sendToolTipMouseExited];
1133
1134     if (newToolTip && [newToolTip length] > 0) {
1135         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
1136         [self removeAllToolTips];
1137         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
1138         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
1139         [self _sendToolTipMouseEntered];
1140     }
1141 }
1142
1143 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut
1144 {
1145     if (!findIndicator) {
1146         _data->_findIndicatorWindow = 0;
1147         return;
1148     }
1149
1150     if (!_data->_findIndicatorWindow)
1151         _data->_findIndicatorWindow = FindIndicatorWindow::create(self);
1152
1153     _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut);
1154 }
1155
1156 #if USE(ACCELERATED_COMPOSITING)
1157 - (void)_startAcceleratedCompositing:(CALayer *)rootLayer
1158 {
1159     if (!_data->_layerHostingView) {
1160         NSView *hostingView = [[NSView alloc] initWithFrame:[self bounds]];
1161 #if !defined(BUILDING_ON_LEOPARD)
1162         [hostingView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
1163 #endif
1164         
1165         [self addSubview:hostingView];
1166         [hostingView release];
1167         _data->_layerHostingView = hostingView;
1168     }
1169
1170     // Make a container layer, which will get sized/positioned by AppKit and CA.
1171     CALayer *viewLayer = [CALayer layer];
1172
1173 #ifndef NDEBUG
1174     [viewLayer setName:@"hosting layer"];
1175 #endif
1176
1177 #if defined(BUILDING_ON_LEOPARD)
1178     // Turn off default animations.
1179     NSNull *nullValue = [NSNull null];
1180     NSDictionary *actions = [NSDictionary dictionaryWithObjectsAndKeys:
1181                              nullValue, @"anchorPoint",
1182                              nullValue, @"bounds",
1183                              nullValue, @"contents",
1184                              nullValue, @"contentsRect",
1185                              nullValue, @"opacity",
1186                              nullValue, @"position",
1187                              nullValue, @"sublayerTransform",
1188                              nullValue, @"sublayers",
1189                              nullValue, @"transform",
1190                              nil];
1191     [viewLayer setStyle:[NSDictionary dictionaryWithObject:actions forKey:@"actions"]];
1192 #endif
1193
1194 #if !defined(BUILDING_ON_LEOPARD)
1195     // If we aren't in the window yet, we'll use the screen's scale factor now, and reset the scale 
1196     // via -viewDidMoveToWindow.
1197     CGFloat scaleFactor = [self window] ? [[self window] userSpaceScaleFactor] : [[NSScreen mainScreen] userSpaceScaleFactor];
1198     [viewLayer setTransform:CATransform3DMakeScale(scaleFactor, scaleFactor, 1)];
1199 #endif
1200
1201     [_data->_layerHostingView setLayer:viewLayer];
1202     [_data->_layerHostingView setWantsLayer:YES];
1203     
1204     // Parent our root layer in the container layer
1205     [viewLayer addSublayer:rootLayer];
1206 }
1207
1208 - (void)_stopAcceleratedCompositing
1209 {
1210     if (_data->_layerHostingView) {
1211         [_data->_layerHostingView setLayer:nil];
1212         [_data->_layerHostingView setWantsLayer:NO];
1213         [_data->_layerHostingView removeFromSuperview];
1214         _data->_layerHostingView = nil;
1215     }
1216 }
1217
1218 - (void)_switchToDrawingAreaTypeIfNecessary:(DrawingAreaInfo::Type)type
1219 {
1220     DrawingAreaInfo::Type existingDrawingAreaType = _data->_page->drawingArea() ? _data->_page->drawingArea()->info().type : DrawingAreaInfo::None;
1221     if (existingDrawingAreaType == type)
1222         return;
1223
1224     OwnPtr<DrawingAreaProxy> newDrawingArea;
1225     switch (type) {
1226         case DrawingAreaInfo::None:
1227             break;
1228         case DrawingAreaInfo::ChunkedUpdate: {
1229             newDrawingArea = ChunkedUpdateDrawingAreaProxy::create(self, _data->_page.get());
1230             break;
1231         }
1232         case DrawingAreaInfo::LayerBacked: {
1233             newDrawingArea = LayerBackedDrawingAreaProxy::create(self, _data->_page.get());
1234             break;
1235         }
1236     }
1237
1238     newDrawingArea->setSize(IntSize([self frame].size));
1239
1240     _data->_page->drawingArea()->detachCompositingContext();
1241     _data->_page->setDrawingArea(newDrawingArea.release());
1242 }
1243
1244 - (void)_pageDidEnterAcceleratedCompositing
1245 {
1246     [self _switchToDrawingAreaTypeIfNecessary:DrawingAreaInfo::LayerBacked];
1247 }
1248
1249 - (void)_pageDidLeaveAcceleratedCompositing
1250 {
1251     // FIXME: we may want to avoid flipping back to the non-layer-backed drawing area until the next page load, to avoid thrashing.
1252     [self _switchToDrawingAreaTypeIfNecessary:DrawingAreaInfo::ChunkedUpdate];
1253 }
1254 #endif // USE(ACCELERATED_COMPOSITING)
1255
1256 - (void)_setComplexTextInputEnabled:(BOOL)complexTextInputEnabled pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier
1257 {
1258     BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier;
1259
1260     if (complexTextInputEnabled) {
1261         // Check if we're already allowing text input for this plug-in.
1262         if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier)
1263             return;
1264
1265         _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier;
1266
1267     } else {
1268         // Check if we got a request to disable complex text input for a plug-in that is not the current plug-in.
1269         if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier)
1270             return;
1271
1272         _data->_pluginComplexTextInputIdentifier = 0;
1273     }
1274
1275     if (inputSourceChanged) {
1276         // Inform the out of line window that the input source changed.
1277         [[WKTextInputWindowController sharedTextInputWindowController] keyboardInputSourceChanged];
1278     }
1279 }
1280
1281 - (void)_setPageHasCustomRepresentation:(BOOL)pageHasCustomRepresentation
1282 {
1283     _data->_pdfViewController = nullptr;
1284
1285     if (pageHasCustomRepresentation)
1286         _data->_pdfViewController = PDFViewController::create(self);
1287 }
1288
1289 - (void)_didFinishLoadingDataForCustomRepresentation:(const CoreIPC::DataReference&)dataReference
1290 {
1291     ASSERT(_data->_pdfViewController);
1292
1293     _data->_pdfViewController->setPDFDocumentData(_data->_page->mainFrame()->mimeType(), dataReference);
1294 }
1295
1296 @end