2010-12-09 Maciej Stachowiak <mjs@apple.com>
[WebKit.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 // C API
29 #import "WKAPICast.h"
30
31 // Implementation
32 #import "ChunkedUpdateDrawingAreaProxy.h"
33 #import "FindIndicator.h"
34 #import "FindIndicatorWindow.h"
35 #import "LayerBackedDrawingAreaProxy.h"
36 #import "NativeWebKeyboardEvent.h"
37 #import "PageClientImpl.h"
38 #import "RunLoop.h"
39 #import "WebContext.h"
40 #import "WebEventFactory.h"
41 #import "WebPage.h"
42 #import "WebPageNamespace.h"
43 #import "WebPageProxy.h"
44 #import "WebProcessManager.h"
45 #import "WebProcessProxy.h"
46 #import "WebSystemInterface.h"
47 #import <QuartzCore/QuartzCore.h>
48 #import <WebCore/FloatRect.h>
49 #import <WebCore/IntRect.h>
50 #import <WebCore/KeyboardEvent.h>
51 #import <WebCore/PlatformScreen.h>
52 #import <wtf/RefPtr.h>
53 #import <wtf/RetainPtr.h>
54
55 extern "C" {
56     
57     // Need to declare this attribute name because AppKit exports it but does not make it available in API or SPI headers.
58     // <rdar://problem/8631468> tracks the request to make it available. This code should be removed when the bug is closed.
59     
60     extern NSString *NSTextInputReplacementRangeAttributeName;
61     
62 }
63
64 using namespace WebKit;
65 using namespace WebCore;
66
67 struct EditCommandState {
68     EditCommandState() : m_isEnabled(false), m_state(0) {};
69     EditCommandState(bool isEnabled, int state) : m_isEnabled(isEnabled), m_state(state) { }
70     bool m_isEnabled;
71     int m_state;
72 };
73
74 @interface NSWindow (Details)
75 - (NSRect)_growBoxRect;
76 - (BOOL)_updateGrowBoxForWindowFrameChange;
77 @end
78
79 @interface WKViewData : NSObject {
80 @public
81     OwnPtr<PageClientImpl> _pageClient;
82     RefPtr<WebPageProxy> _page;
83
84     // For ToolTips.
85     NSToolTipTag _lastToolTipTag;
86     id _trackingRectOwner;
87     void* _trackingRectUserData;
88
89 #if USE(ACCELERATED_COMPOSITING)
90     NSView *_layerHostingView;
91 #endif
92     // For Menus.
93     int _menuEntriesCount;
94     Vector<RetainPtr<NSMenu> > _menuList;
95     bool _isPerformingUpdate;
96     
97     HashMap<String, EditCommandState> _menuMap;
98
99     OwnPtr<FindIndicatorWindow> _findIndicatorWindow;
100     // We keep here the event when resending it to
101     // the application to distinguish the case of a new event from one 
102     // that has been already sent to WebCore.
103     NSEvent *_keyDownEventBeingResent;
104     Vector<KeypressCommand> _commandsList;
105     BOOL _isSelectionNone;
106     BOOL _isSelectionEditable;
107     BOOL _isSelectionInPasswordField;
108     BOOL _hasMarkedText;
109 }
110 @end
111
112 @implementation WKViewData
113 @end
114
115 @implementation WKView
116
117 - (id)initWithFrame:(NSRect)frame pageNamespaceRef:(WKPageNamespaceRef)pageNamespaceRef pageGroupRef:(WKPageGroupRef)pageGroupRef
118 {
119     self = [super initWithFrame:frame];
120     if (!self)
121         return nil;
122
123     InitWebCoreSystemInterface();
124     RunLoop::initializeMainRunLoop();
125
126     NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame
127                                                                 options:(NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect)
128                                                                   owner:self
129                                                                userInfo:nil];
130     [self addTrackingArea:trackingArea];
131     [trackingArea release];
132
133     _data = [[WKViewData alloc] init];
134
135     _data->_pageClient = PageClientImpl::create(self);
136     _data->_page = toImpl(pageNamespaceRef)->createWebPage(toImpl(pageGroupRef));
137     _data->_page->setPageClient(_data->_pageClient.get());
138     _data->_page->setDrawingArea(ChunkedUpdateDrawingAreaProxy::create(self));
139     _data->_page->initializeWebPage(IntSize(frame.size));
140     _data->_page->setIsInWindow([self window]);
141
142     _data->_menuEntriesCount = 0;
143     _data->_isPerformingUpdate = false;
144     _data->_isSelectionNone = YES;
145     _data->_isSelectionEditable = NO;
146     _data->_isSelectionInPasswordField = NO;
147     _data->_hasMarkedText = NO;
148
149     return self;
150 }
151
152 - (id)initWithFrame:(NSRect)frame pageNamespaceRef:(WKPageNamespaceRef)pageNamespaceRef
153 {
154     return [self initWithFrame:frame pageNamespaceRef:pageNamespaceRef pageGroupRef:nil];
155 }
156
157 - (id)initWithFrame:(NSRect)frame
158 {
159     WebContext* context = WebContext::sharedProcessContext();
160     return [self initWithFrame:frame pageNamespaceRef:toAPI(context->createPageNamespace())];
161 }
162
163 - (void)dealloc
164 {
165     _data->_page->close();
166
167     [_data release];
168     [super dealloc];
169 }
170
171 - (WKPageRef)pageRef
172 {
173     return toAPI(_data->_page.get());
174 }
175
176 - (BOOL)acceptsFirstResponder
177 {
178     return YES;
179 }
180
181 - (BOOL)becomeFirstResponder
182 {
183     _data->_page->setFocused(true);
184     return YES;
185 }
186
187 - (BOOL)resignFirstResponder
188 {
189     _data->_page->setFocused(false);
190     return YES;
191 }
192
193 - (BOOL)isFlipped
194 {
195     return YES;
196 }
197
198 - (void)setFrameSize:(NSSize)size
199 {
200     [super setFrameSize:size];
201
202     _data->_page->drawingArea()->setSize(IntSize(size));
203 }
204
205 - (void)_updateWindowAndViewFrames
206 {
207     NSWindow *window = [self window];
208     ASSERT(window);
209     
210     NSRect windowFrameInScreenCoordinates = [window frame];
211     NSRect viewFrameInWindowCoordinates = [self convertRect:[self frame] toView:nil];
212     
213     _data->_page->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
214 }
215
216 - (void)renewGState
217 {
218     // Hide the find indicator.
219     _data->_findIndicatorWindow = nullptr;
220
221     // Update the view frame.
222     if ([self window])
223         [self _updateWindowAndViewFrames];
224
225     [super renewGState];
226 }
227
228 typedef HashMap<SEL, String> SelectorNameMap;
229
230 // Map selectors into Editor command names.
231 // This is not needed for any selectors that have the same name as the Editor command.
232 static const SelectorNameMap* createSelectorExceptionMap()
233 {
234     SelectorNameMap* map = new HashMap<SEL, String>;
235     
236     map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline");
237     map->add(@selector(insertParagraphSeparator:), "InsertNewline");
238     map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab");
239     map->add(@selector(pageDown:), "MovePageDown");
240     map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection");
241     map->add(@selector(pageUp:), "MovePageUp");
242     map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection");
243     
244     return map;
245 }
246
247 static String commandNameForSelector(SEL selector)
248 {
249     // Check the exception map first.
250     static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
251     SelectorNameMap::const_iterator it = exceptionMap->find(selector);
252     if (it != exceptionMap->end())
253         return it->second;
254     
255     // Remove the trailing colon.
256     // No need to capitalize the command name since Editor command names are
257     // not case sensitive.
258     const char* selectorName = sel_getName(selector);
259     size_t selectorNameLength = strlen(selectorName);
260     if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
261         return String();
262     return String(selectorName, selectorNameLength - 1);
263 }
264
265 // Editing commands
266 // FIXME: we should add all the commands here as we implement them.
267
268 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); }
269
270 WEBCORE_COMMAND(copy)
271 WEBCORE_COMMAND(cut)
272 WEBCORE_COMMAND(paste)
273 WEBCORE_COMMAND(delete)
274 WEBCORE_COMMAND(pasteAsPlainText)
275 WEBCORE_COMMAND(selectAll)
276 WEBCORE_COMMAND(takeFindStringFromSelection)
277
278 #undef WEBCORE_COMMAND
279
280 // Menu items validation
281
282 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
283 {
284     String commandName = commandNameForSelector([item action]);
285     NSMenuItem *menuItem = (NSMenuItem *)item;
286     if (![menuItem isKindOfClass:[NSMenuItem class]])
287         return NO; // FIXME: We need to be able to handle other user interface elements.
288     
289     RetainPtr<NSMenu> menu = [menuItem menu];
290     if (!_data->_isPerformingUpdate) {
291         if (_data->_menuList.find(menu) == notFound)
292             _data->_menuList.append(menu);
293         _data->_menuMap.add(commandName, EditCommandState(false, 0));
294         _data->_menuEntriesCount++;
295         _data->_page->validateMenuItem(commandName);
296     } else {
297         EditCommandState info = _data->_menuMap.take(commandName);
298         [menuItem setState:info.m_state];
299         if (_data->_menuMap.isEmpty())
300             _data->_isPerformingUpdate = false;
301         return info.m_isEnabled;
302     }
303
304     return YES;
305 }
306
307 // Events
308
309 // Override this so that AppKit will send us arrow keys as key down events so we can
310 // support them via the key bindings mechanism.
311 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
312 {
313     return YES;
314 }
315
316
317 #define EVENT_HANDLER(Selector, Type) \
318     - (void)Selector:(NSEvent *)theEvent \
319     { \
320         Web##Type##Event webEvent = WebEventFactory::createWeb##Type##Event(theEvent, self); \
321         _data->_page->handle##Type##Event(webEvent); \
322     }
323
324 EVENT_HANDLER(mouseDown, Mouse)
325 EVENT_HANDLER(mouseDragged, Mouse)
326 EVENT_HANDLER(mouseEntered, Mouse)
327 EVENT_HANDLER(mouseExited, Mouse)
328 EVENT_HANDLER(mouseMoved, Mouse)
329 EVENT_HANDLER(mouseUp, Mouse)
330 EVENT_HANDLER(otherMouseDown, Mouse)
331 EVENT_HANDLER(otherMouseDragged, Mouse)
332 EVENT_HANDLER(otherMouseMoved, Mouse)
333 EVENT_HANDLER(otherMouseUp, Mouse)
334 EVENT_HANDLER(rightMouseDown, Mouse)
335 EVENT_HANDLER(rightMouseDragged, Mouse)
336 EVENT_HANDLER(rightMouseMoved, Mouse)
337 EVENT_HANDLER(rightMouseUp, Mouse)
338 EVENT_HANDLER(scrollWheel, Wheel)
339
340 #undef EVENT_HANDLER
341
342 - (void)doCommandBySelector:(SEL)selector
343 {
344     if (selector != @selector(noop:))
345         _data->_commandsList.append(KeypressCommand(commandNameForSelector(selector)));
346 }
347
348 - (void)insertText:(id)string
349 {
350     _data->_commandsList.append(KeypressCommand("insertText", string));
351 }
352
353 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
354 {
355     if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) != NSCommandKeyMask)
356         return NO;
357     
358     // Here we special case cmd+b and cmd+i but not cmd+u, for historic reason.
359     // This should not be changed, since it could break some Mac applications that
360     // rely on this inherent behavior.
361     // See https://bugs.webkit.org/show_bug.cgi?id=24943
362     
363     NSString *string = [event characters];
364     if ([string caseInsensitiveCompare:@"b"] == NSOrderedSame) {
365         _data->_page->executeEditCommand("ToggleBold");
366         return YES;
367     }
368     if ([string caseInsensitiveCompare:@"i"] == NSOrderedSame) {
369         _data->_page->executeEditCommand("ToggleItalic");
370         return YES;
371     }
372     
373     return NO;
374 }
375
376 - (BOOL)performKeyEquivalent:(NSEvent *)event
377 {
378     // There's a chance that responding to this event will run a nested event loop, and
379     // fetching a new event might release the old one. Retaining and then autoreleasing
380     // the current event prevents that from causing a problem inside WebKit or AppKit code.
381     [[event retain] autorelease];
382     
383     BOOL eventWasSentToWebCore = (_data->_keyDownEventBeingResent == event);
384     BOOL ret = NO;
385     
386     [self retain];
387     
388     // Pass key combos through WebCore if there is a key binding available for
389     // this event. This lets web pages have a crack at intercepting key-modified keypresses.
390     // But don't do it if we have already handled the event.
391     // Pressing Esc results in a fake event being sent - don't pass it to WebCore.
392     if (!eventWasSentToWebCore && event == [NSApp currentEvent] && self == [[self window] firstResponder]) {
393         [_data->_keyDownEventBeingResent release];
394         _data->_keyDownEventBeingResent = nil;
395         
396         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, self));
397         return YES;
398     }
399     
400     ret = [self _handleStyleKeyEquivalent:event] || [super performKeyEquivalent:event];
401     
402     [self release];
403     
404     return ret;
405 }
406
407 - (void)_setEventBeingResent:(NSEvent *)event
408 {
409     _data->_keyDownEventBeingResent = [event retain];
410 }
411
412 - (void)_selectionChanged:(BOOL)isNone isEditable:(BOOL)isContentEditable isPassword:(BOOL)isPasswordField hasMarkedText:(BOOL)hasComposition
413 {
414     _data->_isSelectionNone = isNone;
415     _data->_isSelectionEditable = isContentEditable;
416     _data->_isSelectionInPasswordField = isPasswordField;
417     _data->_hasMarkedText = hasComposition;
418 }
419
420 - (Vector<KeypressCommand>&)_interceptKeyEvent:(NSEvent *)theEvent
421 {
422     _data->_commandsList.clear();
423     // interpretKeyEvents will trigger one or more calls to doCommandBySelector or setText
424     // that will populate the commandsList vector.
425     [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
426     
427     return _data->_commandsList;
428 }
429
430 - (void)keyUp:(NSEvent *)theEvent
431 {
432     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
433 }
434
435 - (void)keyDown:(NSEvent *)theEvent
436 {
437     // We could be receiving a key down from AppKit if we have re-sent an event
438     // that maps to an action that is currently unavailable (for example a copy when
439     // there is no range selection).
440     // If this is the case we should ignore the key down.
441     if (_data->_keyDownEventBeingResent == theEvent) {
442         [_data->_keyDownEventBeingResent release];
443         _data->_keyDownEventBeingResent = nil;
444         [super keyDown:theEvent];
445         return;
446     }
447     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
448 }
449
450 - (NSRange)selectedRange
451 {
452     return NSMakeRange(NSNotFound, 0);
453 }
454
455 - (BOOL)hasMarkedText
456 {
457     return _data->_hasMarkedText;
458 }
459
460 - (void)unmarkText
461 {
462     // Not implemented
463 }
464
465 - (NSArray *)validAttributesForMarkedText
466 {
467     static NSArray *validAttributes;
468     if (!validAttributes) {
469         validAttributes = [[NSArray alloc] initWithObjects:
470                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
471                            NSMarkedClauseSegmentAttributeName, NSTextInputReplacementRangeAttributeName, nil];
472         // NSText also supports the following attributes, but it's
473         // hard to tell which are really required for text input to
474         // work well; I have not seen any input method make use of them yet.
475         //     NSFontAttributeName, NSForegroundColorAttributeName,
476         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
477         CFRetain(validAttributes);
478     }
479     return validAttributes;
480 }
481
482 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
483 {
484     // Not implemented
485 }
486
487 - (NSRange)markedRange
488 {
489     // Not implemented
490     return NSMakeRange(0, 0);
491 }
492
493 - (NSAttributedString *)attributedSubstringFromRange:(NSRange)nsRange
494 {
495     // Not implemented
496     return nil;
497 }
498
499 - (NSInteger)conversationIdentifier
500 {
501     return (NSInteger)self;
502 }
503
504 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
505 {
506     // Not implemented
507     return NSNotFound;
508 }
509
510 - (NSRect)firstRectForCharacterRange:(NSRange)theRange
511
512     // Not implemented
513     return NSMakeRect(0, 0, 0, 0);
514 }
515
516 - (void)_updateActiveState
517 {
518     _data->_page->setActive([[self window] isKeyWindow]);
519 }
520
521 - (void)_updateWindowVisibility
522 {
523     _data->_page->updateWindowIsVisible(![[self window] isMiniaturized]);
524 }
525
526 - (BOOL)_ownsWindowGrowBox
527 {
528     NSWindow* window = [self window];
529     if (!window)
530         return NO;
531
532     NSView *superview = [self superview];
533     if (!superview)
534         return NO;
535
536     NSRect growBoxRect = [window _growBoxRect];
537     if (NSIsEmptyRect(growBoxRect))
538         return NO;
539
540     NSRect visibleRect = [self visibleRect];
541     if (NSIsEmptyRect(visibleRect))
542         return NO;
543
544     NSRect visibleRectInWindowCoords = [self convertRect:visibleRect toView:nil];
545     if (!NSIntersectsRect(growBoxRect, visibleRectInWindowCoords))
546         return NO;
547
548     return YES;
549 }
550
551 - (BOOL)_updateGrowBoxForWindowFrameChange
552 {
553     // Temporarily enable the resize indicator to make a the _ownsWindowGrowBox calculation work.
554     BOOL wasShowingIndicator = [[self window] showsResizeIndicator];
555     [[self window] setShowsResizeIndicator:YES];
556
557     BOOL ownsGrowBox = [self _ownsWindowGrowBox];
558     _data->_page->setWindowResizerSize(ownsGrowBox ? enclosingIntRect([[self window] _growBoxRect]).size() : IntSize());
559     
560     // Once WebCore can draw the window resizer, this should read:
561     // if (wasShowingIndicator)
562     //     [[self window] setShowsResizeIndicator:!ownsGrowBox];
563     [[self window] setShowsResizeIndicator:wasShowingIndicator];
564
565     return ownsGrowBox;
566 }
567
568 - (void)addWindowObserversForWindow:(NSWindow *)window
569 {
570     if (window) {
571         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
572                                                      name:NSWindowDidBecomeKeyNotification object:nil];
573         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
574                                                      name:NSWindowDidResignKeyNotification object:nil];
575         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) 
576                                                      name:NSWindowDidMiniaturizeNotification object:window];
577         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
578                                                      name:NSWindowDidDeminiaturizeNotification object:window];
579         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:)
580                                                      name:NSWindowDidMoveNotification object:window];
581         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:) 
582                                                      name:NSWindowDidResizeNotification object:window];
583     }
584 }
585
586 - (void)removeWindowObservers
587 {
588     NSWindow *window = [self window];
589     if (!window)
590         return;
591
592     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
593     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
594     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
595     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
596     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
597     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
598 }
599
600 static bool isViewVisible(NSView *view)
601 {
602     if (![view window])
603         return false;
604     
605     if ([view isHiddenOrHasHiddenAncestor])
606         return false;
607     
608     return true;
609 }
610
611 - (void)_updateVisibility
612 {
613     _data->_page->setIsInWindow([self window]);
614     if (DrawingAreaProxy* area = _data->_page->drawingArea())
615         area->setPageIsVisible(isViewVisible(self));
616 }
617
618 - (void)viewWillMoveToWindow:(NSWindow *)window
619 {
620     if (window != [self window]) {
621         [self removeWindowObservers];
622         [self addWindowObserversForWindow:window];
623     }
624 }
625
626 - (void)viewDidMoveToWindow
627 {
628     // We want to make sure to update the active state while hidden, so if the view is about to become visible, we
629     // update the active state first and then make it visible. If the view is about to be hidden, we hide it first and then
630     // update the active state.
631     if ([self window]) {
632         [self _updateActiveState];
633         [self _updateVisibility];
634         [self _updateWindowVisibility];
635         [self _updateWindowAndViewFrames];
636     } else {
637         [self _updateVisibility];
638         [self _updateActiveState];
639     }
640
641 }
642
643 - (void)_windowDidBecomeKey:(NSNotification *)notification
644 {
645     NSWindow *keyWindow = [notification object];
646     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
647         [self _updateActiveState];
648 }
649
650 - (void)_windowDidResignKey:(NSNotification *)notification
651 {
652     NSWindow *formerKeyWindow = [notification object];
653     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet])
654         [self _updateActiveState];
655 }
656
657 - (void)_windowDidMiniaturize:(NSNotification *)notification
658 {
659     [self _updateWindowVisibility];
660 }
661
662 - (void)_windowDidDeminiaturize:(NSNotification *)notification
663 {
664     [self _updateWindowVisibility];
665 }
666
667 - (void)_windowFrameDidChange:(NSNotification *)notification
668 {
669     [self _updateWindowAndViewFrames];
670 }
671
672 - (void)drawRect:(NSRect)rect
673 {    
674     [[NSColor whiteColor] set];
675     NSRectFill(rect);
676
677     if (_data->_page->isValid() && _data->_page->drawingArea()) {
678         CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
679         _data->_page->drawingArea()->paint(IntRect(rect), context);
680         _data->_page->didDraw();
681     }
682 }
683
684 - (BOOL)isOpaque 
685 {
686     // FIXME: Return NO if we have a transparent background.
687     return YES;
688 }
689
690 - (void)viewDidHide
691 {
692     [self _updateVisibility];
693 }
694
695 - (void)viewDidUnhide
696 {
697     [self _updateVisibility];
698 }
699
700 - (NSView *)hitTest:(NSPoint)point
701 {
702     NSView *hitView = [super hitTest:point];
703 #if USE(ACCELERATED_COMPOSITING)
704     if (hitView && _data && hitView == _data->_layerHostingView)
705         hitView = self;
706 #endif
707     return hitView;
708 }
709
710 @end
711
712 @implementation WKView (Internal)
713
714 - (void)_processDidCrash
715 {
716     [self setNeedsDisplay:YES];
717 }
718
719 - (void)_didRelaunchProcess
720 {
721     _data->_page->reinitializeWebPage(IntSize([self bounds].size));
722
723     _data->_page->setActive([[self window] isKeyWindow]);
724     _data->_page->setFocused([[self window] firstResponder] == self);
725     
726     [self setNeedsDisplay:YES];
727 }
728
729 - (void)_takeFocus:(BOOL)forward
730 {
731     if (forward)
732         [[self window] selectKeyViewFollowingView:self];
733     else
734         [[self window] selectKeyViewPrecedingView:self];
735 }
736
737 - (void)_setCursor:(NSCursor *)cursor
738 {
739     if ([NSCursor currentCursor] == cursor)
740         return;
741     [cursor set];
742 }
743
744 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
745 {
746     ASSERT(_data->_menuEntriesCount);
747     _data->_menuMap.set(commandName, EditCommandState(isEnabled, newState));
748     if (--_data->_menuEntriesCount)
749         return;
750     
751     // All the menu entries have been validated.
752     // Calling update will trigger the validation
753     // to be performed with the acquired data.
754     _data->_isPerformingUpdate = true;
755     for (size_t i = 0; i < _data->_menuList.size(); i++)
756         [_data->_menuList[i].get() update];
757     
758     _data->_menuList.clear();
759 }
760
761 - (NSRect)_convertToDeviceSpace:(NSRect)rect
762 {
763     return toDeviceSpace(rect, [self window]);
764 }
765
766 - (NSRect)_convertToUserSpace:(NSRect)rect
767 {
768     return toUserSpace(rect, [self window]);
769 }
770
771 // Any non-zero value will do, but using something recognizable might help us debug some day.
772 #define TRACKING_RECT_TAG 0xBADFACE
773
774 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
775 {
776     ASSERT(_data->_trackingRectOwner == nil);
777     _data->_trackingRectOwner = owner;
778     _data->_trackingRectUserData = data;
779     return TRACKING_RECT_TAG;
780 }
781
782 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
783 {
784     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
785     ASSERT(_data->_trackingRectOwner == nil);
786     _data->_trackingRectOwner = owner;
787     _data->_trackingRectUserData = data;
788     return TRACKING_RECT_TAG;
789 }
790
791 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
792 {
793     ASSERT(count == 1);
794     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
795     ASSERT(_data->_trackingRectOwner == nil);
796     _data->_trackingRectOwner = owner;
797     _data->_trackingRectUserData = userDataList[0];
798     trackingNums[0] = TRACKING_RECT_TAG;
799 }
800
801 - (void)removeTrackingRect:(NSTrackingRectTag)tag
802 {
803     if (tag == 0)
804         return;
805     
806     if (_data && (tag == TRACKING_RECT_TAG)) {
807         _data->_trackingRectOwner = nil;
808         return;
809     }
810     
811     if (_data && (tag == _data->_lastToolTipTag)) {
812         [super removeTrackingRect:tag];
813         _data->_lastToolTipTag = 0;
814         return;
815     }
816     
817     // If any other tracking rect is being removed, we don't know how it was created
818     // and it's possible there's a leak involved (see 3500217)
819     ASSERT_NOT_REACHED();
820 }
821
822 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
823 {
824     int i;
825     for (i = 0; i < count; ++i) {
826         int tag = tags[i];
827         if (tag == 0)
828             continue;
829         ASSERT(tag == TRACKING_RECT_TAG);
830         if (_data != nil) {
831             _data->_trackingRectOwner = nil;
832         }
833     }
834 }
835
836 - (void)_sendToolTipMouseExited
837 {
838     // Nothing matters except window, trackingNumber, and userData.
839     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
840         location:NSMakePoint(0, 0)
841         modifierFlags:0
842         timestamp:0
843         windowNumber:[[self window] windowNumber]
844         context:NULL
845         eventNumber:0
846         trackingNumber:TRACKING_RECT_TAG
847         userData:_data->_trackingRectUserData];
848     [_data->_trackingRectOwner mouseExited:fakeEvent];
849 }
850
851 - (void)_sendToolTipMouseEntered
852 {
853     // Nothing matters except window, trackingNumber, and userData.
854     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
855         location:NSMakePoint(0, 0)
856         modifierFlags:0
857         timestamp:0
858         windowNumber:[[self window] windowNumber]
859         context:NULL
860         eventNumber:0
861         trackingNumber:TRACKING_RECT_TAG
862         userData:_data->_trackingRectUserData];
863     [_data->_trackingRectOwner mouseEntered:fakeEvent];
864 }
865
866 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
867 {
868     return nsStringFromWebCoreString(_data->_page->toolTip());
869 }
870
871 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
872 {
873     if (oldToolTip)
874         [self _sendToolTipMouseExited];
875
876     if (newToolTip && [newToolTip length] > 0) {
877         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
878         [self removeAllToolTips];
879         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
880         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
881         [self _sendToolTipMouseEntered];
882     }
883 }
884
885 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut
886 {
887     if (!findIndicator) {
888         _data->_findIndicatorWindow = 0;
889         return;
890     }
891
892     if (!_data->_findIndicatorWindow)
893         _data->_findIndicatorWindow = FindIndicatorWindow::create(self);
894
895     _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut);
896 }
897
898 #if USE(ACCELERATED_COMPOSITING)
899 - (void)_startAcceleratedCompositing:(CALayer *)rootLayer
900 {
901     if (!_data->_layerHostingView) {
902         NSView *hostingView = [[NSView alloc] initWithFrame:[self bounds]];
903 #if !defined(BUILDING_ON_LEOPARD)
904         [hostingView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
905 #endif
906         
907         [self addSubview:hostingView];
908         [hostingView release];
909         _data->_layerHostingView = hostingView;
910     }
911
912     // Make a container layer, which will get sized/positioned by AppKit and CA.
913     CALayer *viewLayer = [CALayer layer];
914
915 #ifndef NDEBUG
916     [viewLayer setName:@"hosting layer"];
917 #endif
918
919 #if defined(BUILDING_ON_LEOPARD)
920     // Turn off default animations.
921     NSNull *nullValue = [NSNull null];
922     NSDictionary *actions = [NSDictionary dictionaryWithObjectsAndKeys:
923                              nullValue, @"anchorPoint",
924                              nullValue, @"bounds",
925                              nullValue, @"contents",
926                              nullValue, @"contentsRect",
927                              nullValue, @"opacity",
928                              nullValue, @"position",
929                              nullValue, @"sublayerTransform",
930                              nullValue, @"sublayers",
931                              nullValue, @"transform",
932                              nil];
933     [viewLayer setStyle:[NSDictionary dictionaryWithObject:actions forKey:@"actions"]];
934 #endif
935
936 #if !defined(BUILDING_ON_LEOPARD)
937     // If we aren't in the window yet, we'll use the screen's scale factor now, and reset the scale 
938     // via -viewDidMoveToWindow.
939     CGFloat scaleFactor = [self window] ? [[self window] userSpaceScaleFactor] : [[NSScreen mainScreen] userSpaceScaleFactor];
940     [viewLayer setTransform:CATransform3DMakeScale(scaleFactor, scaleFactor, 1)];
941 #endif
942
943     [_data->_layerHostingView setLayer:viewLayer];
944     [_data->_layerHostingView setWantsLayer:YES];
945     
946     // Parent our root layer in the container layer
947     [viewLayer addSublayer:rootLayer];
948 }
949
950 - (void)_stopAcceleratedCompositing
951 {
952     if (_data->_layerHostingView) {
953         [_data->_layerHostingView setLayer:nil];
954         [_data->_layerHostingView setWantsLayer:NO];
955         [_data->_layerHostingView removeFromSuperview];
956         _data->_layerHostingView = nil;
957     }
958 }
959
960 - (void)_switchToDrawingAreaTypeIfNecessary:(DrawingAreaInfo::Type)type
961 {
962     DrawingAreaInfo::Type existingDrawingAreaType = _data->_page->drawingArea() ? _data->_page->drawingArea()->info().type : DrawingAreaInfo::None;
963     if (existingDrawingAreaType == type)
964         return;
965
966     OwnPtr<DrawingAreaProxy> newDrawingArea;
967     switch (type) {
968         case DrawingAreaInfo::None:
969             break;
970         case DrawingAreaInfo::ChunkedUpdate: {
971             newDrawingArea = ChunkedUpdateDrawingAreaProxy::create(self);
972             break;
973         }
974         case DrawingAreaInfo::LayerBacked: {
975             newDrawingArea = LayerBackedDrawingAreaProxy::create(self);
976             break;
977         }
978     }
979
980     newDrawingArea->setSize(IntSize([self frame].size));
981
982     _data->_page->drawingArea()->detachCompositingContext();
983     _data->_page->setDrawingArea(newDrawingArea.release());
984 }
985
986 - (void)_pageDidEnterAcceleratedCompositing
987 {
988     [self _switchToDrawingAreaTypeIfNecessary:DrawingAreaInfo::LayerBacked];
989 }
990
991 - (void)_pageDidLeaveAcceleratedCompositing
992 {
993     // FIXME: we may want to avoid flipping back to the non-layer-backed drawing area until the next page load, to avoid thrashing.
994     [self _switchToDrawingAreaTypeIfNecessary:DrawingAreaInfo::ChunkedUpdate];
995 }
996 #endif // USE(ACCELERATED_COMPOSITING)
997
998 @end