2 * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Nuanti Ltd.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "FocusController.h"
30 #include "AXObjectCache.h"
32 #include "ComposedShadowTreeWalker.h"
35 #include "EditorClient.h"
37 #include "ElementShadow.h"
39 #include "EventHandler.h"
40 #include "EventNames.h"
41 #include "ExceptionCode.h"
43 #include "FrameSelection.h"
44 #include "FrameTree.h"
45 #include "FrameView.h"
46 #include "HTMLAreaElement.h"
47 #include "HTMLImageElement.h"
48 #include "HTMLNames.h"
49 #include "HitTestResult.h"
50 #include "KeyboardEvent.h"
53 #include "RenderObject.h"
54 #include "RenderWidget.h"
55 #include "ScrollAnimator.h"
57 #include "ShadowRoot.h"
58 #include "SpatialNavigation.h"
60 #include "htmlediting.h" // For firstPositionInOrBeforeNode
65 using namespace HTMLNames;
68 static inline ComposedShadowTreeWalker walkerFrom(const Node* node)
70 return ComposedShadowTreeWalker(node, ComposedShadowTreeWalker::DoNotCrossUpperBoundary);
73 static inline ComposedShadowTreeWalker walkerFromNext(const Node* node)
75 ComposedShadowTreeWalker walker = ComposedShadowTreeWalker(node, ComposedShadowTreeWalker::DoNotCrossUpperBoundary);
80 static inline ComposedShadowTreeWalker walkerFromPrevious(const Node* node)
82 ComposedShadowTreeWalker walker = ComposedShadowTreeWalker(node, ComposedShadowTreeWalker::DoNotCrossUpperBoundary);
87 static inline Node* nextNode(const Node* node)
89 return walkerFromNext(node).get();
92 static inline Node* previousNode(const Node* node)
94 return walkerFromPrevious(node).get();
97 FocusNavigationScope::FocusNavigationScope(TreeScope* treeScope)
98 : m_rootTreeScope(treeScope)
101 ASSERT(!treeScope->rootNode()->isShadowRoot() || toShadowRoot(treeScope->rootNode())->isYoungest());
104 Node* FocusNavigationScope::rootNode() const
106 return m_rootTreeScope->rootNode();
109 Element* FocusNavigationScope::owner() const
111 Node* root = rootNode();
112 if (root->isShadowRoot())
113 return toShadowRoot(root)->host();
114 if (Frame* frame = root->document()->frame())
115 return frame->ownerElement();
119 FocusNavigationScope FocusNavigationScope::focusNavigationScopeOf(Node* node)
122 ComposedShadowTreeWalker walker(node, ComposedShadowTreeWalker::DoNotCrossUpperBoundary);
124 while (walker.get()) {
128 // The result is not always a ShadowRoot nor a DocumentNode since
129 // a starting node is in an orphaned tree in composed shadow tree.
130 return FocusNavigationScope(root->treeScope());
133 FocusNavigationScope FocusNavigationScope::focusNavigationScopeOwnedByShadowHost(Node* node)
135 ASSERT(isShadowHost(node));
136 return FocusNavigationScope(toElement(node)->shadow()->youngestShadowRoot());
139 FocusNavigationScope FocusNavigationScope::focusNavigationScopeOwnedByIFrame(HTMLFrameOwnerElement* frame)
141 ASSERT(frame && frame->contentFrame());
142 return FocusNavigationScope(frame->contentFrame()->document());
145 static inline void dispatchEventsOnWindowAndFocusedNode(Document* document, bool focused)
147 // If we have a focused node we should dispatch blur on it before we blur the window.
148 // If we have a focused node we should dispatch focus on it after we focus the window.
149 // https://bugs.webkit.org/show_bug.cgi?id=27105
151 // Do not fire events while modal dialogs are up. See https://bugs.webkit.org/show_bug.cgi?id=33962
152 if (Page* page = document->page()) {
153 if (page->defersLoading())
157 if (!focused && document->focusedNode())
158 document->focusedNode()->dispatchBlurEvent(0);
159 document->dispatchWindowEvent(Event::create(focused ? eventNames().focusEvent : eventNames().blurEvent, false, false));
160 if (focused && document->focusedNode())
161 document->focusedNode()->dispatchFocusEvent(0);
164 static inline bool hasCustomFocusLogic(Node* node)
166 return node->hasTagName(inputTag) || node->hasTagName(textareaTag) || node->hasTagName(videoTag) || node->hasTagName(audioTag);
169 static inline bool isNonFocusableShadowHost(Node* node, KeyboardEvent* event)
172 return !node->isKeyboardFocusable(event) && isShadowHost(node) && !hasCustomFocusLogic(node);
175 static inline bool isFocusableShadowHost(Node* node, KeyboardEvent* event)
178 return node->isKeyboardFocusable(event) && isShadowHost(node) && !hasCustomFocusLogic(node);
181 static inline int adjustedTabIndex(Node* node, KeyboardEvent* event)
184 return isNonFocusableShadowHost(node, event) ? 0 : node->tabIndex();
187 static inline bool shouldVisit(Node* node, KeyboardEvent* event)
190 return node->isKeyboardFocusable(event) || isNonFocusableShadowHost(node, event);
193 FocusController::FocusController(Page* page)
197 , m_isChangingFocusedFrame(false)
198 , m_containingWindowIsVisible(false)
202 PassOwnPtr<FocusController> FocusController::create(Page* page)
204 return adoptPtr(new FocusController(page));
207 void FocusController::setFocusedFrame(PassRefPtr<Frame> frame)
209 ASSERT(!frame || frame->page() == m_page);
210 if (m_focusedFrame == frame || m_isChangingFocusedFrame)
213 m_isChangingFocusedFrame = true;
215 RefPtr<Frame> oldFrame = m_focusedFrame;
216 RefPtr<Frame> newFrame = frame;
218 m_focusedFrame = newFrame;
220 // Now that the frame is updated, fire events and update the selection focused states of both frames.
221 if (oldFrame && oldFrame->view()) {
222 oldFrame->selection()->setFocused(false);
223 oldFrame->document()->dispatchWindowEvent(Event::create(eventNames().blurEvent, false, false));
226 if (newFrame && newFrame->view() && isFocused()) {
227 newFrame->selection()->setFocused(true);
228 newFrame->document()->dispatchWindowEvent(Event::create(eventNames().focusEvent, false, false));
231 m_page->chrome()->focusedFrameChanged(newFrame.get());
233 m_isChangingFocusedFrame = false;
236 Frame* FocusController::focusedOrMainFrame() const
238 if (Frame* frame = focusedFrame())
240 return m_page->mainFrame();
243 void FocusController::setFocused(bool focused)
245 if (isFocused() == focused)
248 m_isFocused = focused;
251 focusedOrMainFrame()->eventHandler()->stopAutoscrollTimer();
254 setFocusedFrame(m_page->mainFrame());
256 if (m_focusedFrame->view()) {
257 m_focusedFrame->selection()->setFocused(focused);
258 dispatchEventsOnWindowAndFocusedNode(m_focusedFrame->document(), focused);
262 Node* FocusController::findFocusableNodeDecendingDownIntoFrameDocument(FocusDirection direction, Node* node, KeyboardEvent* event)
264 // The node we found might be a HTMLFrameOwnerElement, so descend down the tree until we find either:
265 // 1) a focusable node, or
266 // 2) the deepest-nested HTMLFrameOwnerElement.
267 while (node && node->isFrameOwnerElement()) {
268 HTMLFrameOwnerElement* owner = static_cast<HTMLFrameOwnerElement*>(node);
269 if (!owner->contentFrame())
271 Node* foundNode = findFocusableNode(direction, FocusNavigationScope::focusNavigationScopeOwnedByIFrame(owner), 0, event);
274 ASSERT(node != foundNode);
280 bool FocusController::setInitialFocus(FocusDirection direction, KeyboardEvent* event)
282 bool didAdvanceFocus = advanceFocus(direction, event, true);
284 // If focus is being set initially, accessibility needs to be informed that system focus has moved
285 // into the web area again, even if focus did not change within WebCore. PostNotification is called instead
286 // of handleFocusedUIElementChanged, because this will send the notification even if the element is the same.
287 if (AXObjectCache::accessibilityEnabled())
288 focusedOrMainFrame()->document()->axObjectCache()->postNotification(focusedOrMainFrame()->document()->renderer(), AXObjectCache::AXFocusedUIElementChanged, true);
290 return didAdvanceFocus;
293 bool FocusController::advanceFocus(FocusDirection direction, KeyboardEvent* event, bool initialFocus)
296 case FocusDirectionForward:
297 case FocusDirectionBackward:
298 return advanceFocusInDocumentOrder(direction, event, initialFocus);
299 case FocusDirectionLeft:
300 case FocusDirectionRight:
301 case FocusDirectionUp:
302 case FocusDirectionDown:
303 return advanceFocusDirectionally(direction, event);
305 ASSERT_NOT_REACHED();
311 bool FocusController::advanceFocusInDocumentOrder(FocusDirection direction, KeyboardEvent* event, bool initialFocus)
313 Frame* frame = focusedOrMainFrame();
315 Document* document = frame->document();
317 Node* currentNode = document->focusedNode();
318 // FIXME: Not quite correct when it comes to focus transitions leaving/entering the WebView itself
319 bool caretBrowsing = frame->settings() && frame->settings()->caretBrowsingEnabled();
321 if (caretBrowsing && !currentNode)
322 currentNode = frame->selection()->start().deprecatedNode();
324 document->updateLayoutIgnorePendingStylesheets();
326 RefPtr<Node> node = findFocusableNodeAcrossFocusScope(direction, FocusNavigationScope::focusNavigationScopeOf(currentNode ? currentNode : document), currentNode, event);
329 // We didn't find a node to focus, so we should try to pass focus to Chrome.
330 if (!initialFocus && m_page->chrome()->canTakeFocus(direction)) {
331 document->setFocusedNode(0);
333 m_page->chrome()->takeFocus(direction);
337 // Chrome doesn't want focus, so we should wrap focus.
338 node = findFocusableNodeRecursively(direction, FocusNavigationScope::focusNavigationScopeOf(m_page->mainFrame()->document()), 0, event);
339 node = findFocusableNodeDecendingDownIntoFrameDocument(direction, node.get(), event);
347 if (node == document->focusedNode())
348 // Focus wrapped around to the same node.
351 if (!node->isElementNode())
352 // FIXME: May need a way to focus a document here.
355 if (node->isFrameOwnerElement()) {
356 // We focus frames rather than frame owners.
357 // FIXME: We should not focus frames that have no scrollbars, as focusing them isn't useful to the user.
358 HTMLFrameOwnerElement* owner = static_cast<HTMLFrameOwnerElement*>(node.get());
359 if (!owner->contentFrame())
362 document->setFocusedNode(0);
363 setFocusedFrame(owner->contentFrame());
367 // FIXME: It would be nice to just be able to call setFocusedNode(node) here, but we can't do
368 // that because some elements (e.g. HTMLInputElement and HTMLTextAreaElement) do extra work in
369 // their focus() methods.
371 Document* newDocument = node->document();
373 if (newDocument != document)
374 // Focus is going away from this document, so clear the focused node.
375 document->setFocusedNode(0);
378 setFocusedFrame(newDocument->frame());
381 Position position = firstPositionInOrBeforeNode(node.get());
382 VisibleSelection newSelection(position, position, DOWNSTREAM);
383 if (frame->selection()->shouldChangeSelection(newSelection))
384 frame->selection()->setSelection(newSelection);
387 static_cast<Element*>(node.get())->focus(false);
391 Node* FocusController::findFocusableNodeAcrossFocusScope(FocusDirection direction, FocusNavigationScope scope, Node* currentNode, KeyboardEvent* event)
393 ASSERT(!currentNode || !isNonFocusableShadowHost(currentNode, event));
395 if (currentNode && direction == FocusDirectionForward && isFocusableShadowHost(currentNode, event)) {
396 Node* foundInInnerFocusScope = findFocusableNodeRecursively(direction, FocusNavigationScope::focusNavigationScopeOwnedByShadowHost(currentNode), 0, event);
397 found = foundInInnerFocusScope ? foundInInnerFocusScope : findFocusableNodeRecursively(direction, scope, currentNode, event);
399 found = findFocusableNodeRecursively(direction, scope, currentNode, event);
401 // If there's no focusable node to advance to, move up the focus scopes until we find one.
403 Node* owner = scope.owner();
406 scope = FocusNavigationScope::focusNavigationScopeOf(owner);
407 if (direction == FocusDirectionBackward && isFocusableShadowHost(owner, event)) {
411 found = findFocusableNodeRecursively(direction, scope, owner, event);
413 found = findFocusableNodeDecendingDownIntoFrameDocument(direction, found, event);
417 Node* FocusController::findFocusableNodeRecursively(FocusDirection direction, FocusNavigationScope scope, Node* start, KeyboardEvent* event)
419 // Starting node is exclusive.
420 Node* found = findFocusableNode(direction, scope, start, event);
423 if (direction == FocusDirectionForward) {
424 if (!isNonFocusableShadowHost(found, event))
426 Node* foundInInnerFocusScope = findFocusableNodeRecursively(direction, FocusNavigationScope::focusNavigationScopeOwnedByShadowHost(found), 0, event);
427 return foundInInnerFocusScope ? foundInInnerFocusScope : findFocusableNodeRecursively(direction, scope, found, event);
429 ASSERT(direction == FocusDirectionBackward);
430 if (isFocusableShadowHost(found, event)) {
431 Node* foundInInnerFocusScope = findFocusableNodeRecursively(direction, FocusNavigationScope::focusNavigationScopeOwnedByShadowHost(found), 0, event);
432 return foundInInnerFocusScope ? foundInInnerFocusScope : found;
434 if (isNonFocusableShadowHost(found, event)) {
435 Node* foundInInnerFocusScope = findFocusableNodeRecursively(direction, FocusNavigationScope::focusNavigationScopeOwnedByShadowHost(found), 0, event);
436 return foundInInnerFocusScope ? foundInInnerFocusScope :findFocusableNodeRecursively(direction, scope, found, event);
441 Node* FocusController::findFocusableNode(FocusDirection direction, FocusNavigationScope scope, Node* node, KeyboardEvent* event)
443 return (direction == FocusDirectionForward)
444 ? nextFocusableNode(scope, node, event)
445 : previousFocusableNode(scope, node, event);
448 Node* FocusController::findNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event, FocusDirection direction)
450 // Search is inclusive of start
451 for (ComposedShadowTreeWalker walker = walkerFrom(start); walker.get(); direction == FocusDirectionForward ? walker.next() : walker.previous()) {
452 if (shouldVisit(walker.get(), event) && adjustedTabIndex(walker.get(), event) == tabIndex)
458 static Node* nextNodeWithGreaterTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
460 // Search is inclusive of start
461 int winningTabIndex = std::numeric_limits<short>::max() + 1;
463 for (ComposedShadowTreeWalker walker = walkerFrom(start); walker.get(); walker.next()) {
464 Node* node = walker.get();
465 if (shouldVisit(node, event) && node->tabIndex() > tabIndex && node->tabIndex() < winningTabIndex) {
467 winningTabIndex = node->tabIndex();
474 static Node* previousNodeWithLowerTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
476 // Search is inclusive of start
477 int winningTabIndex = 0;
479 for (ComposedShadowTreeWalker walker = walkerFrom(start); walker.get(); walker.previous()) {
480 Node* node = walker.get();
481 int currentTabIndex = adjustedTabIndex(node, event);
482 if ((shouldVisit(node, event) || isNonFocusableShadowHost(node, event)) && currentTabIndex < tabIndex && currentTabIndex > winningTabIndex) {
484 winningTabIndex = currentTabIndex;
490 Node* FocusController::nextFocusableNode(FocusNavigationScope scope, Node* start, KeyboardEvent* event)
493 int tabIndex = adjustedTabIndex(start, event);
494 // If a node is excluded from the normal tabbing cycle, the next focusable node is determined by tree order
496 for (ComposedShadowTreeWalker walker = walkerFromNext(start); walker.get(); walker.next()) {
497 if (shouldVisit(walker.get(), event) && adjustedTabIndex(walker.get(), event) >= 0)
502 // First try to find a node with the same tabindex as start that comes after start in the scope.
503 if (Node* winner = findNodeWithExactTabIndex(nextNode(start), tabIndex, event, FocusDirectionForward))
507 // We've reached the last node in the document with a tabindex of 0. This is the end of the tabbing order.
511 // Look for the first node in the scope that:
512 // 1) has the lowest tabindex that is higher than start's tabindex (or 0, if start is null), and
513 // 2) comes first in the scope, if there's a tie.
514 if (Node* winner = nextNodeWithGreaterTabIndex(scope.rootNode(), start ? adjustedTabIndex(start, event) : 0, event))
517 // There are no nodes with a tabindex greater than start's tabindex,
518 // so find the first node with a tabindex of 0.
519 return findNodeWithExactTabIndex(scope.rootNode(), 0, event, FocusDirectionForward);
522 Node* FocusController::previousFocusableNode(FocusNavigationScope scope, Node* start, KeyboardEvent* event)
525 for (ComposedShadowTreeWalker walker = walkerFrom(scope.rootNode()); walker.get(); walker.lastChild())
529 // First try to find the last node in the scope that comes before start and has the same tabindex as start.
530 // If start is null, find the last node in the scope with a tabindex of 0.
532 int startingTabIndex;
534 startingNode = previousNode(start);
535 startingTabIndex = adjustedTabIndex(start, event);
538 startingTabIndex = 0;
541 // However, if a node is excluded from the normal tabbing cycle, the previous focusable node is determined by tree order
542 if (startingTabIndex < 0) {
543 for (ComposedShadowTreeWalker walker = walkerFrom(startingNode); walker.get(); walker.previous()) {
544 if (shouldVisit(walker.get(), event) && adjustedTabIndex(walker.get(), event) >= 0)
549 if (Node* winner = findNodeWithExactTabIndex(startingNode, startingTabIndex, event, FocusDirectionBackward))
552 // There are no nodes before start with the same tabindex as start, so look for a node that:
553 // 1) has the highest non-zero tabindex (that is less than start's tabindex), and
554 // 2) comes last in the scope, if there's a tie.
555 startingTabIndex = (start && startingTabIndex) ? startingTabIndex : std::numeric_limits<short>::max();
556 return previousNodeWithLowerTabIndex(last, startingTabIndex, event);
559 static bool relinquishesEditingFocus(Node *node)
562 ASSERT(node->rendererIsEditable());
564 Node* root = node->rootEditableElement();
565 Frame* frame = node->document()->frame();
569 return frame->editor()->shouldEndEditing(rangeOfContents(root).get());
572 static void clearSelectionIfNeeded(Frame* oldFocusedFrame, Frame* newFocusedFrame, Node* newFocusedNode)
574 if (!oldFocusedFrame || !newFocusedFrame)
577 if (oldFocusedFrame->document() != newFocusedFrame->document())
580 FrameSelection* s = oldFocusedFrame->selection();
584 bool caretBrowsing = oldFocusedFrame->settings()->caretBrowsingEnabled();
588 Node* selectionStartNode = s->selection().start().deprecatedNode();
589 if (selectionStartNode == newFocusedNode || selectionStartNode->isDescendantOf(newFocusedNode) || selectionStartNode->shadowAncestorNode() == newFocusedNode)
592 if (Node* mousePressNode = newFocusedFrame->eventHandler()->mousePressNode()) {
593 if (mousePressNode->renderer() && !mousePressNode->canStartSelection()) {
594 // Don't clear the selection for contentEditable elements, but do clear it for input and textarea. See bug 38696.
595 Node * root = s->rootEditableElement();
599 if (Node* shadowAncestorNode = root->shadowAncestorNode()) {
600 if (!shadowAncestorNode->hasTagName(inputTag) && !shadowAncestorNode->hasTagName(textareaTag))
609 bool FocusController::setFocusedNode(Node* node, PassRefPtr<Frame> newFocusedFrame)
611 RefPtr<Frame> oldFocusedFrame = focusedFrame();
612 RefPtr<Document> oldDocument = oldFocusedFrame ? oldFocusedFrame->document() : 0;
614 Node* oldFocusedNode = oldDocument ? oldDocument->focusedNode() : 0;
615 #if ENABLE(TIZEN_ISF_PORT)
616 if (oldFocusedNode == node) {
617 if (node && node->shouldUseInputMethod() && newFocusedFrame->eventHandler()->mousePressed()) {
618 #if ENABLE(TIZEN_CLIPBOARD) || ENABLE(TIZEN_PASTEBOARD)
619 if (m_page->selection().isRange())
622 m_page->editorClient()->setInputMethodState(true);
627 // A variable to remember a desingMode state before focusing/bluring will change it.
628 bool oldDesignMode = false;
630 if (oldFocusedNode == node)
632 #endif //ENABLE(TIZEN_ISF_PORT)
634 // FIXME: Might want to disable this check for caretBrowsing
635 if (oldFocusedNode && oldFocusedNode->isRootEditableElement() && !relinquishesEditingFocus(oldFocusedNode))
638 m_page->editorClient()->willSetInputMethodState();
640 clearSelectionIfNeeded(oldFocusedFrame.get(), newFocusedFrame.get(), node);
644 oldDocument->setFocusedNode(0);
645 m_page->editorClient()->setInputMethodState(false);
649 RefPtr<Document> newDocument = node->document();
651 if (newDocument && newDocument->focusedNode() == node) {
652 m_page->editorClient()->setInputMethodState(node->shouldUseInputMethod());
656 if (oldDocument && oldDocument != newDocument)
657 oldDocument->setFocusedNode(0);
659 setFocusedFrame(newFocusedFrame);
661 // Setting the focused node can result in losing our last reft to node when JS event handlers fire.
662 RefPtr<Node> protect = node;
664 #if ENABLE(TIZEN_ISF_PORT)
665 // Setting oldDesingMode befere focus/blur events.
666 oldDesignMode = newDocument->inDesignMode();
668 bool successfullyFocused = newDocument->setFocusedNode(node);
669 if (!successfullyFocused)
673 #if ENABLE(TIZEN_ISF_PORT)
674 // If designMode during focusing/bluring was changed from true to false we do not allow to change
675 // input method state.
676 if (oldDesignMode && !newDocument->inDesignMode() && !node->shouldUseInputMethod())
680 if (newDocument->focusedNode() == node)
681 m_page->editorClient()->setInputMethodState(node->shouldUseInputMethod());
686 void FocusController::setActive(bool active)
688 if (m_isActive == active)
693 if (FrameView* view = m_page->mainFrame()->view()) {
694 if (!view->platformWidget()) {
695 view->updateLayoutAndStyleIfNeededRecursive();
696 view->updateControlTints();
700 focusedOrMainFrame()->selection()->pageActivationChanged();
702 if (m_focusedFrame && isFocused())
703 dispatchEventsOnWindowAndFocusedNode(m_focusedFrame->document(), active);
706 static void contentAreaDidShowOrHide(ScrollableArea* scrollableArea, bool didShow)
709 scrollableArea->contentAreaDidShow();
711 scrollableArea->contentAreaDidHide();
714 void FocusController::setContainingWindowIsVisible(bool containingWindowIsVisible)
716 if (m_containingWindowIsVisible == containingWindowIsVisible)
719 m_containingWindowIsVisible = containingWindowIsVisible;
721 FrameView* view = m_page->mainFrame()->view();
725 contentAreaDidShowOrHide(view, containingWindowIsVisible);
727 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
728 FrameView* frameView = frame->view();
732 const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
733 if (!scrollableAreas)
736 for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
737 ScrollableArea* scrollableArea = *it;
738 ASSERT(scrollableArea->isOnActivePage());
740 contentAreaDidShowOrHide(scrollableArea, containingWindowIsVisible);
745 static void updateFocusCandidateIfNeeded(FocusDirection direction, const FocusCandidate& current, FocusCandidate& candidate, FocusCandidate& closest)
747 ASSERT(candidate.visibleNode->isElementNode());
748 ASSERT(candidate.visibleNode->renderer());
750 // Ignore iframes that don't have a src attribute
751 if (frameOwnerElement(candidate) && (!frameOwnerElement(candidate)->contentFrame() || candidate.rect.isEmpty()))
754 // Ignore off screen child nodes of containers that do not scroll (overflow:hidden)
755 if (candidate.isOffscreen && !canBeScrolledIntoView(direction, candidate))
758 distanceDataForNode(direction, current, candidate);
759 if (candidate.distance == maxDistance())
762 if (candidate.isOffscreenAfterScrolling && candidate.alignment < Full)
765 if (closest.isNull()) {
770 LayoutRect intersectionRect = intersection(candidate.rect, closest.rect);
771 if (!intersectionRect.isEmpty() && !areElementsOnSameLine(closest, candidate)) {
772 // If 2 nodes are intersecting, do hit test to find which node in on top.
773 LayoutUnit x = intersectionRect.x() + intersectionRect.width() / 2;
774 LayoutUnit y = intersectionRect.y() + intersectionRect.height() / 2;
775 HitTestResult result = candidate.visibleNode->document()->page()->mainFrame()->eventHandler()->hitTestResultAtPoint(IntPoint(x, y), false, true);
776 if (candidate.visibleNode->contains(result.innerNode())) {
780 if (closest.visibleNode->contains(result.innerNode()))
784 if (candidate.alignment == closest.alignment) {
785 if (candidate.distance < closest.distance)
790 if (candidate.alignment > closest.alignment)
794 void FocusController::findFocusCandidateInContainer(Node* container, const LayoutRect& startingRect, FocusDirection direction, KeyboardEvent* event, FocusCandidate& closest)
797 Node* focusedNode = (focusedFrame() && focusedFrame()->document()) ? focusedFrame()->document()->focusedNode() : 0;
799 Node* node = container->firstChild();
800 FocusCandidate current;
801 current.rect = startingRect;
802 current.focusableNode = focusedNode;
803 current.visibleNode = focusedNode;
805 for (; node; node = (node->isFrameOwnerElement() || canScrollInDirection(node, direction)) ? node->traverseNextSibling(container) : node->traverseNextNode(container)) {
806 if (node == focusedNode)
809 if (!node->isElementNode())
812 if (!node->isKeyboardFocusable(event) && !node->isFrameOwnerElement() && !canScrollInDirection(node, direction))
815 FocusCandidate candidate = FocusCandidate(node, direction);
816 if (candidate.isNull())
819 candidate.enclosingScrollableBox = container;
820 updateFocusCandidateIfNeeded(direction, current, candidate, closest);
824 bool FocusController::advanceFocusDirectionallyInContainer(Node* container, const LayoutRect& startingRect, FocusDirection direction, KeyboardEvent* event)
826 if (!container || !container->document())
829 LayoutRect newStartingRect = startingRect;
831 if (startingRect.isEmpty())
832 newStartingRect = virtualRectForDirection(direction, nodeRectInAbsoluteCoordinates(container));
834 // Find the closest node within current container in the direction of the navigation.
835 FocusCandidate focusCandidate;
836 findFocusCandidateInContainer(container, newStartingRect, direction, event, focusCandidate);
838 if (focusCandidate.isNull()) {
839 // Nothing to focus, scroll if possible.
840 // NOTE: If no scrolling is performed (i.e. scrollInDirection returns false), the
841 // spatial navigation algorithm will skip this container.
842 return scrollInDirection(container, direction);
845 if (HTMLFrameOwnerElement* frameElement = frameOwnerElement(focusCandidate)) {
846 // If we have an iframe without the src attribute, it will not have a contentFrame().
847 // We ASSERT here to make sure that
848 // updateFocusCandidateIfNeeded() will never consider such an iframe as a candidate.
849 ASSERT(frameElement->contentFrame());
851 if (focusCandidate.isOffscreenAfterScrolling) {
852 scrollInDirection(focusCandidate.visibleNode->document(), direction);
855 // Navigate into a new frame.
857 Node* focusedNode = focusedOrMainFrame()->document()->focusedNode();
858 if (focusedNode && !hasOffscreenRect(focusedNode))
859 rect = nodeRectInAbsoluteCoordinates(focusedNode, true /* ignore border */);
860 frameElement->contentFrame()->document()->updateLayoutIgnorePendingStylesheets();
861 if (!advanceFocusDirectionallyInContainer(frameElement->contentFrame()->document(), rect, direction, event)) {
862 // The new frame had nothing interesting, need to find another candidate.
863 return advanceFocusDirectionallyInContainer(container, nodeRectInAbsoluteCoordinates(focusCandidate.visibleNode, true), direction, event);
868 if (canScrollInDirection(focusCandidate.visibleNode, direction)) {
869 if (focusCandidate.isOffscreenAfterScrolling) {
870 scrollInDirection(focusCandidate.visibleNode, direction);
873 // Navigate into a new scrollable container.
874 LayoutRect startingRect;
875 Node* focusedNode = focusedOrMainFrame()->document()->focusedNode();
876 if (focusedNode && !hasOffscreenRect(focusedNode))
877 startingRect = nodeRectInAbsoluteCoordinates(focusedNode, true);
878 return advanceFocusDirectionallyInContainer(focusCandidate.visibleNode, startingRect, direction, event);
880 if (focusCandidate.isOffscreenAfterScrolling) {
881 Node* container = focusCandidate.enclosingScrollableBox;
882 scrollInDirection(container, direction);
886 // We found a new focus node, navigate to it.
887 Element* element = toElement(focusCandidate.focusableNode);
890 element->focus(false);
894 bool FocusController::advanceFocusDirectionally(FocusDirection direction, KeyboardEvent* event)
896 Frame* curFrame = focusedOrMainFrame();
899 Document* focusedDocument = curFrame->document();
900 if (!focusedDocument)
903 Node* focusedNode = focusedDocument->focusedNode();
904 Node* container = focusedDocument;
906 if (container->isDocumentNode())
907 static_cast<Document*>(container)->updateLayoutIgnorePendingStylesheets();
909 // Figure out the starting rect.
910 LayoutRect startingRect;
912 if (!hasOffscreenRect(focusedNode)) {
913 container = scrollableEnclosingBoxOrParentFrameForNodeInDirection(direction, focusedNode);
914 startingRect = nodeRectInAbsoluteCoordinates(focusedNode, true /* ignore border */);
915 } else if (focusedNode->hasTagName(areaTag)) {
916 HTMLAreaElement* area = static_cast<HTMLAreaElement*>(focusedNode);
917 container = scrollableEnclosingBoxOrParentFrameForNodeInDirection(direction, area->imageElement());
918 startingRect = virtualRectForAreaElementAndDirection(area, direction);
922 bool consumed = false;
924 consumed = advanceFocusDirectionallyInContainer(container, startingRect, direction, event);
925 startingRect = nodeRectInAbsoluteCoordinates(container, true /* ignore border */);
926 container = scrollableEnclosingBoxOrParentFrameForNodeInDirection(direction, container);
927 if (container && container->isDocumentNode())
928 static_cast<Document*>(container)->updateLayoutIgnorePendingStylesheets();
929 } while (!consumed && container);
934 } // namespace WebCore