2 * Copyright (C) 2004, 2005, 2006 Apple Computer, 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 "VisibleSelection.h"
31 #include "htmlediting.h"
32 #include "TextIterator.h"
33 #include "VisiblePosition.h"
34 #include "visible_units.h"
37 #include <wtf/Assertions.h>
38 #include <wtf/text/CString.h>
39 #include <wtf/unicode/CharacterNames.h>
43 VisibleSelection::VisibleSelection()
44 : m_affinity(DOWNSTREAM)
45 , m_selectionType(NoSelection)
50 VisibleSelection::VisibleSelection(const Position& pos, EAffinity affinity)
53 , m_affinity(affinity)
58 VisibleSelection::VisibleSelection(const Position& base, const Position& extent, EAffinity affinity)
61 , m_affinity(affinity)
66 VisibleSelection::VisibleSelection(const VisiblePosition& pos)
67 : m_base(pos.deepEquivalent())
68 , m_extent(pos.deepEquivalent())
69 , m_affinity(pos.affinity())
74 VisibleSelection::VisibleSelection(const VisiblePosition& base, const VisiblePosition& extent)
75 : m_base(base.deepEquivalent())
76 , m_extent(extent.deepEquivalent())
77 , m_affinity(base.affinity())
82 VisibleSelection::VisibleSelection(const Range* range, EAffinity affinity)
83 : m_base(range->startPosition())
84 , m_extent(range->endPosition())
85 , m_affinity(affinity)
90 VisibleSelection VisibleSelection::selectionFromContentsOfNode(Node* node)
92 ASSERT(!editingIgnoresContent(node));
93 return VisibleSelection(firstPositionInNode(node), lastPositionInNode(node), DOWNSTREAM);
96 void VisibleSelection::setBase(const Position& position)
102 void VisibleSelection::setBase(const VisiblePosition& visiblePosition)
104 m_base = visiblePosition.deepEquivalent();
108 void VisibleSelection::setExtent(const Position& position)
114 void VisibleSelection::setExtent(const VisiblePosition& visiblePosition)
116 m_extent = visiblePosition.deepEquivalent();
120 PassRefPtr<Range> VisibleSelection::firstRange() const
124 Position start = m_start.parentAnchoredEquivalent();
125 Position end = m_end.parentAnchoredEquivalent();
126 return Range::create(start.anchorNode()->document(), start, end);
129 PassRefPtr<Range> VisibleSelection::toNormalizedRange() const
134 // Make sure we have an updated layout since this function is called
135 // in the course of running edit commands which modify the DOM.
136 // Failing to call this can result in equivalentXXXPosition calls returning
137 // incorrect results.
138 m_start.anchorNode()->document()->updateLayout();
140 // Check again, because updating layout can clear the selection.
146 // If the selection is a caret, move the range start upstream. This helps us match
147 // the conventions of text editors tested, which make style determinations based
148 // on the character before the caret, if any.
149 s = m_start.upstream().parentAnchoredEquivalent();
152 // If the selection is a range, select the minimum range that encompasses the selection.
153 // Again, this is to match the conventions of text editors tested, which make style
154 // determinations based on the first character of the selection.
155 // For instance, this operation helps to make sure that the "X" selected below is the
156 // only thing selected. The range should not be allowed to "leak" out to the end of the
157 // previous text node, or to the beginning of the next text node, each of which has a
160 // On a treasure map, <b>X</b> marks the spot.
164 s = m_start.downstream();
165 e = m_end.upstream();
166 if (comparePositions(s, e) > 0) {
167 // Make sure the start is before the end.
168 // The end can wind up before the start if collapsed whitespace is the only thing selected.
173 s = s.parentAnchoredEquivalent();
174 e = e.parentAnchoredEquivalent();
177 if (!s.containerNode() || !e.containerNode())
180 // VisibleSelections are supposed to always be valid. This constructor will ASSERT
181 // if a valid range could not be created, which is fine for this callsite.
182 return Range::create(s.anchorNode()->document(), s, e);
185 bool VisibleSelection::expandUsingGranularity(TextGranularity granularity)
190 validate(granularity);
194 static PassRefPtr<Range> makeSearchRange(const Position& pos)
196 Node* n = pos.deprecatedNode();
199 Document* d = n->document();
200 Node* de = d->documentElement();
203 Node* boundary = n->enclosingBlockFlowElement();
207 RefPtr<Range> searchRange(Range::create(d));
208 ExceptionCode ec = 0;
210 Position start(pos.parentAnchoredEquivalent());
211 searchRange->selectNodeContents(boundary, ec);
212 searchRange->setStart(start.containerNode(), start.offsetInContainerNode(), ec);
218 return searchRange.release();
221 bool VisibleSelection::isAll(EditingBoundaryCrossingRule rule) const
223 return !shadowTreeRootNode() && visibleStart().previous(rule).isNull() && visibleEnd().next(rule).isNull();
226 void VisibleSelection::appendTrailingWhitespace()
228 RefPtr<Range> searchRange = makeSearchRange(m_end);
232 CharacterIterator charIt(searchRange.get(), TextIteratorEmitsCharactersBetweenAllVisiblePositions);
234 for (; charIt.length(); charIt.advance(1)) {
235 UChar c = charIt.characters()[0];
236 if ((!isSpaceOrNewline(c) && c != noBreakSpace) || c == '\n')
238 m_end = charIt.range()->endPosition();
242 void VisibleSelection::setBaseAndExtentToDeepEquivalents()
244 // Move the selection to rendered positions, if possible.
245 bool baseAndExtentEqual = m_base == m_extent;
246 if (m_base.isNotNull()) {
247 m_base = VisiblePosition(m_base, m_affinity).deepEquivalent();
248 if (baseAndExtentEqual)
251 if (m_extent.isNotNull() && !baseAndExtentEqual)
252 m_extent = VisiblePosition(m_extent, m_affinity).deepEquivalent();
254 // Make sure we do not have a dangling base or extent.
255 if (m_base.isNull() && m_extent.isNull())
256 m_baseIsFirst = true;
257 else if (m_base.isNull()) {
259 m_baseIsFirst = true;
260 } else if (m_extent.isNull()) {
262 m_baseIsFirst = true;
264 m_baseIsFirst = comparePositions(m_base, m_extent) <= 0;
267 void VisibleSelection::setStartAndEndFromBaseAndExtentRespectingGranularity(TextGranularity granularity)
277 switch (granularity) {
278 case CharacterGranularity:
279 // Don't do any expansion.
281 case WordGranularity: {
282 // General case: Select the word the caret is positioned inside of, or at the start of (RightWordIfOnBoundary).
283 // Edge case: If the caret is after the last word in a soft-wrapped line or the last word in
284 // the document, select that last word (LeftWordIfOnBoundary).
285 // Edge case: If the caret is after the last word in a paragraph, select from the the end of the
286 // last word to the line break (also RightWordIfOnBoundary);
287 VisiblePosition start = VisiblePosition(m_start, m_affinity);
288 VisiblePosition originalEnd(m_end, m_affinity);
289 EWordSide side = RightWordIfOnBoundary;
290 if (isEndOfDocument(start) || (isEndOfLine(start) && !isStartOfLine(start) && !isEndOfParagraph(start)))
291 side = LeftWordIfOnBoundary;
292 m_start = startOfWord(start, side).deepEquivalent();
293 side = RightWordIfOnBoundary;
294 if (isEndOfDocument(originalEnd) || (isEndOfLine(originalEnd) && !isStartOfLine(originalEnd) && !isEndOfParagraph(originalEnd)))
295 side = LeftWordIfOnBoundary;
297 VisiblePosition wordEnd(endOfWord(originalEnd, side));
298 VisiblePosition end(wordEnd);
300 if (isEndOfParagraph(originalEnd) && !isEmptyTableCell(m_start.deprecatedNode())) {
301 // Select the paragraph break (the space from the end of a paragraph to the start of
302 // the next one) to match TextEdit.
303 end = wordEnd.next();
305 if (Node* table = isFirstPositionAfterTable(end)) {
306 // The paragraph break after the last paragraph in the last cell of a block table ends
307 // at the start of the paragraph after the table.
309 end = end.next(CannotCrossEditingBoundary);
319 m_end = end.deepEquivalent();
322 case SentenceGranularity: {
323 m_start = startOfSentence(VisiblePosition(m_start, m_affinity)).deepEquivalent();
324 m_end = endOfSentence(VisiblePosition(m_end, m_affinity)).deepEquivalent();
327 case LineGranularity: {
328 m_start = startOfLine(VisiblePosition(m_start, m_affinity)).deepEquivalent();
329 VisiblePosition end = endOfLine(VisiblePosition(m_end, m_affinity));
330 // If the end of this line is at the end of a paragraph, include the space
331 // after the end of the line in the selection.
332 if (isEndOfParagraph(end)) {
333 VisiblePosition next = end.next();
334 if (next.isNotNull())
337 m_end = end.deepEquivalent();
341 m_start = startOfLine(VisiblePosition(m_start, m_affinity)).deepEquivalent();
342 m_end = endOfLine(VisiblePosition(m_end, m_affinity)).deepEquivalent();
344 case ParagraphGranularity: {
345 VisiblePosition pos(m_start, m_affinity);
346 if (isStartOfLine(pos) && isEndOfDocument(pos))
347 pos = pos.previous();
348 m_start = startOfParagraph(pos).deepEquivalent();
349 VisiblePosition visibleParagraphEnd = endOfParagraph(VisiblePosition(m_end, m_affinity));
351 // Include the "paragraph break" (the space from the end of this paragraph to the start
352 // of the next one) in the selection.
353 VisiblePosition end(visibleParagraphEnd.next());
355 if (Node* table = isFirstPositionAfterTable(end)) {
356 // The paragraph break after the last paragraph in the last cell of a block table ends
357 // at the start of the paragraph after the table, not at the position just after the table.
359 end = end.next(CannotCrossEditingBoundary);
360 // There is no parargraph break after the last paragraph in the last cell of an inline table.
362 end = visibleParagraphEnd;
366 end = visibleParagraphEnd;
368 m_end = end.deepEquivalent();
371 case DocumentBoundary:
372 m_start = startOfDocument(VisiblePosition(m_start, m_affinity)).deepEquivalent();
373 m_end = endOfDocument(VisiblePosition(m_end, m_affinity)).deepEquivalent();
375 case ParagraphBoundary:
376 m_start = startOfParagraph(VisiblePosition(m_start, m_affinity)).deepEquivalent();
377 m_end = endOfParagraph(VisiblePosition(m_end, m_affinity)).deepEquivalent();
379 case SentenceBoundary:
380 m_start = startOfSentence(VisiblePosition(m_start, m_affinity)).deepEquivalent();
381 m_end = endOfSentence(VisiblePosition(m_end, m_affinity)).deepEquivalent();
385 // Make sure we do not have a dangling start or end.
386 if (m_start.isNull())
392 void VisibleSelection::updateSelectionType()
394 if (m_start.isNull()) {
395 ASSERT(m_end.isNull());
396 m_selectionType = NoSelection;
397 } else if (m_start == m_end || m_start.upstream() == m_end.upstream()) {
398 m_selectionType = CaretSelection;
400 m_selectionType = RangeSelection;
402 // Affinity only makes sense for a caret
403 if (m_selectionType != CaretSelection)
404 m_affinity = DOWNSTREAM;
407 void VisibleSelection::validate(TextGranularity granularity)
409 setBaseAndExtentToDeepEquivalents();
410 setStartAndEndFromBaseAndExtentRespectingGranularity(granularity);
411 adjustSelectionToAvoidCrossingEditingBoundaries();
412 updateSelectionType();
414 if (selectionType() == RangeSelection) {
415 // "Constrain" the selection to be the smallest equivalent range of nodes.
416 // This is a somewhat arbitrary choice, but experience shows that it is
417 // useful to make to make the selection "canonical" (if only for
418 // purposes of comparing selections). This is an ideal point of the code
419 // to do this operation, since all selection changes that result in a RANGE
420 // come through here before anyone uses it.
421 // FIXME: Canonicalizing is good, but haven't we already done it (when we
422 // set these two positions to VisiblePosition deepEquivalent()s above)?
423 m_start = m_start.downstream();
424 m_end = m_end.upstream();
428 // FIXME: This function breaks the invariant of this class.
429 // But because we use VisibleSelection to store values in editing commands for use when
430 // undoing the command, we need to be able to create a selection that while currently
431 // invalid, will be valid once the changes are undone. This is a design problem.
432 // To fix it we either need to change the invariants of VisibleSelection or create a new
433 // class for editing to use that can manipulate selections that are not currently valid.
434 void VisibleSelection::setWithoutValidation(const Position& base, const Position& extent)
436 ASSERT(!base.isNull());
437 ASSERT(!extent.isNull());
438 ASSERT(m_affinity == DOWNSTREAM);
441 m_baseIsFirst = comparePositions(base, extent) <= 0;
449 m_selectionType = base == extent ? CaretSelection : RangeSelection;
452 void VisibleSelection::adjustSelectionToAvoidCrossingEditingBoundaries()
454 if (m_base.isNull() || m_start.isNull() || m_end.isNull())
457 Node* baseRoot = highestEditableRoot(m_base);
458 Node* startRoot = highestEditableRoot(m_start);
459 Node* endRoot = highestEditableRoot(m_end);
461 Node* baseEditableAncestor = lowestEditableAncestor(m_base.containerNode());
463 // The base, start and end are all in the same region. No adjustment necessary.
464 if (baseRoot == startRoot && baseRoot == endRoot)
467 // The selection is based in editable content.
469 // If the start is outside the base's editable root, cap it at the start of that root.
470 // If the start is in non-editable content that is inside the base's editable root, put it
471 // at the first editable position after start inside the base's editable root.
472 if (startRoot != baseRoot) {
473 VisiblePosition first = firstEditablePositionAfterPositionInRoot(m_start, baseRoot);
474 m_start = first.deepEquivalent();
475 if (m_start.isNull()) {
476 ASSERT_NOT_REACHED();
480 // If the end is outside the base's editable root, cap it at the end of that root.
481 // If the end is in non-editable content that is inside the base's root, put it
482 // at the last editable position before the end inside the base's root.
483 if (endRoot != baseRoot) {
484 VisiblePosition last = lastEditablePositionBeforePositionInRoot(m_end, baseRoot);
485 m_end = last.deepEquivalent();
489 // The selection is based in non-editable content.
491 // FIXME: Non-editable pieces inside editable content should be atomic, in the same way that editable
492 // pieces in non-editable content are atomic.
494 // The selection ends in editable content or non-editable content inside a different editable ancestor,
495 // move backward until non-editable content inside the same lowest editable ancestor is reached.
496 Node* endEditableAncestor = lowestEditableAncestor(m_end.containerNode());
497 if (endRoot || endEditableAncestor != baseEditableAncestor) {
499 Position p = previousVisuallyDistinctCandidate(m_end);
500 Node* shadowAncestor = endRoot ? endRoot->shadowAncestorNode() : 0;
501 if (p.isNull() && endRoot && (shadowAncestor != endRoot))
502 p = positionAfterNode(shadowAncestor);
503 while (p.isNotNull() && !(lowestEditableAncestor(p.containerNode()) == baseEditableAncestor && !isEditablePosition(p))) {
504 Node* root = editableRootForPosition(p);
505 shadowAncestor = root ? root->shadowAncestorNode() : 0;
506 p = isAtomicNode(p.containerNode()) ? positionInParentBeforeNode(p.containerNode()) : previousVisuallyDistinctCandidate(p);
507 if (p.isNull() && (shadowAncestor != root))
508 p = positionAfterNode(shadowAncestor);
510 VisiblePosition previous(p);
512 if (previous.isNull()) {
513 // The selection crosses an Editing boundary. This is a
514 // programmer error in the editing code. Happy debugging!
515 ASSERT_NOT_REACHED();
517 m_extent = Position();
521 m_end = previous.deepEquivalent();
524 // The selection starts in editable content or non-editable content inside a different editable ancestor,
525 // move forward until non-editable content inside the same lowest editable ancestor is reached.
526 Node* startEditableAncestor = lowestEditableAncestor(m_start.containerNode());
527 if (startRoot || startEditableAncestor != baseEditableAncestor) {
528 Position p = nextVisuallyDistinctCandidate(m_start);
529 Node* shadowAncestor = startRoot ? startRoot->shadowAncestorNode() : 0;
530 if (p.isNull() && startRoot && (shadowAncestor != startRoot))
531 p = positionBeforeNode(shadowAncestor);
532 while (p.isNotNull() && !(lowestEditableAncestor(p.containerNode()) == baseEditableAncestor && !isEditablePosition(p))) {
533 Node* root = editableRootForPosition(p);
534 shadowAncestor = root ? root->shadowAncestorNode() : 0;
535 p = isAtomicNode(p.containerNode()) ? positionInParentAfterNode(p.containerNode()) : nextVisuallyDistinctCandidate(p);
536 if (p.isNull() && (shadowAncestor != root))
537 p = positionBeforeNode(shadowAncestor);
539 VisiblePosition next(p);
542 // The selection crosses an Editing boundary. This is a
543 // programmer error in the editing code. Happy debugging!
544 ASSERT_NOT_REACHED();
546 m_extent = Position();
550 m_start = next.deepEquivalent();
554 // Correct the extent if necessary.
555 if (baseEditableAncestor != lowestEditableAncestor(m_extent.containerNode()))
556 m_extent = m_baseIsFirst ? m_end : m_start;
559 bool VisibleSelection::isContentEditable() const
561 return isEditablePosition(start());
564 bool VisibleSelection::isContentRichlyEditable() const
566 return isRichlyEditablePosition(start());
569 Element* VisibleSelection::rootEditableElement() const
571 return editableRootForPosition(start());
574 Node* VisibleSelection::shadowTreeRootNode() const
576 return start().deprecatedNode() ? start().deprecatedNode()->shadowTreeRootNode() : 0;
581 void VisibleSelection::debugPosition() const
583 fprintf(stderr, "VisibleSelection ===============\n");
585 if (!m_start.anchorNode())
586 fputs("pos: null", stderr);
587 else if (m_start == m_end) {
588 fprintf(stderr, "pos: %s ", m_start.anchorNode()->nodeName().utf8().data());
589 m_start.showAnchorTypeAndOffset();
591 fprintf(stderr, "start: %s ", m_start.anchorNode()->nodeName().utf8().data());
592 m_start.showAnchorTypeAndOffset();
593 fprintf(stderr, "end: %s ", m_end.anchorNode()->nodeName().utf8().data());
594 m_end.showAnchorTypeAndOffset();
597 fprintf(stderr, "================================\n");
600 void VisibleSelection::formatForDebugger(char* buffer, unsigned length) const
608 const int FormatBufferSize = 1024;
609 char s[FormatBufferSize];
611 start().formatForDebugger(s, FormatBufferSize);
614 end().formatForDebugger(s, FormatBufferSize);
618 strncpy(buffer, result.utf8().data(), length - 1);
621 void VisibleSelection::showTreeForThis() const
623 if (start().anchorNode()) {
624 start().anchorNode()->showTreeAndMark(start().anchorNode(), "S", end().anchorNode(), "E");
625 fputs("start: ", stderr);
626 start().showAnchorTypeAndOffset();
627 fputs("end: ", stderr);
628 end().showAnchorTypeAndOffset();
634 } // namespace WebCore
638 void showTree(const WebCore::VisibleSelection& sel)
640 sel.showTreeForThis();
643 void showTree(const WebCore::VisibleSelection* sel)
646 sel->showTreeForThis();