VisibleSelection.cpp revision cad810f21b803229eb11403f9209855525a25d57
1/*
2 * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE 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.
24 */
25
26#include "config.h"
27#include "VisibleSelection.h"
28
29#include "CharacterNames.h"
30#include "Document.h"
31#include "Element.h"
32#include "htmlediting.h"
33#include "TextIterator.h"
34#include "VisiblePosition.h"
35#include "visible_units.h"
36#include "Range.h"
37
38#include <wtf/Assertions.h>
39#include <wtf/text/CString.h>
40#include <stdio.h>
41
42namespace WebCore {
43
44VisibleSelection::VisibleSelection()
45    : m_affinity(DOWNSTREAM)
46    , m_selectionType(NoSelection)
47    , m_baseIsFirst(true)
48{
49}
50
51VisibleSelection::VisibleSelection(const Position& pos, EAffinity affinity)
52    : m_base(pos)
53    , m_extent(pos)
54    , m_affinity(affinity)
55{
56    validate();
57}
58
59VisibleSelection::VisibleSelection(const Position& base, const Position& extent, EAffinity affinity)
60    : m_base(base)
61    , m_extent(extent)
62    , m_affinity(affinity)
63{
64    validate();
65}
66
67VisibleSelection::VisibleSelection(const VisiblePosition& pos)
68    : m_base(pos.deepEquivalent())
69    , m_extent(pos.deepEquivalent())
70    , m_affinity(pos.affinity())
71{
72    validate();
73}
74
75VisibleSelection::VisibleSelection(const VisiblePosition& base, const VisiblePosition& extent)
76    : m_base(base.deepEquivalent())
77    , m_extent(extent.deepEquivalent())
78    , m_affinity(base.affinity())
79{
80    validate();
81}
82
83VisibleSelection::VisibleSelection(const Range* range, EAffinity affinity)
84    : m_base(range->startPosition())
85    , m_extent(range->endPosition())
86    , m_affinity(affinity)
87{
88    validate();
89}
90
91VisibleSelection VisibleSelection::selectionFromContentsOfNode(Node* node)
92{
93    return VisibleSelection(firstDeepEditingPositionForNode(node), lastDeepEditingPositionForNode(node), DOWNSTREAM);
94}
95
96void VisibleSelection::setBase(const Position& position)
97{
98    m_base = position;
99    validate();
100}
101
102void VisibleSelection::setBase(const VisiblePosition& visiblePosition)
103{
104    m_base = visiblePosition.deepEquivalent();
105    validate();
106}
107
108void VisibleSelection::setExtent(const Position& position)
109{
110    m_extent = position;
111    validate();
112}
113
114void VisibleSelection::setExtent(const VisiblePosition& visiblePosition)
115{
116    m_extent = visiblePosition.deepEquivalent();
117    validate();
118}
119
120PassRefPtr<Range> VisibleSelection::firstRange() const
121{
122    if (isNone())
123        return 0;
124    Position start = rangeCompliantEquivalent(m_start);
125    Position end = rangeCompliantEquivalent(m_end);
126    return Range::create(start.node()->document(), start, end);
127}
128
129PassRefPtr<Range> VisibleSelection::toNormalizedRange() const
130{
131    if (isNone())
132        return 0;
133
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.node()->document()->updateLayout();
139
140    // Check again, because updating layout can clear the selection.
141    if (isNone())
142        return 0;
143
144    Position s, e;
145    if (isCaret()) {
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 = rangeCompliantEquivalent(m_start.upstream());
150        e = s;
151    } else {
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
158        // different style.
159        //
160        // On a treasure map, <b>X</b> marks the spot.
161        //                       ^ selected
162        //
163        ASSERT(isRange());
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.
169            Position tmp = s;
170            s = e;
171            e = tmp;
172        }
173        s = rangeCompliantEquivalent(s);
174        e = rangeCompliantEquivalent(e);
175    }
176
177    // VisibleSelections are supposed to always be valid.  This constructor will ASSERT
178    // if a valid range could not be created, which is fine for this callsite.
179    return Range::create(s.node()->document(), s, e);
180}
181
182bool VisibleSelection::expandUsingGranularity(TextGranularity granularity)
183{
184    if (isNone())
185        return false;
186
187    validate(granularity);
188    return true;
189}
190
191static PassRefPtr<Range> makeSearchRange(const Position& pos)
192{
193    Node* n = pos.node();
194    if (!n)
195        return 0;
196    Document* d = n->document();
197    Node* de = d->documentElement();
198    if (!de)
199        return 0;
200    Node* boundary = n->enclosingBlockFlowElement();
201    if (!boundary)
202        return 0;
203
204    RefPtr<Range> searchRange(Range::create(d));
205    ExceptionCode ec = 0;
206
207    Position start(rangeCompliantEquivalent(pos));
208    searchRange->selectNodeContents(boundary, ec);
209    searchRange->setStart(start.node(), start.deprecatedEditingOffset(), ec);
210
211    ASSERT(!ec);
212    if (ec)
213        return 0;
214
215    return searchRange.release();
216}
217
218bool VisibleSelection::isAll(StayInEditableContent stayInEditableContent) const
219{
220    return !shadowTreeRootNode() && visibleStart().previous(stayInEditableContent).isNull() && visibleEnd().next(stayInEditableContent).isNull();
221}
222
223void VisibleSelection::appendTrailingWhitespace()
224{
225    RefPtr<Range> searchRange = makeSearchRange(m_end);
226    if (!searchRange)
227        return;
228
229    CharacterIterator charIt(searchRange.get(), TextIteratorEmitsCharactersBetweenAllVisiblePositions);
230
231    for (; charIt.length(); charIt.advance(1)) {
232        UChar c = charIt.characters()[0];
233        if ((!isSpaceOrNewline(c) && c != noBreakSpace) || c == '\n')
234            break;
235        m_end = charIt.range()->endPosition();
236    }
237}
238
239void VisibleSelection::setBaseAndExtentToDeepEquivalents()
240{
241    // Move the selection to rendered positions, if possible.
242    bool baseAndExtentEqual = m_base == m_extent;
243    if (m_base.isNotNull()) {
244        m_base = VisiblePosition(m_base, m_affinity).deepEquivalent();
245        if (baseAndExtentEqual)
246            m_extent = m_base;
247    }
248    if (m_extent.isNotNull() && !baseAndExtentEqual)
249        m_extent = VisiblePosition(m_extent, m_affinity).deepEquivalent();
250
251    // Make sure we do not have a dangling base or extent.
252    if (m_base.isNull() && m_extent.isNull())
253        m_baseIsFirst = true;
254    else if (m_base.isNull()) {
255        m_base = m_extent;
256        m_baseIsFirst = true;
257    } else if (m_extent.isNull()) {
258        m_extent = m_base;
259        m_baseIsFirst = true;
260    } else
261        m_baseIsFirst = comparePositions(m_base, m_extent) <= 0;
262}
263
264void VisibleSelection::setStartAndEndFromBaseAndExtentRespectingGranularity(TextGranularity granularity)
265{
266    if (m_baseIsFirst) {
267        m_start = m_base;
268        m_end = m_extent;
269    } else {
270        m_start = m_extent;
271        m_end = m_base;
272    }
273
274    switch (granularity) {
275        case CharacterGranularity:
276            // Don't do any expansion.
277            break;
278        case WordGranularity: {
279            // General case: Select the word the caret is positioned inside of, or at the start of (RightWordIfOnBoundary).
280            // Edge case: If the caret is after the last word in a soft-wrapped line or the last word in
281            // the document, select that last word (LeftWordIfOnBoundary).
282            // Edge case: If the caret is after the last word in a paragraph, select from the the end of the
283            // last word to the line break (also RightWordIfOnBoundary);
284            VisiblePosition start = VisiblePosition(m_start, m_affinity);
285            VisiblePosition originalEnd(m_end, m_affinity);
286            EWordSide side = RightWordIfOnBoundary;
287            if (isEndOfDocument(start) || (isEndOfLine(start) && !isStartOfLine(start) && !isEndOfParagraph(start)))
288                side = LeftWordIfOnBoundary;
289            m_start = startOfWord(start, side).deepEquivalent();
290            side = RightWordIfOnBoundary;
291            if (isEndOfDocument(originalEnd) || (isEndOfLine(originalEnd) && !isStartOfLine(originalEnd) && !isEndOfParagraph(originalEnd)))
292                side = LeftWordIfOnBoundary;
293
294            VisiblePosition wordEnd(endOfWord(originalEnd, side));
295            VisiblePosition end(wordEnd);
296
297            if (isEndOfParagraph(originalEnd) && !isEmptyTableCell(m_start.node())) {
298                // Select the paragraph break (the space from the end of a paragraph to the start of
299                // the next one) to match TextEdit.
300                end = wordEnd.next();
301
302                if (Node* table = isFirstPositionAfterTable(end)) {
303                    // The paragraph break after the last paragraph in the last cell of a block table ends
304                    // at the start of the paragraph after the table.
305                    if (isBlock(table))
306                        end = end.next(true);
307                    else
308                        end = wordEnd;
309                }
310
311                if (end.isNull())
312                    end = wordEnd;
313
314            }
315
316            m_end = end.deepEquivalent();
317            break;
318        }
319        case SentenceGranularity: {
320            m_start = startOfSentence(VisiblePosition(m_start, m_affinity)).deepEquivalent();
321            m_end = endOfSentence(VisiblePosition(m_end, m_affinity)).deepEquivalent();
322            break;
323        }
324        case LineGranularity: {
325            m_start = startOfLine(VisiblePosition(m_start, m_affinity)).deepEquivalent();
326            VisiblePosition end = endOfLine(VisiblePosition(m_end, m_affinity));
327            // If the end of this line is at the end of a paragraph, include the space
328            // after the end of the line in the selection.
329            if (isEndOfParagraph(end)) {
330                VisiblePosition next = end.next();
331                if (next.isNotNull())
332                    end = next;
333            }
334            m_end = end.deepEquivalent();
335            break;
336        }
337        case LineBoundary:
338            m_start = startOfLine(VisiblePosition(m_start, m_affinity)).deepEquivalent();
339            m_end = endOfLine(VisiblePosition(m_end, m_affinity)).deepEquivalent();
340            break;
341        case ParagraphGranularity: {
342            VisiblePosition pos(m_start, m_affinity);
343            if (isStartOfLine(pos) && isEndOfDocument(pos))
344                pos = pos.previous();
345            m_start = startOfParagraph(pos).deepEquivalent();
346            VisiblePosition visibleParagraphEnd = endOfParagraph(VisiblePosition(m_end, m_affinity));
347
348            // Include the "paragraph break" (the space from the end of this paragraph to the start
349            // of the next one) in the selection.
350            VisiblePosition end(visibleParagraphEnd.next());
351
352            if (Node* table = isFirstPositionAfterTable(end)) {
353                // The paragraph break after the last paragraph in the last cell of a block table ends
354                // at the start of the paragraph after the table, not at the position just after the table.
355                if (isBlock(table))
356                    end = end.next(true);
357                // There is no parargraph break after the last paragraph in the last cell of an inline table.
358                else
359                    end = visibleParagraphEnd;
360            }
361
362            if (end.isNull())
363                end = visibleParagraphEnd;
364
365            m_end = end.deepEquivalent();
366            break;
367        }
368        case DocumentBoundary:
369            m_start = startOfDocument(VisiblePosition(m_start, m_affinity)).deepEquivalent();
370            m_end = endOfDocument(VisiblePosition(m_end, m_affinity)).deepEquivalent();
371            break;
372        case ParagraphBoundary:
373            m_start = startOfParagraph(VisiblePosition(m_start, m_affinity)).deepEquivalent();
374            m_end = endOfParagraph(VisiblePosition(m_end, m_affinity)).deepEquivalent();
375            break;
376        case SentenceBoundary:
377            m_start = startOfSentence(VisiblePosition(m_start, m_affinity)).deepEquivalent();
378            m_end = endOfSentence(VisiblePosition(m_end, m_affinity)).deepEquivalent();
379            break;
380    }
381
382    // Make sure we do not have a dangling start or end.
383    if (m_start.isNull())
384        m_start = m_end;
385    if (m_end.isNull())
386        m_end = m_start;
387}
388
389void VisibleSelection::updateSelectionType()
390{
391    if (m_start.isNull()) {
392        ASSERT(m_end.isNull());
393        m_selectionType = NoSelection;
394    } else if (m_start == m_end || m_start.upstream() == m_end.upstream()) {
395        m_selectionType = CaretSelection;
396    } else
397        m_selectionType = RangeSelection;
398
399    // Affinity only makes sense for a caret
400    if (m_selectionType != CaretSelection)
401        m_affinity = DOWNSTREAM;
402}
403
404void VisibleSelection::validate(TextGranularity granularity)
405{
406    setBaseAndExtentToDeepEquivalents();
407    setStartAndEndFromBaseAndExtentRespectingGranularity(granularity);
408    adjustSelectionToAvoidCrossingEditingBoundaries();
409    updateSelectionType();
410
411    if (selectionType() == RangeSelection) {
412        // "Constrain" the selection to be the smallest equivalent range of nodes.
413        // This is a somewhat arbitrary choice, but experience shows that it is
414        // useful to make to make the selection "canonical" (if only for
415        // purposes of comparing selections). This is an ideal point of the code
416        // to do this operation, since all selection changes that result in a RANGE
417        // come through here before anyone uses it.
418        // FIXME: Canonicalizing is good, but haven't we already done it (when we
419        // set these two positions to VisiblePosition deepEquivalent()s above)?
420        m_start = m_start.downstream();
421        m_end = m_end.upstream();
422    }
423}
424
425// FIXME: This function breaks the invariant of this class.
426// But because we use VisibleSelection to store values in editing commands for use when
427// undoing the command, we need to be able to create a selection that while currently
428// invalid, will be valid once the changes are undone. This is a design problem.
429// To fix it we either need to change the invariants of VisibleSelection or create a new
430// class for editing to use that can manipulate selections that are not currently valid.
431void VisibleSelection::setWithoutValidation(const Position& base, const Position& extent)
432{
433    ASSERT(!base.isNull());
434    ASSERT(!extent.isNull());
435    ASSERT(base != extent);
436    ASSERT(m_affinity == DOWNSTREAM);
437    m_base = base;
438    m_extent = extent;
439    m_baseIsFirst = comparePositions(base, extent) <= 0;
440    if (m_baseIsFirst) {
441        m_start = base;
442        m_end = extent;
443    } else {
444        m_start = extent;
445        m_end = base;
446    }
447    m_selectionType = RangeSelection;
448}
449
450void VisibleSelection::adjustSelectionToAvoidCrossingEditingBoundaries()
451{
452    if (m_base.isNull() || m_start.isNull() || m_end.isNull())
453        return;
454
455    Node* baseRoot = highestEditableRoot(m_base);
456    Node* startRoot = highestEditableRoot(m_start);
457    Node* endRoot = highestEditableRoot(m_end);
458
459    Node* baseEditableAncestor = lowestEditableAncestor(m_base.node());
460
461    // The base, start and end are all in the same region.  No adjustment necessary.
462    if (baseRoot == startRoot && baseRoot == endRoot)
463        return;
464
465    // The selection is based in editable content.
466    if (baseRoot) {
467        // If the start is outside the base's editable root, cap it at the start of that root.
468        // If the start is in non-editable content that is inside the base's editable root, put it
469        // at the first editable position after start inside the base's editable root.
470        if (startRoot != baseRoot) {
471            VisiblePosition first = firstEditablePositionAfterPositionInRoot(m_start, baseRoot);
472            m_start = first.deepEquivalent();
473            if (m_start.isNull()) {
474                ASSERT_NOT_REACHED();
475                m_start = m_end;
476            }
477        }
478        // If the end is outside the base's editable root, cap it at the end of that root.
479        // If the end is in non-editable content that is inside the base's root, put it
480        // at the last editable position before the end inside the base's root.
481        if (endRoot != baseRoot) {
482            VisiblePosition last = lastEditablePositionBeforePositionInRoot(m_end, baseRoot);
483            m_end = last.deepEquivalent();
484            if (m_end.isNull())
485                m_end = m_start;
486        }
487    // The selection is based in non-editable content.
488    } else {
489        // FIXME: Non-editable pieces inside editable content should be atomic, in the same way that editable
490        // pieces in non-editable content are atomic.
491
492        // The selection ends in editable content or non-editable content inside a different editable ancestor,
493        // move backward until non-editable content inside the same lowest editable ancestor is reached.
494        Node* endEditableAncestor = lowestEditableAncestor(m_end.node());
495        if (endRoot || endEditableAncestor != baseEditableAncestor) {
496
497            Position p = previousVisuallyDistinctCandidate(m_end);
498            Node* shadowAncestor = endRoot ? endRoot->shadowAncestorNode() : 0;
499            if (p.isNull() && endRoot && (shadowAncestor != endRoot))
500                p = lastDeepEditingPositionForNode(shadowAncestor);
501            while (p.isNotNull() && !(lowestEditableAncestor(p.node()) == baseEditableAncestor && !isEditablePosition(p))) {
502                Node* root = editableRootForPosition(p);
503                shadowAncestor = root ? root->shadowAncestorNode() : 0;
504                p = isAtomicNode(p.node()) ? positionInParentBeforeNode(p.node()) : previousVisuallyDistinctCandidate(p);
505                if (p.isNull() && (shadowAncestor != root))
506                    p = lastDeepEditingPositionForNode(shadowAncestor);
507            }
508            VisiblePosition previous(p);
509
510            if (previous.isNull()) {
511                // The selection crosses an Editing boundary.  This is a
512                // programmer error in the editing code.  Happy debugging!
513                ASSERT_NOT_REACHED();
514                m_base = Position();
515                m_extent = Position();
516                validate();
517                return;
518            }
519            m_end = previous.deepEquivalent();
520        }
521
522        // The selection starts in editable content or non-editable content inside a different editable ancestor,
523        // move forward until non-editable content inside the same lowest editable ancestor is reached.
524        Node* startEditableAncestor = lowestEditableAncestor(m_start.node());
525        if (startRoot || startEditableAncestor != baseEditableAncestor) {
526            Position p = nextVisuallyDistinctCandidate(m_start);
527            Node* shadowAncestor = startRoot ? startRoot->shadowAncestorNode() : 0;
528            if (p.isNull() && startRoot && (shadowAncestor != startRoot))
529                p = Position(shadowAncestor, 0);
530            while (p.isNotNull() && !(lowestEditableAncestor(p.node()) == baseEditableAncestor && !isEditablePosition(p))) {
531                Node* root = editableRootForPosition(p);
532                shadowAncestor = root ? root->shadowAncestorNode() : 0;
533                p = isAtomicNode(p.node()) ? positionInParentAfterNode(p.node()) : nextVisuallyDistinctCandidate(p);
534                if (p.isNull() && (shadowAncestor != root))
535                    p = Position(shadowAncestor, 0);
536            }
537            VisiblePosition next(p);
538
539            if (next.isNull()) {
540                // The selection crosses an Editing boundary.  This is a
541                // programmer error in the editing code.  Happy debugging!
542                ASSERT_NOT_REACHED();
543                m_base = Position();
544                m_extent = Position();
545                validate();
546                return;
547            }
548            m_start = next.deepEquivalent();
549        }
550    }
551
552    // Correct the extent if necessary.
553    if (baseEditableAncestor != lowestEditableAncestor(m_extent.node()))
554        m_extent = m_baseIsFirst ? m_end : m_start;
555}
556
557bool VisibleSelection::isContentEditable() const
558{
559    return isEditablePosition(start());
560}
561
562bool VisibleSelection::isContentRichlyEditable() const
563{
564    return isRichlyEditablePosition(start());
565}
566
567Element* VisibleSelection::rootEditableElement() const
568{
569    return editableRootForPosition(start());
570}
571
572Node* VisibleSelection::shadowTreeRootNode() const
573{
574    return start().node() ? start().node()->shadowTreeRootNode() : 0;
575}
576
577void VisibleSelection::debugPosition() const
578{
579    if (!m_start.node())
580        return;
581
582    fprintf(stderr, "VisibleSelection =================\n");
583
584    if (m_start == m_end) {
585        Position pos = m_start;
586        fprintf(stderr, "pos:        %s %p:%d\n", pos.node()->nodeName().utf8().data(), pos.node(), pos.deprecatedEditingOffset());
587    } else {
588        Position pos = m_start;
589        fprintf(stderr, "start:      %s %p:%d\n", pos.node()->nodeName().utf8().data(), pos.node(), pos.deprecatedEditingOffset());
590        fprintf(stderr, "-----------------------------------\n");
591        pos = m_end;
592        fprintf(stderr, "end:        %s %p:%d\n", pos.node()->nodeName().utf8().data(), pos.node(), pos.deprecatedEditingOffset());
593        fprintf(stderr, "-----------------------------------\n");
594    }
595
596    fprintf(stderr, "================================\n");
597}
598
599#ifndef NDEBUG
600
601void VisibleSelection::formatForDebugger(char* buffer, unsigned length) const
602{
603    String result;
604    String s;
605
606    if (isNone()) {
607        result = "<none>";
608    } else {
609        const int FormatBufferSize = 1024;
610        char s[FormatBufferSize];
611        result += "from ";
612        start().formatForDebugger(s, FormatBufferSize);
613        result += s;
614        result += " to ";
615        end().formatForDebugger(s, FormatBufferSize);
616        result += s;
617    }
618
619    strncpy(buffer, result.utf8().data(), length - 1);
620}
621
622void VisibleSelection::showTreeForThis() const
623{
624    if (start().node()) {
625        start().node()->showTreeAndMark(start().node(), "S", end().node(), "E");
626        fprintf(stderr, "start offset: %d, end offset: %d\n", start().deprecatedEditingOffset(), end().deprecatedEditingOffset());
627    }
628}
629
630#endif
631
632} // namespace WebCore
633
634#ifndef NDEBUG
635
636void showTree(const WebCore::VisibleSelection& sel)
637{
638    sel.showTreeForThis();
639}
640
641void showTree(const WebCore::VisibleSelection* sel)
642{
643    if (sel)
644        sel->showTreeForThis();
645}
646
647#endif
648