2 * Copyright (C) 2004, 2005, 2006, 2009 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "core/dom/Position.h"
29 #include "core/HTMLNames.h"
30 #include "core/css/CSSComputedStyleDeclaration.h"
31 #include "core/dom/PositionIterator.h"
32 #include "core/dom/Text.h"
33 #include "core/editing/TextIterator.h"
34 #include "core/editing/VisiblePosition.h"
35 #include "core/editing/VisibleUnits.h"
36 #include "core/editing/htmlediting.h"
37 #include "core/frame/LocalFrame.h"
38 #include "core/frame/Settings.h"
39 #include "core/html/HTMLTableElement.h"
40 #include "core/rendering/InlineIterator.h"
41 #include "core/rendering/InlineTextBox.h"
42 #include "core/rendering/RenderBlock.h"
43 #include "core/rendering/RenderInline.h"
44 #include "core/rendering/RenderText.h"
45 #include "platform/Logging.h"
46 #include "wtf/text/CString.h"
47 #include "wtf/unicode/CharacterNames.h"
52 using namespace HTMLNames;
54 static Node* nextRenderedEditable(Node* node)
56 while ((node = node->nextLeafNode())) {
57 RenderObject* renderer = node->renderer();
60 if (!node->rendererIsEditable())
62 if ((renderer->isBox() && toRenderBox(renderer)->inlineBoxWrapper()) || (renderer->isText() && toRenderText(renderer)->firstTextBox()))
68 static Node* previousRenderedEditable(Node* node)
70 while ((node = node->previousLeafNode())) {
71 RenderObject* renderer = node->renderer();
74 if (!node->rendererIsEditable())
76 if ((renderer->isBox() && toRenderBox(renderer)->inlineBoxWrapper()) || (renderer->isText() && toRenderText(renderer)->firstTextBox()))
82 Position::Position(PassRefPtrWillBeRawPtr<Node> anchorNode, LegacyEditingOffset offset)
83 : m_anchorNode(anchorNode)
84 , m_offset(offset.value())
85 , m_anchorType(anchorTypeForLegacyEditingPosition(m_anchorNode.get(), m_offset))
86 , m_isLegacyEditingPosition(true)
88 ASSERT(!m_anchorNode || !m_anchorNode->isPseudoElement());
91 Position::Position(PassRefPtrWillBeRawPtr<Node> anchorNode, AnchorType anchorType)
92 : m_anchorNode(anchorNode)
94 , m_anchorType(anchorType)
95 , m_isLegacyEditingPosition(false)
97 ASSERT(!m_anchorNode || !m_anchorNode->isPseudoElement());
99 ASSERT(anchorType != PositionIsOffsetInAnchor);
100 ASSERT(!((anchorType == PositionIsBeforeChildren || anchorType == PositionIsAfterChildren)
101 && (m_anchorNode->isTextNode() || editingIgnoresContent(m_anchorNode.get()))));
104 Position::Position(PassRefPtrWillBeRawPtr<Node> anchorNode, int offset, AnchorType anchorType)
105 : m_anchorNode(anchorNode)
107 , m_anchorType(anchorType)
108 , m_isLegacyEditingPosition(false)
110 ASSERT(!m_anchorNode || !m_anchorNode->isPseudoElement());
112 ASSERT(anchorType == PositionIsOffsetInAnchor);
115 Position::Position(PassRefPtrWillBeRawPtr<Text> textNode, unsigned offset)
116 : m_anchorNode(textNode)
117 , m_offset(static_cast<int>(offset))
118 , m_anchorType(PositionIsOffsetInAnchor)
119 , m_isLegacyEditingPosition(false)
121 ASSERT(m_anchorNode);
124 void Position::moveToPosition(PassRefPtrWillBeRawPtr<Node> node, int offset)
126 ASSERT(!editingIgnoresContent(node.get()));
127 ASSERT(anchorType() == PositionIsOffsetInAnchor || m_isLegacyEditingPosition);
130 if (m_isLegacyEditingPosition)
131 m_anchorType = anchorTypeForLegacyEditingPosition(m_anchorNode.get(), m_offset);
133 void Position::moveToOffset(int offset)
135 ASSERT(anchorType() == PositionIsOffsetInAnchor || m_isLegacyEditingPosition);
137 if (m_isLegacyEditingPosition)
138 m_anchorType = anchorTypeForLegacyEditingPosition(m_anchorNode.get(), m_offset);
141 Node* Position::containerNode() const
146 switch (anchorType()) {
147 case PositionIsBeforeChildren:
148 case PositionIsAfterChildren:
149 case PositionIsOffsetInAnchor:
150 return m_anchorNode.get();
151 case PositionIsBeforeAnchor:
152 case PositionIsAfterAnchor:
153 return m_anchorNode->parentNode();
155 ASSERT_NOT_REACHED();
159 Text* Position::containerText() const
161 switch (anchorType()) {
162 case PositionIsOffsetInAnchor:
163 return m_anchorNode && m_anchorNode->isTextNode() ? toText(m_anchorNode) : 0;
164 case PositionIsBeforeAnchor:
165 case PositionIsAfterAnchor:
167 case PositionIsBeforeChildren:
168 case PositionIsAfterChildren:
169 ASSERT(!m_anchorNode || !m_anchorNode->isTextNode());
172 ASSERT_NOT_REACHED();
176 int Position::computeOffsetInContainerNode() const
181 switch (anchorType()) {
182 case PositionIsBeforeChildren:
184 case PositionIsAfterChildren:
185 return lastOffsetInNode(m_anchorNode.get());
186 case PositionIsOffsetInAnchor:
187 return minOffsetForNode(m_anchorNode.get(), m_offset);
188 case PositionIsBeforeAnchor:
189 return m_anchorNode->nodeIndex();
190 case PositionIsAfterAnchor:
191 return m_anchorNode->nodeIndex() + 1;
193 ASSERT_NOT_REACHED();
197 int Position::offsetForPositionAfterAnchor() const
199 ASSERT(m_anchorType == PositionIsAfterAnchor || m_anchorType == PositionIsAfterChildren);
200 ASSERT(!m_isLegacyEditingPosition);
201 return lastOffsetForEditing(m_anchorNode.get());
204 // Neighbor-anchored positions are invalid DOM positions, so they need to be
205 // fixed up before handing them off to the Range object.
206 Position Position::parentAnchoredEquivalent() const
211 // FIXME: This should only be necessary for legacy positions, but is also needed for positions before and after Tables
212 if (m_offset <= 0 && (m_anchorType != PositionIsAfterAnchor && m_anchorType != PositionIsAfterChildren)) {
213 if (m_anchorNode->parentNode() && (editingIgnoresContent(m_anchorNode.get()) || isRenderedTableElement(m_anchorNode.get())))
214 return positionInParentBeforeNode(*m_anchorNode);
215 return Position(m_anchorNode.get(), 0, PositionIsOffsetInAnchor);
217 if (!m_anchorNode->offsetInCharacters()
218 && (m_anchorType == PositionIsAfterAnchor || m_anchorType == PositionIsAfterChildren || static_cast<unsigned>(m_offset) == m_anchorNode->countChildren())
219 && (editingIgnoresContent(m_anchorNode.get()) || isRenderedTableElement(m_anchorNode.get()))
220 && containerNode()) {
221 return positionInParentAfterNode(*m_anchorNode);
224 return Position(containerNode(), computeOffsetInContainerNode(), PositionIsOffsetInAnchor);
227 Node* Position::computeNodeBeforePosition() const
231 switch (anchorType()) {
232 case PositionIsBeforeChildren:
234 case PositionIsAfterChildren:
235 return m_anchorNode->lastChild();
236 case PositionIsOffsetInAnchor:
237 return m_anchorNode->traverseToChildAt(m_offset - 1); // -1 converts to traverseToChildAt((unsigned)-1) and returns null.
238 case PositionIsBeforeAnchor:
239 return m_anchorNode->previousSibling();
240 case PositionIsAfterAnchor:
241 return m_anchorNode.get();
243 ASSERT_NOT_REACHED();
247 Node* Position::computeNodeAfterPosition() const
252 switch (anchorType()) {
253 case PositionIsBeforeChildren:
254 return m_anchorNode->firstChild();
255 case PositionIsAfterChildren:
257 case PositionIsOffsetInAnchor:
258 return m_anchorNode->traverseToChildAt(m_offset);
259 case PositionIsBeforeAnchor:
260 return m_anchorNode.get();
261 case PositionIsAfterAnchor:
262 return m_anchorNode->nextSibling();
264 ASSERT_NOT_REACHED();
268 Position::AnchorType Position::anchorTypeForLegacyEditingPosition(Node* anchorNode, int offset)
270 if (anchorNode && editingIgnoresContent(anchorNode)) {
272 return Position::PositionIsBeforeAnchor;
273 return Position::PositionIsAfterAnchor;
275 return Position::PositionIsOffsetInAnchor;
278 // FIXME: This method is confusing (does it return anchorNode() or containerNode()?) and should be renamed or removed
279 Element* Position::element() const
281 Node* n = anchorNode();
282 while (n && !n->isElementNode())
287 PassRefPtrWillBeRawPtr<CSSComputedStyleDeclaration> Position::computedStyle() const
289 Element* elem = element();
292 return CSSComputedStyleDeclaration::create(elem);
295 Position Position::previous(PositionMoveType moveType) const
297 Node* node = deprecatedNode();
301 int offset = deprecatedEditingOffset();
302 // FIXME: Negative offsets shouldn't be allowed. We should catch this earlier.
306 if (Node* child = node->traverseToChildAt(offset - 1))
307 return lastPositionInOrAfterNode(child);
309 // There are two reasons child might be 0:
310 // 1) The node is node like a text node that is not an element, and therefore has no children.
311 // Going backward one character at a time is correct.
312 // 2) The old offset was a bogus offset like (<br>, 1), and there is no child.
313 // Going from 1 to 0 is correct.
316 return createLegacyEditingPosition(node, offset - 1);
318 return createLegacyEditingPosition(node, uncheckedPreviousOffset(node, offset));
319 case BackwardDeletion:
320 return createLegacyEditingPosition(node, uncheckedPreviousOffsetForBackwardDeletion(node, offset));
324 if (ContainerNode* parent = node->parentNode())
325 return createLegacyEditingPosition(parent, node->nodeIndex());
329 Position Position::next(PositionMoveType moveType) const
331 ASSERT(moveType != BackwardDeletion);
333 Node* node = deprecatedNode();
337 int offset = deprecatedEditingOffset();
338 // FIXME: Negative offsets shouldn't be allowed. We should catch this earlier.
341 if (Node* child = node->traverseToChildAt(offset))
342 return firstPositionInOrBeforeNode(child);
344 if (!node->hasChildren() && offset < lastOffsetForEditing(node)) {
345 // There are two reasons child might be 0:
346 // 1) The node is node like a text node that is not an element, and therefore has no children.
347 // Going forward one character at a time is correct.
348 // 2) The new offset is a bogus offset like (<br>, 1), and there is no child.
349 // Going from 0 to 1 is correct.
350 return createLegacyEditingPosition(node, (moveType == Character) ? uncheckedNextOffset(node, offset) : offset + 1);
353 if (ContainerNode* parent = node->parentNode())
354 return createLegacyEditingPosition(parent, node->nodeIndex() + 1);
358 int Position::uncheckedPreviousOffset(const Node* n, int current)
360 return n->renderer() ? n->renderer()->previousOffset(current) : current - 1;
363 int Position::uncheckedPreviousOffsetForBackwardDeletion(const Node* n, int current)
365 return n->renderer() ? n->renderer()->previousOffsetForBackwardDeletion(current) : current - 1;
368 int Position::uncheckedNextOffset(const Node* n, int current)
370 return n->renderer() ? n->renderer()->nextOffset(current) : current + 1;
373 bool Position::atFirstEditingPositionForNode() const
377 // FIXME: Position before anchor shouldn't be considered as at the first editing position for node
378 // since that position resides outside of the node.
379 switch (m_anchorType) {
380 case PositionIsOffsetInAnchor:
381 return m_offset <= 0;
382 case PositionIsBeforeChildren:
383 case PositionIsBeforeAnchor:
385 case PositionIsAfterChildren:
386 case PositionIsAfterAnchor:
387 return !lastOffsetForEditing(deprecatedNode());
389 ASSERT_NOT_REACHED();
393 bool Position::atLastEditingPositionForNode() const
397 // FIXME: Position after anchor shouldn't be considered as at the first editing position for node
398 // since that position resides outside of the node.
399 return m_anchorType == PositionIsAfterAnchor || m_anchorType == PositionIsAfterChildren || m_offset >= lastOffsetForEditing(deprecatedNode());
402 // A position is considered at editing boundary if one of the following is true:
403 // 1. It is the first position in the node and the next visually equivalent position
405 // 2. It is the last position in the node and the previous visually equivalent position
407 // 3. It is an editable position and both the next and previous visually equivalent
408 // positions are both non editable.
409 bool Position::atEditingBoundary() const
411 Position nextPosition = downstream(CanCrossEditingBoundary);
412 if (atFirstEditingPositionForNode() && nextPosition.isNotNull() && !nextPosition.deprecatedNode()->rendererIsEditable())
415 Position prevPosition = upstream(CanCrossEditingBoundary);
416 if (atLastEditingPositionForNode() && prevPosition.isNotNull() && !prevPosition.deprecatedNode()->rendererIsEditable())
419 return nextPosition.isNotNull() && !nextPosition.deprecatedNode()->rendererIsEditable()
420 && prevPosition.isNotNull() && !prevPosition.deprecatedNode()->rendererIsEditable();
423 Node* Position::parentEditingBoundary() const
428 Node* documentElement = m_anchorNode->document().documentElement();
429 if (!documentElement)
432 Node* boundary = m_anchorNode.get();
433 while (boundary != documentElement && boundary->nonShadowBoundaryParentNode() && m_anchorNode->rendererIsEditable() == boundary->parentNode()->rendererIsEditable())
434 boundary = boundary->nonShadowBoundaryParentNode();
440 bool Position::atStartOfTree() const
444 return !deprecatedNode()->parentNode() && m_offset <= 0;
447 bool Position::atEndOfTree() const
451 return !deprecatedNode()->parentNode() && m_offset >= lastOffsetForEditing(deprecatedNode());
454 int Position::renderedOffset() const
456 if (!deprecatedNode()->isTextNode())
459 if (!deprecatedNode()->renderer())
463 RenderText* textRenderer = toRenderText(deprecatedNode()->renderer());
464 for (InlineTextBox *box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
465 int start = box->start();
466 int end = box->start() + box->len();
467 if (m_offset < start)
469 if (m_offset <= end) {
470 result += m_offset - start;
473 result += box->len();
478 // return first preceding DOM position rendered at a different location, or "this"
479 Position Position::previousCharacterPosition(EAffinity affinity) const
484 Node* fromRootEditableElement = deprecatedNode()->rootEditableElement();
486 bool atStartOfLine = isStartOfLine(VisiblePosition(*this, affinity));
487 bool rendered = isCandidate();
489 Position currentPos = *this;
490 while (!currentPos.atStartOfTree()) {
491 currentPos = currentPos.previous();
493 if (currentPos.deprecatedNode()->rootEditableElement() != fromRootEditableElement)
496 if (atStartOfLine || !rendered) {
497 if (currentPos.isCandidate())
499 } else if (rendersInDifferentPosition(currentPos))
506 // Whether or not [node, 0] and [node, lastOffsetForEditing(node)] are their own VisiblePositions.
507 // If true, adjacent candidates are visually distinct.
508 // FIXME: Disregard nodes with renderers that have no height, as we do in isCandidate.
509 // FIXME: Share code with isCandidate, if possible.
510 static bool endsOfNodeAreVisuallyDistinctPositions(Node* node)
512 if (!node || !node->renderer())
515 if (!node->renderer()->isInline())
518 // Don't include inline tables.
519 if (isHTMLTableElement(*node))
522 // A Marquee elements are moving so we should assume their ends are always
523 // visibily distinct.
524 if (isHTMLMarqueeElement(*node))
527 // There is a VisiblePosition inside an empty inline-block container.
528 return node->renderer()->isReplaced() && canHaveChildrenForEditing(node) && toRenderBox(node->renderer())->height() != 0 && !node->firstChild();
531 static Node* enclosingVisualBoundary(Node* node)
533 while (node && !endsOfNodeAreVisuallyDistinctPositions(node))
534 node = node->parentNode();
539 // upstream() and downstream() want to return positions that are either in a
540 // text node or at just before a non-text node. This method checks for that.
541 static bool isStreamer(const PositionIterator& pos)
546 if (isAtomicNode(pos.node()))
549 return pos.atStartOfNode();
552 // This function and downstream() are used for moving back and forth between visually equivalent candidates.
553 // For example, for the text node "foo bar" where whitespace is collapsible, there are two candidates
554 // that map to the VisiblePosition between 'b' and the space. This function will return the left candidate
555 // and downstream() will return the right one.
556 // Also, upstream() will return [boundary, 0] for any of the positions from [boundary, 0] to the first candidate
557 // in boundary, where endsOfNodeAreVisuallyDistinctPositions(boundary) is true.
558 Position Position::upstream(EditingBoundaryCrossingRule rule) const
560 Node* startNode = deprecatedNode();
564 // iterate backward from there, looking for a qualified position
565 Node* boundary = enclosingVisualBoundary(startNode);
566 // FIXME: PositionIterator should respect Before and After positions.
567 PositionIterator lastVisible = m_anchorType == PositionIsAfterAnchor ? createLegacyEditingPosition(m_anchorNode.get(), caretMaxOffset(m_anchorNode.get())) : *this;
568 PositionIterator currentPos = lastVisible;
569 bool startEditable = startNode->rendererIsEditable();
570 Node* lastNode = startNode;
571 bool boundaryCrossed = false;
572 for (; !currentPos.atStart(); currentPos.decrement()) {
573 Node* currentNode = currentPos.node();
575 // Don't check for an editability change if we haven't moved to a different node,
576 // to avoid the expense of computing rendererIsEditable().
577 if (currentNode != lastNode) {
578 // Don't change editability.
579 bool currentEditable = currentNode->rendererIsEditable();
580 if (startEditable != currentEditable) {
581 if (rule == CannotCrossEditingBoundary)
583 boundaryCrossed = true;
585 lastNode = currentNode;
588 // If we've moved to a position that is visually distinct, return the last saved position. There
589 // is code below that terminates early if we're *about* to move to a visually distinct position.
590 if (endsOfNodeAreVisuallyDistinctPositions(currentNode) && currentNode != boundary)
593 // skip position in unrendered or invisible node
594 RenderObject* renderer = currentNode->renderer();
595 if (!renderer || renderer->style()->visibility() != VISIBLE)
598 if (rule == CanCrossEditingBoundary && boundaryCrossed) {
599 lastVisible = currentPos;
603 // track last visible streamer position
604 if (isStreamer(currentPos))
605 lastVisible = currentPos;
607 // Don't move past a position that is visually distinct. We could rely on code above to terminate and
608 // return lastVisible on the next iteration, but we terminate early to avoid doing a nodeIndex() call.
609 if (endsOfNodeAreVisuallyDistinctPositions(currentNode) && currentPos.atStartOfNode())
612 // Return position after tables and nodes which have content that can be ignored.
613 if (editingIgnoresContent(currentNode) || isRenderedTableElement(currentNode)) {
614 if (currentPos.atEndOfNode())
615 return positionAfterNode(currentNode);
619 // return current position if it is in rendered text
620 if (renderer->isText() && toRenderText(renderer)->firstTextBox()) {
621 if (currentNode != startNode) {
622 // This assertion fires in layout tests in the case-transform.html test because
623 // of a mix-up between offsets in the text in the DOM tree with text in the
624 // render tree which can have a different length due to case transformation.
625 // Until we resolve that, disable this so we can run the layout tests!
626 //ASSERT(currentOffset >= renderer->caretMaxOffset());
627 return createLegacyEditingPosition(currentNode, renderer->caretMaxOffset());
630 unsigned textOffset = currentPos.offsetInLeafNode();
631 RenderText* textRenderer = toRenderText(renderer);
632 InlineTextBox* lastTextBox = textRenderer->lastTextBox();
633 for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
634 if (textOffset <= box->start() + box->len()) {
635 if (textOffset > box->start())
640 if (box == lastTextBox || textOffset != box->start() + box->len() + 1)
643 // The text continues on the next line only if the last text box is not on this line and
644 // none of the boxes on this line have a larger start offset.
646 bool continuesOnNextLine = true;
647 InlineBox* otherBox = box;
648 while (continuesOnNextLine) {
649 otherBox = otherBox->nextLeafChild();
652 if (otherBox == lastTextBox || (otherBox->renderer() == textRenderer && toInlineTextBox(otherBox)->start() > textOffset))
653 continuesOnNextLine = false;
657 while (continuesOnNextLine) {
658 otherBox = otherBox->prevLeafChild();
661 if (otherBox == lastTextBox || (otherBox->renderer() == textRenderer && toInlineTextBox(otherBox)->start() > textOffset))
662 continuesOnNextLine = false;
665 if (continuesOnNextLine)
674 // This function and upstream() are used for moving back and forth between visually equivalent candidates.
675 // For example, for the text node "foo bar" where whitespace is collapsible, there are two candidates
676 // that map to the VisiblePosition between 'b' and the space. This function will return the right candidate
677 // and upstream() will return the left one.
678 // Also, downstream() will return the last position in the last atomic node in boundary for all of the positions
679 // in boundary after the last candidate, where endsOfNodeAreVisuallyDistinctPositions(boundary).
680 // FIXME: This function should never be called when the line box tree is dirty. See https://bugs.webkit.org/show_bug.cgi?id=97264
681 Position Position::downstream(EditingBoundaryCrossingRule rule) const
683 Node* startNode = deprecatedNode();
687 // iterate forward from there, looking for a qualified position
688 Node* boundary = enclosingVisualBoundary(startNode);
689 // FIXME: PositionIterator should respect Before and After positions.
690 PositionIterator lastVisible = m_anchorType == PositionIsAfterAnchor ? createLegacyEditingPosition(m_anchorNode.get(), caretMaxOffset(m_anchorNode.get())) : *this;
691 PositionIterator currentPos = lastVisible;
692 bool startEditable = startNode->rendererIsEditable();
693 Node* lastNode = startNode;
694 bool boundaryCrossed = false;
695 for (; !currentPos.atEnd(); currentPos.increment()) {
696 Node* currentNode = currentPos.node();
698 // Don't check for an editability change if we haven't moved to a different node,
699 // to avoid the expense of computing rendererIsEditable().
700 if (currentNode != lastNode) {
701 // Don't change editability.
702 bool currentEditable = currentNode->rendererIsEditable();
703 if (startEditable != currentEditable) {
704 if (rule == CannotCrossEditingBoundary)
706 boundaryCrossed = true;
709 lastNode = currentNode;
712 // stop before going above the body, up into the head
713 // return the last visible streamer position
714 if (isHTMLBodyElement(*currentNode) && currentPos.atEndOfNode())
717 // Do not move to a visually distinct position.
718 if (endsOfNodeAreVisuallyDistinctPositions(currentNode) && currentNode != boundary)
720 // Do not move past a visually disinct position.
721 // Note: The first position after the last in a node whose ends are visually distinct
722 // positions will be [boundary->parentNode(), originalBlock->nodeIndex() + 1].
723 if (boundary && boundary->parentNode() == currentNode)
726 // skip position in unrendered or invisible node
727 RenderObject* renderer = currentNode->renderer();
728 if (!renderer || renderer->style()->visibility() != VISIBLE)
731 if (rule == CanCrossEditingBoundary && boundaryCrossed) {
732 lastVisible = currentPos;
736 // track last visible streamer position
737 if (isStreamer(currentPos))
738 lastVisible = currentPos;
740 // Return position before tables and nodes which have content that can be ignored.
741 if (editingIgnoresContent(currentNode) || isRenderedTableElement(currentNode)) {
742 if (currentPos.offsetInLeafNode() <= renderer->caretMinOffset())
743 return createLegacyEditingPosition(currentNode, renderer->caretMinOffset());
747 // return current position if it is in rendered text
748 if (renderer->isText() && toRenderText(renderer)->firstTextBox()) {
749 if (currentNode != startNode) {
750 ASSERT(currentPos.atStartOfNode());
751 return createLegacyEditingPosition(currentNode, renderer->caretMinOffset());
754 unsigned textOffset = currentPos.offsetInLeafNode();
755 RenderText* textRenderer = toRenderText(renderer);
756 InlineTextBox* lastTextBox = textRenderer->lastTextBox();
757 for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
758 if (textOffset <= box->end()) {
759 if (textOffset >= box->start())
764 if (box == lastTextBox || textOffset != box->start() + box->len())
767 // The text continues on the next line only if the last text box is not on this line and
768 // none of the boxes on this line have a larger start offset.
770 bool continuesOnNextLine = true;
771 InlineBox* otherBox = box;
772 while (continuesOnNextLine) {
773 otherBox = otherBox->nextLeafChild();
776 if (otherBox == lastTextBox || (otherBox->renderer() == textRenderer && toInlineTextBox(otherBox)->start() >= textOffset))
777 continuesOnNextLine = false;
781 while (continuesOnNextLine) {
782 otherBox = otherBox->prevLeafChild();
785 if (otherBox == lastTextBox || (otherBox->renderer() == textRenderer && toInlineTextBox(otherBox)->start() >= textOffset))
786 continuesOnNextLine = false;
789 if (continuesOnNextLine)
798 static int boundingBoxLogicalHeight(RenderObject *o, const IntRect &rect)
800 return o->style()->isHorizontalWritingMode() ? rect.height() : rect.width();
803 bool Position::hasRenderedNonAnonymousDescendantsWithHeight(RenderObject* renderer)
805 RenderObject* stop = renderer->nextInPreOrderAfterChildren();
806 for (RenderObject *o = renderer->slowFirstChild(); o && o != stop; o = o->nextInPreOrder())
807 if (o->nonPseudoNode()) {
808 if ((o->isText() && boundingBoxLogicalHeight(o, toRenderText(o)->linesBoundingBox()))
809 || (o->isBox() && toRenderBox(o)->pixelSnappedLogicalHeight())
810 || (o->isRenderInline() && isEmptyInline(o) && boundingBoxLogicalHeight(o, toRenderInline(o)->linesBoundingBox())))
816 bool Position::nodeIsUserSelectNone(Node* node)
818 return node && node->renderer() && !node->renderer()->isSelectable();
821 bool Position::nodeIsUserSelectAll(const Node* node)
823 return RuntimeEnabledFeatures::userSelectAllEnabled() && node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_ALL;
826 Node* Position::rootUserSelectAllForNode(Node* node)
828 if (!node || !nodeIsUserSelectAll(node))
830 Node* parent = node->parentNode();
834 Node* candidateRoot = node;
836 if (!parent->renderer()) {
837 parent = parent->parentNode();
840 if (!nodeIsUserSelectAll(parent))
842 candidateRoot = parent;
843 parent = candidateRoot->parentNode();
845 return candidateRoot;
848 bool Position::isCandidate() const
853 RenderObject* renderer = deprecatedNode()->renderer();
857 if (renderer->style()->visibility() != VISIBLE)
860 if (renderer->isBR())
861 // FIXME: The condition should be m_anchorType == PositionIsBeforeAnchor, but for now we still need to support legacy positions.
862 return !m_offset && m_anchorType != PositionIsAfterAnchor && !nodeIsUserSelectNone(deprecatedNode()->parentNode());
864 if (renderer->isText())
865 return !nodeIsUserSelectNone(deprecatedNode()) && inRenderedText();
867 if (renderer->isSVG()) {
868 // We don't consider SVG elements are contenteditable except for
869 // associated renderer returns isText() true, e.g. RenderSVGInlineText.
873 if (isRenderedTableElement(deprecatedNode()) || editingIgnoresContent(deprecatedNode()))
874 return (atFirstEditingPositionForNode() || atLastEditingPositionForNode()) && !nodeIsUserSelectNone(deprecatedNode()->parentNode());
876 if (isHTMLHtmlElement(*m_anchorNode))
879 if (renderer->isRenderBlockFlow()) {
880 if (toRenderBlock(renderer)->logicalHeight() || isHTMLBodyElement(*m_anchorNode)) {
881 if (!Position::hasRenderedNonAnonymousDescendantsWithHeight(renderer))
882 return atFirstEditingPositionForNode() && !Position::nodeIsUserSelectNone(deprecatedNode());
883 return m_anchorNode->rendererIsEditable() && !Position::nodeIsUserSelectNone(deprecatedNode()) && atEditingBoundary();
886 LocalFrame* frame = m_anchorNode->document().frame();
887 bool caretBrowsing = frame->settings() && frame->settings()->caretBrowsingEnabled();
888 return (caretBrowsing || m_anchorNode->rendererIsEditable()) && !Position::nodeIsUserSelectNone(deprecatedNode()) && atEditingBoundary();
894 bool Position::inRenderedText() const
896 if (isNull() || !deprecatedNode()->isTextNode())
899 RenderObject* renderer = deprecatedNode()->renderer();
903 RenderText *textRenderer = toRenderText(renderer);
904 for (InlineTextBox *box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
905 if (m_offset < static_cast<int>(box->start()) && !textRenderer->containsReversedText()) {
906 // The offset we're looking for is before this node
907 // this means the offset must be in content that is
908 // not rendered. Return false.
911 if (box->containsCaretOffset(m_offset))
912 // Return false for offsets inside composed characters.
913 return m_offset == 0 || m_offset == textRenderer->nextOffset(textRenderer->previousOffset(m_offset));
919 bool Position::isRenderedCharacter() const
921 if (isNull() || !deprecatedNode()->isTextNode())
924 RenderObject* renderer = deprecatedNode()->renderer();
928 RenderText* textRenderer = toRenderText(renderer);
929 for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
930 if (m_offset < static_cast<int>(box->start()) && !textRenderer->containsReversedText()) {
931 // The offset we're looking for is before this node
932 // this means the offset must be in content that is
933 // not rendered. Return false.
936 if (m_offset >= static_cast<int>(box->start()) && m_offset < static_cast<int>(box->start() + box->len()))
943 bool Position::rendersInDifferentPosition(const Position &pos) const
945 if (isNull() || pos.isNull())
948 RenderObject* renderer = deprecatedNode()->renderer();
952 RenderObject* posRenderer = pos.deprecatedNode()->renderer();
956 if (renderer->style()->visibility() != VISIBLE ||
957 posRenderer->style()->visibility() != VISIBLE)
960 if (deprecatedNode() == pos.deprecatedNode()) {
961 if (isHTMLBRElement(*deprecatedNode()))
964 if (m_offset == pos.deprecatedEditingOffset())
967 if (!deprecatedNode()->isTextNode() && !pos.deprecatedNode()->isTextNode()) {
968 if (m_offset != pos.deprecatedEditingOffset())
973 if (isHTMLBRElement(*deprecatedNode()) && pos.isCandidate())
976 if (isHTMLBRElement(*pos.deprecatedNode()) && isCandidate())
979 if (deprecatedNode()->enclosingBlockFlowElement() != pos.deprecatedNode()->enclosingBlockFlowElement())
982 if (deprecatedNode()->isTextNode() && !inRenderedText())
985 if (pos.deprecatedNode()->isTextNode() && !pos.inRenderedText())
988 int thisRenderedOffset = renderedOffset();
989 int posRenderedOffset = pos.renderedOffset();
991 if (renderer == posRenderer && thisRenderedOffset == posRenderedOffset)
994 int ignoredCaretOffset;
996 getInlineBoxAndOffset(DOWNSTREAM, b1, ignoredCaretOffset);
998 pos.getInlineBoxAndOffset(DOWNSTREAM, b2, ignoredCaretOffset);
1000 WTF_LOG(Editing, "renderer: %p [%p]\n", renderer, b1);
1001 WTF_LOG(Editing, "thisRenderedOffset: %d\n", thisRenderedOffset);
1002 WTF_LOG(Editing, "posRenderer: %p [%p]\n", posRenderer, b2);
1003 WTF_LOG(Editing, "posRenderedOffset: %d\n", posRenderedOffset);
1004 WTF_LOG(Editing, "node min/max: %d:%d\n", caretMinOffset(deprecatedNode()), caretMaxOffset(deprecatedNode()));
1005 WTF_LOG(Editing, "pos node min/max: %d:%d\n", caretMinOffset(pos.deprecatedNode()), caretMaxOffset(pos.deprecatedNode()));
1006 WTF_LOG(Editing, "----------------------------------------------------------------------\n");
1012 if (b1->root() != b2->root()) {
1016 if (nextRenderedEditable(deprecatedNode()) == pos.deprecatedNode()
1017 && thisRenderedOffset == caretMaxOffset(deprecatedNode()) && !posRenderedOffset) {
1021 if (previousRenderedEditable(deprecatedNode()) == pos.deprecatedNode()
1022 && !thisRenderedOffset && posRenderedOffset == caretMaxOffset(pos.deprecatedNode())) {
1029 // This assumes that it starts in editable content.
1030 Position Position::leadingWhitespacePosition(EAffinity affinity, bool considerNonCollapsibleWhitespace) const
1032 ASSERT(isEditablePosition(*this, ContentIsEditable, DoNotUpdateStyle));
1036 if (isHTMLBRElement(*upstream().deprecatedNode()))
1039 Position prev = previousCharacterPosition(affinity);
1040 if (prev != *this && prev.deprecatedNode()->inSameContainingBlockFlowElement(deprecatedNode()) && prev.deprecatedNode()->isTextNode()) {
1041 String string = toText(prev.deprecatedNode())->data();
1042 UChar c = string[prev.deprecatedEditingOffset()];
1043 if (considerNonCollapsibleWhitespace ? (isSpaceOrNewline(c) || c == noBreakSpace) : isCollapsibleWhitespace(c))
1044 if (isEditablePosition(prev))
1051 // This assumes that it starts in editable content.
1052 Position Position::trailingWhitespacePosition(EAffinity, bool considerNonCollapsibleWhitespace) const
1054 ASSERT(isEditablePosition(*this, ContentIsEditable, DoNotUpdateStyle));
1058 VisiblePosition v(*this);
1059 UChar c = v.characterAfter();
1060 // The space must not be in another paragraph and it must be editable.
1061 if (!isEndOfParagraph(v) && v.next(CannotCrossEditingBoundary).isNotNull())
1062 if (considerNonCollapsibleWhitespace ? (isSpaceOrNewline(c) || c == noBreakSpace) : isCollapsibleWhitespace(c))
1068 void Position::getInlineBoxAndOffset(EAffinity affinity, InlineBox*& inlineBox, int& caretOffset) const
1070 getInlineBoxAndOffset(affinity, primaryDirection(), inlineBox, caretOffset);
1073 static bool isNonTextLeafChild(RenderObject* object)
1075 if (object->slowFirstChild())
1077 if (object->isText())
1082 static InlineTextBox* searchAheadForBetterMatch(RenderObject* renderer)
1084 RenderBlock* container = renderer->containingBlock();
1085 RenderObject* next = renderer;
1086 while ((next = next->nextInPreOrder(container))) {
1087 if (next->isRenderBlock())
1091 if (isNonTextLeafChild(next))
1093 if (next->isText()) {
1094 InlineTextBox* match = 0;
1095 int minOffset = INT_MAX;
1096 for (InlineTextBox* box = toRenderText(next)->firstTextBox(); box; box = box->nextTextBox()) {
1097 int caretMinOffset = box->caretMinOffset();
1098 if (caretMinOffset < minOffset) {
1100 minOffset = caretMinOffset;
1110 static Position downstreamIgnoringEditingBoundaries(Position position)
1112 Position lastPosition;
1113 while (position != lastPosition) {
1114 lastPosition = position;
1115 position = position.downstream(CanCrossEditingBoundary);
1120 static Position upstreamIgnoringEditingBoundaries(Position position)
1122 Position lastPosition;
1123 while (position != lastPosition) {
1124 lastPosition = position;
1125 position = position.upstream(CanCrossEditingBoundary);
1130 void Position::getInlineBoxAndOffset(EAffinity affinity, TextDirection primaryDirection, InlineBox*& inlineBox, int& caretOffset) const
1132 caretOffset = deprecatedEditingOffset();
1133 RenderObject* renderer = deprecatedNode()->renderer();
1135 if (!renderer->isText()) {
1137 if (canHaveChildrenForEditing(deprecatedNode()) && renderer->isRenderBlockFlow() && hasRenderedNonAnonymousDescendantsWithHeight(renderer)) {
1138 // Try a visually equivalent position with possibly opposite editability. This helps in case |this| is in
1139 // an editable block but surrounded by non-editable positions. It acts to negate the logic at the beginning
1140 // of RenderObject::createVisiblePosition().
1141 Position equivalent = downstreamIgnoringEditingBoundaries(*this);
1142 if (equivalent == *this) {
1143 equivalent = upstreamIgnoringEditingBoundaries(*this);
1144 if (equivalent == *this || downstreamIgnoringEditingBoundaries(equivalent) == *this)
1148 equivalent.getInlineBoxAndOffset(UPSTREAM, primaryDirection, inlineBox, caretOffset);
1151 if (renderer->isBox()) {
1152 inlineBox = toRenderBox(renderer)->inlineBoxWrapper();
1153 if (!inlineBox || (caretOffset > inlineBox->caretMinOffset() && caretOffset < inlineBox->caretMaxOffset()))
1157 RenderText* textRenderer = toRenderText(renderer);
1160 InlineTextBox* candidate = 0;
1162 for (box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
1163 int caretMinOffset = box->caretMinOffset();
1164 int caretMaxOffset = box->caretMaxOffset();
1166 if (caretOffset < caretMinOffset || caretOffset > caretMaxOffset || (caretOffset == caretMaxOffset && box->isLineBreak()))
1169 if (caretOffset > caretMinOffset && caretOffset < caretMaxOffset) {
1174 if (((caretOffset == caretMaxOffset) ^ (affinity == DOWNSTREAM))
1175 || ((caretOffset == caretMinOffset) ^ (affinity == UPSTREAM))
1176 || (caretOffset == caretMaxOffset && box->nextLeafChild() && box->nextLeafChild()->isLineBreak()))
1181 if (candidate && candidate == textRenderer->lastTextBox() && affinity == DOWNSTREAM) {
1182 box = searchAheadForBetterMatch(textRenderer);
1184 caretOffset = box->caretMinOffset();
1186 inlineBox = box ? box : candidate;
1192 unsigned char level = inlineBox->bidiLevel();
1194 if (inlineBox->direction() == primaryDirection) {
1195 if (caretOffset == inlineBox->caretRightmostOffset()) {
1196 InlineBox* nextBox = inlineBox->nextLeafChild();
1197 if (!nextBox || nextBox->bidiLevel() >= level)
1200 level = nextBox->bidiLevel();
1201 InlineBox* prevBox = inlineBox;
1203 prevBox = prevBox->prevLeafChild();
1204 } while (prevBox && prevBox->bidiLevel() > level);
1206 if (prevBox && prevBox->bidiLevel() == level) // For example, abc FED 123 ^ CBA
1209 // For example, abc 123 ^ CBA
1210 while (InlineBox* nextBox = inlineBox->nextLeafChild()) {
1211 if (nextBox->bidiLevel() < level)
1213 inlineBox = nextBox;
1215 caretOffset = inlineBox->caretRightmostOffset();
1217 InlineBox* prevBox = inlineBox->prevLeafChild();
1218 if (!prevBox || prevBox->bidiLevel() >= level)
1221 level = prevBox->bidiLevel();
1222 InlineBox* nextBox = inlineBox;
1224 nextBox = nextBox->nextLeafChild();
1225 } while (nextBox && nextBox->bidiLevel() > level);
1227 if (nextBox && nextBox->bidiLevel() == level)
1230 while (InlineBox* prevBox = inlineBox->prevLeafChild()) {
1231 if (prevBox->bidiLevel() < level)
1233 inlineBox = prevBox;
1235 caretOffset = inlineBox->caretLeftmostOffset();
1240 if (caretOffset == inlineBox->caretLeftmostOffset()) {
1241 InlineBox* prevBox = inlineBox->prevLeafChildIgnoringLineBreak();
1242 if (!prevBox || prevBox->bidiLevel() < level) {
1243 // Left edge of a secondary run. Set to the right edge of the entire run.
1244 while (InlineBox* nextBox = inlineBox->nextLeafChildIgnoringLineBreak()) {
1245 if (nextBox->bidiLevel() < level)
1247 inlineBox = nextBox;
1249 caretOffset = inlineBox->caretRightmostOffset();
1250 } else if (prevBox->bidiLevel() > level) {
1251 // Right edge of a "tertiary" run. Set to the left edge of that run.
1252 while (InlineBox* tertiaryBox = inlineBox->prevLeafChildIgnoringLineBreak()) {
1253 if (tertiaryBox->bidiLevel() <= level)
1255 inlineBox = tertiaryBox;
1257 caretOffset = inlineBox->caretLeftmostOffset();
1260 InlineBox* nextBox = inlineBox->nextLeafChildIgnoringLineBreak();
1261 if (!nextBox || nextBox->bidiLevel() < level) {
1262 // Right edge of a secondary run. Set to the left edge of the entire run.
1263 while (InlineBox* prevBox = inlineBox->prevLeafChildIgnoringLineBreak()) {
1264 if (prevBox->bidiLevel() < level)
1266 inlineBox = prevBox;
1268 if (m_anchorNode->selfOrAncestorHasDirAutoAttribute())
1269 caretOffset = inlineBox->bidiLevel() < level ? inlineBox->caretLeftmostOffset() : inlineBox->caretRightmostOffset();
1271 caretOffset = inlineBox->caretLeftmostOffset();
1272 } else if (nextBox->bidiLevel() > level) {
1273 // Left edge of a "tertiary" run. Set to the right edge of that run.
1274 while (InlineBox* tertiaryBox = inlineBox->nextLeafChildIgnoringLineBreak()) {
1275 if (tertiaryBox->bidiLevel() <= level)
1277 inlineBox = tertiaryBox;
1279 caretOffset = inlineBox->caretRightmostOffset();
1284 TextDirection Position::primaryDirection() const
1286 TextDirection primaryDirection = LTR;
1287 for (const RenderObject* r = m_anchorNode->renderer(); r; r = r->parent()) {
1288 if (r->isRenderBlockFlow()) {
1289 primaryDirection = r->style()->direction();
1294 return primaryDirection;
1297 void Position::trace(Visitor* visitor)
1299 visitor->trace(m_anchorNode);
1302 void Position::debugPosition(const char* msg) const
1305 fprintf(stderr, "Position [%s]: null\n", msg);
1307 fprintf(stderr, "Position [%s]: %s [%p] at %d\n", msg, deprecatedNode()->nodeName().utf8().data(), deprecatedNode(), m_offset);
1312 void Position::formatForDebugger(char* buffer, unsigned length) const
1314 StringBuilder result;
1317 result.appendLiteral("<null>");
1320 result.appendLiteral("offset ");
1321 result.appendNumber(m_offset);
1322 result.appendLiteral(" of ");
1323 deprecatedNode()->formatForDebugger(s, sizeof(s));
1327 strncpy(buffer, result.toString().utf8().data(), length - 1);
1330 void Position::showAnchorTypeAndOffset() const
1332 if (m_isLegacyEditingPosition)
1333 fputs("legacy, ", stderr);
1334 switch (anchorType()) {
1335 case PositionIsOffsetInAnchor:
1336 fputs("offset", stderr);
1338 case PositionIsBeforeChildren:
1339 fputs("beforeChildren", stderr);
1341 case PositionIsAfterChildren:
1342 fputs("afterChildren", stderr);
1344 case PositionIsBeforeAnchor:
1345 fputs("before", stderr);
1347 case PositionIsAfterAnchor:
1348 fputs("after", stderr);
1351 fprintf(stderr, ", offset:%d\n", m_offset);
1354 void Position::showTreeForThis() const
1357 anchorNode()->showTreeForThis();
1358 showAnchorTypeAndOffset();
1366 } // namespace WebCore
1370 void showTree(const WebCore::Position& pos)
1372 pos.showTreeForThis();
1375 void showTree(const WebCore::Position* pos)
1378 pos->showTreeForThis();