Element* TreeScope::adjustedFocusedElement() const
{
    Document& document = rootNode().document();
    Element* element = document.focusedElement();
    if (!element && document.page())
        element = document.page()->focusController().focusedFrameOwnerElement(*document.frame());
    if (!element)
        return 0;

    RawPtr<EventPath> eventPath = new EventPath(*element);
    for (size_t i = 0; i < eventPath->size(); ++i) {
        if (eventPath->at(i).node() == rootNode()) {
            // eventPath->at(i).target() is one of the followings:
            // - InsertionPoint
            // - shadow host
            // - Document::focusedElement()
            // So, it's safe to do toElement().
            return toElement(eventPath->at(i).target()->toNode());
        }
    }
    return 0;
}