3f28f9927bc8fddb7cdfcc9778f5874ffef858d3
[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
277 #undef WEBCORE_COMMAND
278
279 // Menu items validation
280
281 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
282 {
283     String commandName = commandNameForSelector([item action]);
284     NSMenuItem *menuItem = (NSMenuItem *)item;
285     if (![menuItem isKindOfClass:[NSMenuItem class]])
286         return NO; // FIXME: We need to be able to handle other user interface elements.
287     
288     RetainPtr<NSMenu> menu = [menuItem menu];
289     if (!_data->_isPerformingUpdate) {
290         if (_data->_menuList.find(menu) == notFound)
291             _data->_menuList.append(menu);
292         _data->_menuMap.add(commandName, EditCommandState(false, 0));
293         _data->_menuEntriesCount++;
294         _data->_page->validateMenuItem(commandName);
295     } else {
296         EditCommandState info = _data->_menuMap.take(commandName);
297         [menuItem setState:info.m_state];
298         if (_data->_menuMap.isEmpty())
299             _data->_isPerformingUpdate = false;
300         return info.m_isEnabled;
301     }
302
303     return YES;
304 }
305
306 // Events
307
308 // Override this so that AppKit will send us arrow keys as key down events so we can
309 // support them via the key bindings mechanism.
310 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
311 {
312     return YES;
313 }
314
315
316 #define EVENT_HANDLER(Selector, Type) \
317     - (void)Selector:(NSEvent *)theEvent \
318     { \
319         Web##Type##Event webEvent = WebEventFactory::createWeb##Type##Event(theEvent, self); \
320         _data->_page->handle##Type##Event(webEvent); \
321     }
322
323 EVENT_HANDLER(mouseDown, Mouse)
324 EVENT_HANDLER(mouseDragged, Mouse)
325 EVENT_HANDLER(mouseEntered, Mouse)
326 EVENT_HANDLER(mouseExited, Mouse)
327 EVENT_HANDLER(mouseMoved, Mouse)
328 EVENT_HANDLER(mouseUp, Mouse)
329 EVENT_HANDLER(otherMouseDown, Mouse)
330 EVENT_HANDLER(otherMouseDragged, Mouse)
331 EVENT_HANDLER(otherMouseMoved, Mouse)
332 EVENT_HANDLER(otherMouseUp, Mouse)
333 EVENT_HANDLER(rightMouseDown, Mouse)
334 EVENT_HANDLER(rightMouseDragged, Mouse)
335 EVENT_HANDLER(rightMouseMoved, Mouse)
336 EVENT_HANDLER(rightMouseUp, Mouse)
337 EVENT_HANDLER(scrollWheel, Wheel)
338
339 #undef EVENT_HANDLER
340
341 - (void)doCommandBySelector:(SEL)selector
342 {
343     if (selector != @selector(noop:))
344         _data->_commandsList.append(KeypressCommand(commandNameForSelector(selector)));
345 }
346
347 - (void)insertText:(id)string
348 {
349     _data->_commandsList.append(KeypressCommand("insertText", string));
350 }
351
352 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
353 {
354     if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) != NSCommandKeyMask)
355         return NO;
356     
357     // Here we special case cmd+b and cmd+i but not cmd+u, for historic reason.
358     // This should not be changed, since it could break some Mac applications that
359     // rely on this inherent behavior.
360     // See https://bugs.webkit.org/show_bug.cgi?id=24943
361     
362     NSString *string = [event characters];
363     if ([string caseInsensitiveCompare:@"b"] == NSOrderedSame) {
364         _data->_page->executeEditCommand("ToggleBold");
365         return YES;
366     }
367     if ([string caseInsensitiveCompare:@"i"] == NSOrderedSame) {
368         _data->_page->executeEditCommand("ToggleItalic");
369         return YES;
370     }
371     
372     return NO;
373 }
374
375 - (BOOL)performKeyEquivalent:(NSEvent *)event
376 {
377     // There's a chance that responding to this event will run a nested event loop, and
378     // fetching a new event might release the old one. Retaining and then autoreleasing
379     // the current event prevents that from causing a problem inside WebKit or AppKit code.
380     [[event retain] autorelease];
381     
382     BOOL eventWasSentToWebCore = (_data->_keyDownEventBeingResent == event);
383     BOOL ret = NO;
384     
385     [self retain];
386     
387     // Pass key combos through WebCore if there is a key binding available for
388     // this event. This lets web pages have a crack at intercepting key-modified keypresses.
389     // But don't do it if we have already handled the event.
390     // Pressing Esc results in a fake event being sent - don't pass it to WebCore.
391     if (!eventWasSentToWebCore && event == [NSApp currentEvent] && self == [[self window] firstResponder]) {
392         [_data->_keyDownEventBeingResent release];
393         _data->_keyDownEventBeingResent = nil;
394         
395         _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, self));
396         return YES;
397     }
398     
399     ret = [self _handleStyleKeyEquivalent:event] || [super performKeyEquivalent:event];
400     
401     [self release];
402     
403     return ret;
404 }
405
406 - (void)_setEventBeingResent:(NSEvent *)event
407 {
408     _data->_keyDownEventBeingResent = [event retain];
409 }
410
411 - (void)_selectionChanged:(BOOL)isNone isEditable:(BOOL)isContentEditable isPassword:(BOOL)isPasswordField hasMarkedText:(BOOL)hasComposition
412 {
413     _data->_isSelectionNone = isNone;
414     _data->_isSelectionEditable = isContentEditable;
415     _data->_isSelectionInPasswordField = isPasswordField;
416     _data->_hasMarkedText = hasComposition;
417 }
418
419 - (Vector<KeypressCommand>&)_interceptKeyEvent:(NSEvent *)theEvent
420 {
421     _data->_commandsList.clear();
422     // interpretKeyEvents will trigger one or more calls to doCommandBySelector or setText
423     // that will populate the commandsList vector.
424     [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
425     
426     return _data->_commandsList;
427 }
428
429 - (void)keyUp:(NSEvent *)theEvent
430 {
431     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
432 }
433
434 - (void)keyDown:(NSEvent *)theEvent
435 {
436     // We could be receiving a key down from AppKit if we have re-sent an event
437     // that maps to an action that is currently unavailable (for example a copy when
438     // there is no range selection).
439     // If this is the case we should ignore the key down.
440     if (_data->_keyDownEventBeingResent == theEvent) {
441         [_data->_keyDownEventBeingResent release];
442         _data->_keyDownEventBeingResent = nil;
443         [super keyDown:theEvent];
444         return;
445     }
446     _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self));
447 }
448
449 - (NSRange)selectedRange
450 {
451     return NSMakeRange(NSNotFound, 0);
452 }
453
454 - (BOOL)hasMarkedText
455 {
456     return _data->_hasMarkedText;
457 }
458
459 - (void)unmarkText
460 {
461     // Not implemented
462 }
463
464 - (NSArray *)validAttributesForMarkedText
465 {
466     static NSArray *validAttributes;
467     if (!validAttributes) {
468         validAttributes = [[NSArray alloc] initWithObjects:
469                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
470                            NSMarkedClauseSegmentAttributeName, NSTextInputReplacementRangeAttributeName, nil];
471         // NSText also supports the following attributes, but it's
472         // hard to tell which are really required for text input to
473         // work well; I have not seen any input method make use of them yet.
474         //     NSFontAttributeName, NSForegroundColorAttributeName,
475         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
476         CFRetain(validAttributes);
477     }
478     return validAttributes;
479 }
480
481 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
482 {
483     // Not implemented
484 }
485
486 - (NSRange)markedRange
487 {
488     // Not implemented
489     return NSMakeRange(0, 0);
490 }
491
492 - (NSAttributedString *)attributedSubstringFromRange:(NSRange)nsRange
493 {
494     // Not implemented
495     return nil;
496 }
497
498 - (NSInteger)conversationIdentifier
499 {
500     return (NSInteger)self;
501 }
502
503 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
504 {
505     // Not implemented
506     return NSNotFound;
507 }
508
509 - (NSRect)firstRectForCharacterRange:(NSRange)theRange
510
511     // Not implemented
512     return NSMakeRect(0, 0, 0, 0);
513 }
514
515 - (void)_updateActiveState
516 {
517     _data->_page->setActive([[self window] isKeyWindow]);
518 }
519
520 - (void)_updateWindowVisibility
521 {
522     _data->_page->updateWindowIsVisible(![[self window] isMiniaturized]);
523 }
524
525 - (BOOL)_ownsWindowGrowBox
526 {
527     NSWindow* window = [self window];
528     if (!window)
529         return NO;
530
531     NSView *superview = [self superview];
532     if (!superview)
533         return NO;
534
535     NSRect growBoxRect = [window _growBoxRect];
536     if (NSIsEmptyRect(growBoxRect))
537         return NO;
538
539     NSRect visibleRect = [self visibleRect];
540     if (NSIsEmptyRect(visibleRect))
541         return NO;
542
543     NSRect visibleRectInWindowCoords = [self convertRect:visibleRect toView:nil];
544     if (!NSIntersectsRect(growBoxRect, visibleRectInWindowCoords))
545         return NO;
546
547     return YES;
548 }
549
550 - (BOOL)_updateGrowBoxForWindowFrameChange
551 {
552     // Temporarily enable the resize indicator to make a the _ownsWindowGrowBox calculation work.
553     BOOL wasShowingIndicator = [[self window] showsResizeIndicator];
554     [[self window] setShowsResizeIndicator:YES];
555
556     BOOL ownsGrowBox = [self _ownsWindowGrowBox];
557     _data->_page->setWindowResizerSize(ownsGrowBox ? enclosingIntRect([[self window] _growBoxRect]).size() : IntSize());
558     
559     // Once WebCore can draw the window resizer, this should read:
560     // if (wasShowingIndicator)
561     //     [[self window] setShowsResizeIndicator:!ownsGrowBox];
562     [[self window] setShowsResizeIndicator:wasShowingIndicator];
563
564     return ownsGrowBox;
565 }
566
567 - (void)addWindowObserversForWindow:(NSWindow *)window
568 {
569     if (window) {
570         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
571                                                      name:NSWindowDidBecomeKeyNotification object:nil];
572         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
573                                                      name:NSWindowDidResignKeyNotification object:nil];
574         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) 
575                                                      name:NSWindowDidMiniaturizeNotification object:window];
576         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:)
577                                                      name:NSWindowDidDeminiaturizeNotification object:window];
578         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:)
579                                                      name:NSWindowDidMoveNotification object:window];
580         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowFrameDidChange:) 
581                                                      name:NSWindowDidResizeNotification object:window];
582     }
583 }
584
585 - (void)removeWindowObservers
586 {
587     NSWindow *window = [self window];
588     if (!window)
589         return;
590
591     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
592     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
593     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window];
594     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window];
595     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window];
596     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window];
597 }
598
599 static bool isViewVisible(NSView *view)
600 {
601     if (![view window])
602         return false;
603     
604     if ([view isHiddenOrHasHiddenAncestor])
605         return false;
606     
607     return true;
608 }
609
610 - (void)_updateVisibility
611 {
612     _data->_page->setIsInWindow([self window]);
613     if (DrawingAreaProxy* area = _data->_page->drawingArea())
614         area->setPageIsVisible(isViewVisible(self));
615 }
616
617 - (void)viewWillMoveToWindow:(NSWindow *)window
618 {
619     if (window != [self window]) {
620         [self removeWindowObservers];
621         [self addWindowObserversForWindow:window];
622     }
623 }
624
625 - (void)viewDidMoveToWindow
626 {
627     // We want to make sure to update the active state while hidden, so if the view is about to become visible, we
628     // update the active state first and then make it visible. If the view is about to be hidden, we hide it first and then
629     // update the active state.
630     if ([self window]) {
631         [self _updateActiveState];
632         [self _updateVisibility];
633         [self _updateWindowVisibility];
634         [self _updateWindowAndViewFrames];
635     } else {
636         [self _updateVisibility];
637         [self _updateActiveState];
638     }
639
640 }
641
642 - (void)_windowDidBecomeKey:(NSNotification *)notification
643 {
644     NSWindow *keyWindow = [notification object];
645     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
646         [self _updateActiveState];
647 }
648
649 - (void)_windowDidResignKey:(NSNotification *)notification
650 {
651     NSWindow *formerKeyWindow = [notification object];
652     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet])
653         [self _updateActiveState];
654 }
655
656 - (void)_windowDidMiniaturize:(NSNotification *)notification
657 {
658     [self _updateWindowVisibility];
659 }
660
661 - (void)_windowDidDeminiaturize:(NSNotification *)notification
662 {
663     [self _updateWindowVisibility];
664 }
665
666 - (void)_windowFrameDidChange:(NSNotification *)notification
667 {
668     [self _updateWindowAndViewFrames];
669 }
670
671 - (void)drawRect:(NSRect)rect
672 {    
673     [[NSColor whiteColor] set];
674     NSRectFill(rect);
675
676     if (_data->_page->isValid() && _data->_page->drawingArea()) {
677         CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
678         _data->_page->drawingArea()->paint(IntRect(rect), context);
679         _data->_page->didDraw();
680     }
681 }
682
683 - (BOOL)isOpaque 
684 {
685     // FIXME: Return NO if we have a transparent background.
686     return YES;
687 }
688
689 - (void)viewDidHide
690 {
691     [self _updateVisibility];
692 }
693
694 - (void)viewDidUnhide
695 {
696     [self _updateVisibility];
697 }
698
699 - (NSView *)hitTest:(NSPoint)point
700 {
701     NSView *hitView = [super hitTest:point];
702 #if USE(ACCELERATED_COMPOSITING)
703     if (hitView && _data && hitView == _data->_layerHostingView)
704         hitView = self;
705 #endif
706     return hitView;
707 }
708
709 @end
710
711 @implementation WKView (Internal)
712
713 - (void)_processDidCrash
714 {
715     [self setNeedsDisplay:YES];
716 }
717
718 - (void)_didRelaunchProcess
719 {
720     _data->_page->reinitializeWebPage(IntSize([self bounds].size));
721
722     _data->_page->setActive([[self window] isKeyWindow]);
723     _data->_page->setFocused([[self window] firstResponder] == self);
724     
725     [self setNeedsDisplay:YES];
726 }
727
728 - (void)_takeFocus:(BOOL)forward
729 {
730     if (forward)
731         [[self window] selectKeyViewFollowingView:self];
732     else
733         [[self window] selectKeyViewPrecedingView:self];
734 }
735
736 - (void)_setCursor:(NSCursor *)cursor
737 {
738     if ([NSCursor currentCursor] == cursor)
739         return;
740     [cursor set];
741 }
742
743 - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState
744 {
745     ASSERT(_data->_menuEntriesCount);
746     _data->_menuMap.set(commandName, EditCommandState(isEnabled, newState));
747     if (--_data->_menuEntriesCount)
748         return;
749     
750     // All the menu entries have been validated.
751     // Calling update will trigger the validation
752     // to be performed with the acquired data.
753     _data->_isPerformingUpdate = true;
754     for (size_t i = 0; i < _data->_menuList.size(); i++)
755         [_data->_menuList[i].get() update];
756     
757     _data->_menuList.clear();
758 }
759
760 - (NSRect)_convertToDeviceSpace:(NSRect)rect
761 {
762     return toDeviceSpace(rect, [self window]);
763 }
764
765 - (NSRect)_convertToUserSpace:(NSRect)rect
766 {
767     return toUserSpace(rect, [self window]);
768 }
769
770 // Any non-zero value will do, but using something recognizable might help us debug some day.
771 #define TRACKING_RECT_TAG 0xBADFACE
772
773 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
774 {
775     ASSERT(_data->_trackingRectOwner == nil);
776     _data->_trackingRectOwner = owner;
777     _data->_trackingRectUserData = data;
778     return TRACKING_RECT_TAG;
779 }
780
781 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
782 {
783     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
784     ASSERT(_data->_trackingRectOwner == nil);
785     _data->_trackingRectOwner = owner;
786     _data->_trackingRectUserData = data;
787     return TRACKING_RECT_TAG;
788 }
789
790 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
791 {
792     ASSERT(count == 1);
793     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
794     ASSERT(_data->_trackingRectOwner == nil);
795     _data->_trackingRectOwner = owner;
796     _data->_trackingRectUserData = userDataList[0];
797     trackingNums[0] = TRACKING_RECT_TAG;
798 }
799
800 - (void)removeTrackingRect:(NSTrackingRectTag)tag
801 {
802     if (tag == 0)
803         return;
804     
805     if (_data && (tag == TRACKING_RECT_TAG)) {
806         _data->_trackingRectOwner = nil;
807         return;
808     }
809     
810     if (_data && (tag == _data->_lastToolTipTag)) {
811         [super removeTrackingRect:tag];
812         _data->_lastToolTipTag = 0;
813         return;
814     }
815     
816     // If any other tracking rect is being removed, we don't know how it was created
817     // and it's possible there's a leak involved (see 3500217)
818     ASSERT_NOT_REACHED();
819 }
820
821 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
822 {
823     int i;
824     for (i = 0; i < count; ++i) {
825         int tag = tags[i];
826         if (tag == 0)
827             continue;
828         ASSERT(tag == TRACKING_RECT_TAG);
829         if (_data != nil) {
830             _data->_trackingRectOwner = nil;
831         }
832     }
833 }
834
835 - (void)_sendToolTipMouseExited
836 {
837     // Nothing matters except window, trackingNumber, and userData.
838     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
839         location:NSMakePoint(0, 0)
840         modifierFlags:0
841         timestamp:0
842         windowNumber:[[self window] windowNumber]
843         context:NULL
844         eventNumber:0
845         trackingNumber:TRACKING_RECT_TAG
846         userData:_data->_trackingRectUserData];
847     [_data->_trackingRectOwner mouseExited:fakeEvent];
848 }
849
850 - (void)_sendToolTipMouseEntered
851 {
852     // Nothing matters except window, trackingNumber, and userData.
853     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
854         location:NSMakePoint(0, 0)
855         modifierFlags:0
856         timestamp:0
857         windowNumber:[[self window] windowNumber]
858         context:NULL
859         eventNumber:0
860         trackingNumber:TRACKING_RECT_TAG
861         userData:_data->_trackingRectUserData];
862     [_data->_trackingRectOwner mouseEntered:fakeEvent];
863 }
864
865 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
866 {
867     return nsStringFromWebCoreString(_data->_page->toolTip());
868 }
869
870 - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip
871 {
872     if (oldToolTip)
873         [self _sendToolTipMouseExited];
874
875     if (newToolTip && [newToolTip length] > 0) {
876         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
877         [self removeAllToolTips];
878         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
879         _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
880         [self _sendToolTipMouseEntered];
881     }
882 }
883
884 - (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut
885 {
886     if (!findIndicator) {
887         _data->_findIndicatorWindow = 0;
888         return;
889     }
890
891     if (!_data->_findIndicatorWindow)
892         _data->_findIndicatorWindow = FindIndicatorWindow::create(self);
893
894     _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut);
895 }
896
897 #if USE(ACCELERATED_COMPOSITING)
898 - (void)_startAcceleratedCompositing:(CALayer *)rootLayer
899 {
900     if (!_data->_layerHostingView) {
901         NSView *hostingView = [[NSView alloc] initWithFrame:[self bounds]];
902 #if !defined(BUILDING_ON_LEOPARD)
903         [hostingView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
904 #endif
905         
906         [self addSubview:hostingView];
907         [hostingView release];
908         _data->_layerHostingView = hostingView;
909     }
910
911     // Make a container layer, which will get sized/positioned by AppKit and CA.
912     CALayer *viewLayer = [CALayer layer];
913
914 #ifndef NDEBUG
915     [viewLayer setName:@"hosting layer"];
916 #endif
917
918 #if defined(BUILDING_ON_LEOPARD)
919     // Turn off default animations.
920     NSNull *nullValue = [NSNull null];
921     NSDictionary *actions = [NSDictionary dictionaryWithObjectsAndKeys:
922                              nullValue, @"anchorPoint",
923                              nullValue, @"bounds",
924                              nullValue, @"contents",
925                              nullValue, @"contentsRect",
926                              nullValue, @"opacity",
927                              nullValue, @"position",
928                              nullValue, @"sublayerTransform",
929                              nullValue, @"sublayers",
930                              nullValue, @"transform",
931                              nil];
932     [viewLayer setStyle:[NSDictionary dictionaryWithObject:actions forKey:@"actions"]];
933 #endif
934
935 #if !defined(BUILDING_ON_LEOPARD)
936     // If we aren't in the window yet, we'll use the screen's scale factor now, and reset the scale 
937     // via -viewDidMoveToWindow.
938     CGFloat scaleFactor = [self window] ? [[self window] userSpaceScaleFactor] : [[NSScreen mainScreen] userSpaceScaleFactor];
939     [viewLayer setTransform:CATransform3DMakeScale(scaleFactor, scaleFactor, 1)];
940 #endif
941
942     [_data->_layerHostingView setLayer:viewLayer];
943     [_data->_layerHostingView setWantsLayer:YES];
944     
945     // Parent our root layer in the container layer
946     [viewLayer addSublayer:rootLayer];
947 }
948
949 - (void)_stopAcceleratedCompositing
950 {
951     if (_data->_layerHostingView) {
952         [_data->_layerHostingView setLayer:nil];
953         [_data->_layerHostingView setWantsLayer:NO];
954         [_data->_layerHostingView removeFromSuperview];
955         _data->_layerHostingView = nil;
956     }
957 }
958
959 - (void)_switchToDrawingAreaTypeIfNecessary:(DrawingAreaInfo::Type)type
960 {
961     DrawingAreaInfo::Type existingDrawingAreaType = _data->_page->drawingArea() ? _data->_page->drawingArea()->info().type : DrawingAreaInfo::None;
962     if (existingDrawingAreaType == type)
963         return;
964
965     OwnPtr<DrawingAreaProxy> newDrawingArea;
966     switch (type) {
967         case DrawingAreaInfo::None:
968             break;
969         case DrawingAreaInfo::ChunkedUpdate: {
970             newDrawingArea = ChunkedUpdateDrawingAreaProxy::create(self);
971             break;
972         }
973         case DrawingAreaInfo::LayerBacked: {
974             newDrawingArea = LayerBackedDrawingAreaProxy::create(self);
975             break;
976         }
977     }
978
979     newDrawingArea->setSize(IntSize([self frame].size));
980
981     _data->_page->drawingArea()->detachCompositingContext();
982     _data->_page->setDrawingArea(newDrawingArea.release());
983 }
984
985 - (void)_pageDidEnterAcceleratedCompositing
986 {
987     [self _switchToDrawingAreaTypeIfNecessary:DrawingAreaInfo::LayerBacked];
988 }
989
990 - (void)_pageDidLeaveAcceleratedCompositing
991 {
992     // FIXME: we may want to avoid flipping back to the non-layer-backed drawing area until the next page load, to avoid thrashing.
993     [self _switchToDrawingAreaTypeIfNecessary:DrawingAreaInfo::ChunkedUpdate];
994 }
995 #endif // USE(ACCELERATED_COMPOSITING)
996
997 @end