2 * Copyright (C) 2007, 2009 Apple Inc. All rights reserved.
3 * Copyright (C) 2012 Google Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15 * its contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "core/page/DOMSelection.h"
34 #include "bindings/v8/ExceptionMessages.h"
35 #include "bindings/v8/ExceptionState.h"
36 #include "bindings/v8/ExceptionStatePlaceholder.h"
37 #include "core/dom/Document.h"
38 #include "core/dom/ExceptionCode.h"
39 #include "core/dom/Node.h"
40 #include "core/dom/Range.h"
41 #include "core/dom/TreeScope.h"
42 #include "core/editing/FrameSelection.h"
43 #include "core/editing/TextIterator.h"
44 #include "core/editing/htmlediting.h"
45 #include "core/frame/LocalFrame.h"
46 #include "wtf/text/WTFString.h"
50 static Node* selectionShadowAncestor(LocalFrame* frame)
52 Node* node = frame->selection().selection().base().anchorNode();
56 if (!node->isInShadowTree())
59 return frame->document()->ancestorInThisScope(node);
62 DOMSelection::DOMSelection(const TreeScope* treeScope)
63 : DOMWindowProperty(treeScope->rootNode().document().frame())
64 , m_treeScope(treeScope)
66 ScriptWrappable::init(this);
69 void DOMSelection::clearTreeScope()
71 m_treeScope = nullptr;
74 const VisibleSelection& DOMSelection::visibleSelection() const
77 return m_frame->selection().selection();
80 static Position anchorPosition(const VisibleSelection& selection)
82 Position anchor = selection.isBaseFirst() ? selection.start() : selection.end();
83 return anchor.parentAnchoredEquivalent();
86 static Position focusPosition(const VisibleSelection& selection)
88 Position focus = selection.isBaseFirst() ? selection.end() : selection.start();
89 return focus.parentAnchoredEquivalent();
92 static Position basePosition(const VisibleSelection& selection)
94 return selection.base().parentAnchoredEquivalent();
97 static Position extentPosition(const VisibleSelection& selection)
99 return selection.extent().parentAnchoredEquivalent();
102 Node* DOMSelection::anchorNode() const
107 return shadowAdjustedNode(anchorPosition(visibleSelection()));
110 int DOMSelection::anchorOffset() const
115 return shadowAdjustedOffset(anchorPosition(visibleSelection()));
118 Node* DOMSelection::focusNode() const
123 return shadowAdjustedNode(focusPosition(visibleSelection()));
126 int DOMSelection::focusOffset() const
131 return shadowAdjustedOffset(focusPosition(visibleSelection()));
134 Node* DOMSelection::baseNode() const
139 return shadowAdjustedNode(basePosition(visibleSelection()));
142 int DOMSelection::baseOffset() const
147 return shadowAdjustedOffset(basePosition(visibleSelection()));
150 Node* DOMSelection::extentNode() const
155 return shadowAdjustedNode(extentPosition(visibleSelection()));
158 int DOMSelection::extentOffset() const
163 return shadowAdjustedOffset(extentPosition(visibleSelection()));
166 bool DOMSelection::isCollapsed() const
168 if (!m_frame || selectionShadowAncestor(m_frame))
170 return !m_frame->selection().isRange();
173 String DOMSelection::type() const
178 FrameSelection& selection = m_frame->selection();
180 // This is a WebKit DOM extension, incompatible with an IE extension
181 // IE has this same attribute, but returns "none", "text" and "control"
182 // http://msdn.microsoft.com/en-us/library/ms534692(VS.85).aspx
183 if (selection.isNone())
185 if (selection.isCaret())
190 int DOMSelection::rangeCount() const
194 return m_frame->selection().isNone() ? 0 : 1;
197 void DOMSelection::collapse(Node* node, int offset, ExceptionState& exceptionState)
204 exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is not a valid offset.");
208 if (!isValidForPosition(node))
210 RefPtrWillBeRawPtr<Range> range = Range::create(node->document());
211 range->setStart(node, offset, exceptionState);
212 if (exceptionState.hadException())
214 range->setEnd(node, offset, exceptionState);
215 if (exceptionState.hadException())
217 m_frame->selection().setSelectedRange(range.get(), DOWNSTREAM, m_frame->selection().isDirectional() ? FrameSelection::Directional : FrameSelection::NonDirectional);
220 void DOMSelection::collapse(Node* node, ExceptionState& exceptionState)
222 collapse(node, 0, exceptionState);
225 void DOMSelection::collapseToEnd(ExceptionState& exceptionState)
230 const VisibleSelection& selection = m_frame->selection().selection();
232 if (selection.isNone()) {
233 exceptionState.throwDOMException(InvalidStateError, "there is no selection.");
237 m_frame->selection().moveTo(VisiblePosition(selection.end(), DOWNSTREAM));
240 void DOMSelection::collapseToStart(ExceptionState& exceptionState)
245 const VisibleSelection& selection = m_frame->selection().selection();
247 if (selection.isNone()) {
248 exceptionState.throwDOMException(InvalidStateError, "there is no selection.");
252 m_frame->selection().moveTo(VisiblePosition(selection.start(), DOWNSTREAM));
255 void DOMSelection::empty()
259 m_frame->selection().clear();
262 void DOMSelection::setBaseAndExtent(Node* baseNode, int baseOffset, Node* extentNode, int extentOffset, ExceptionState& exceptionState)
267 if (baseOffset < 0) {
268 exceptionState.throwDOMException(IndexSizeError, String::number(baseOffset) + " is not a valid base offset.");
272 if (extentOffset < 0) {
273 exceptionState.throwDOMException(IndexSizeError, String::number(extentOffset) + " is not a valid extent offset.");
277 if (!isValidForPosition(baseNode) || !isValidForPosition(extentNode))
280 // FIXME: Eliminate legacy editing positions
281 VisiblePosition visibleBase = VisiblePosition(createLegacyEditingPosition(baseNode, baseOffset), DOWNSTREAM);
282 VisiblePosition visibleExtent = VisiblePosition(createLegacyEditingPosition(extentNode, extentOffset), DOWNSTREAM);
284 m_frame->selection().moveTo(visibleBase, visibleExtent);
287 void DOMSelection::modify(const String& alterString, const String& directionString, const String& granularityString)
292 FrameSelection::EAlteration alter;
293 if (equalIgnoringCase(alterString, "extend"))
294 alter = FrameSelection::AlterationExtend;
295 else if (equalIgnoringCase(alterString, "move"))
296 alter = FrameSelection::AlterationMove;
300 SelectionDirection direction;
301 if (equalIgnoringCase(directionString, "forward"))
302 direction = DirectionForward;
303 else if (equalIgnoringCase(directionString, "backward"))
304 direction = DirectionBackward;
305 else if (equalIgnoringCase(directionString, "left"))
306 direction = DirectionLeft;
307 else if (equalIgnoringCase(directionString, "right"))
308 direction = DirectionRight;
312 TextGranularity granularity;
313 if (equalIgnoringCase(granularityString, "character"))
314 granularity = CharacterGranularity;
315 else if (equalIgnoringCase(granularityString, "word"))
316 granularity = WordGranularity;
317 else if (equalIgnoringCase(granularityString, "sentence"))
318 granularity = SentenceGranularity;
319 else if (equalIgnoringCase(granularityString, "line"))
320 granularity = LineGranularity;
321 else if (equalIgnoringCase(granularityString, "paragraph"))
322 granularity = ParagraphGranularity;
323 else if (equalIgnoringCase(granularityString, "lineboundary"))
324 granularity = LineBoundary;
325 else if (equalIgnoringCase(granularityString, "sentenceboundary"))
326 granularity = SentenceBoundary;
327 else if (equalIgnoringCase(granularityString, "paragraphboundary"))
328 granularity = ParagraphBoundary;
329 else if (equalIgnoringCase(granularityString, "documentboundary"))
330 granularity = DocumentBoundary;
334 m_frame->selection().modify(alter, direction, granularity);
337 void DOMSelection::extend(Node* node, int offset, ExceptionState& exceptionState)
343 exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
348 exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is not a valid offset.");
351 if (offset > (node->offsetInCharacters() ? caretMaxOffset(node) : (int)node->countChildren())) {
352 exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is larger than the given node's length.");
356 if (!isValidForPosition(node))
359 // FIXME: Eliminate legacy editing positions
360 m_frame->selection().setExtent(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
363 PassRefPtrWillBeRawPtr<Range> DOMSelection::getRangeAt(int index, ExceptionState& exceptionState)
368 if (index < 0 || index >= rangeCount()) {
369 exceptionState.throwDOMException(IndexSizeError, String::number(index) + " is not a valid index.");
373 // If you're hitting this, you've added broken multi-range selection support
374 ASSERT(rangeCount() == 1);
376 if (Node* shadowAncestor = selectionShadowAncestor(m_frame)) {
377 ASSERT(!shadowAncestor->isShadowRoot());
378 ContainerNode* container = shadowAncestor->parentOrShadowHostNode();
379 int offset = shadowAncestor->nodeIndex();
380 return Range::create(shadowAncestor->document(), container, offset, container, offset);
383 return m_frame->selection().firstRange();
386 void DOMSelection::removeAllRanges()
390 m_frame->selection().clear();
393 void DOMSelection::addRange(Range* newRange)
398 // FIXME: Should we throw DOMException for error cases below?
400 addConsoleError("The given range is null.");
404 if (!newRange->startContainer()) {
405 addConsoleError("The given range has no container. Perhaps 'detach()' has been invoked on it?");
409 FrameSelection& selection = m_frame->selection();
411 if (selection.isNone()) {
412 selection.setSelectedRange(newRange, VP_DEFAULT_AFFINITY);
416 RefPtrWillBeRawPtr<Range> originalRange = selection.firstRange();
418 if (originalRange->startContainer()->document() != newRange->startContainer()->document()) {
419 addConsoleError("The given range does not belong to the current selection's document.");
422 if (originalRange->startContainer()->treeScope() != newRange->startContainer()->treeScope()) {
423 addConsoleError("The given range and the current selection belong to two different document fragments.");
427 if (originalRange->compareBoundaryPoints(Range::START_TO_END, newRange, ASSERT_NO_EXCEPTION) < 0
428 || newRange->compareBoundaryPoints(Range::START_TO_END, originalRange.get(), ASSERT_NO_EXCEPTION) < 0) {
429 addConsoleError("Discontiguous selection is not supported.");
433 // FIXME: "Merge the ranges if they intersect" is Blink-specific behavior; other browsers supporting discontiguous
434 // selection (obviously) keep each Range added and return it in getRangeAt(). But it's unclear if we can really
435 // do the same, since we don't support discontiguous selection. Further discussions at
436 // <https://code.google.com/p/chromium/issues/detail?id=353069>.
438 Range* start = originalRange->compareBoundaryPoints(Range::START_TO_START, newRange, ASSERT_NO_EXCEPTION) < 0 ? originalRange.get() : newRange;
439 Range* end = originalRange->compareBoundaryPoints(Range::END_TO_END, newRange, ASSERT_NO_EXCEPTION) < 0 ? newRange : originalRange.get();
440 RefPtrWillBeRawPtr<Range> merged = Range::create(originalRange->startContainer()->document(), start->startContainer(), start->startOffset(), end->endContainer(), end->endOffset());
441 EAffinity affinity = selection.selection().affinity();
442 selection.setSelectedRange(merged.get(), affinity);
445 void DOMSelection::deleteFromDocument()
450 FrameSelection& selection = m_frame->selection();
452 if (selection.isNone())
455 RefPtrWillBeRawPtr<Range> selectedRange = selection.selection().toNormalizedRange();
459 selectedRange->deleteContents(ASSERT_NO_EXCEPTION);
461 setBaseAndExtent(selectedRange->startContainer(), selectedRange->startOffset(), selectedRange->startContainer(), selectedRange->startOffset(), ASSERT_NO_EXCEPTION);
464 bool DOMSelection::containsNode(const Node* n, bool allowPartial) const
469 FrameSelection& selection = m_frame->selection();
471 if (!n || m_frame->document() != n->document() || selection.isNone())
474 unsigned nodeIndex = n->nodeIndex();
475 RefPtrWillBeRawPtr<Range> selectedRange = selection.selection().toNormalizedRange();
477 ContainerNode* parentNode = n->parentNode();
481 TrackExceptionState exceptionState;
482 bool nodeFullySelected = Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->startContainer(), selectedRange->startOffset(), exceptionState) >= 0 && !exceptionState.hadException()
483 && Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->endContainer(), selectedRange->endOffset(), exceptionState) <= 0 && !exceptionState.hadException();
484 if (exceptionState.hadException())
486 if (nodeFullySelected)
489 bool nodeFullyUnselected = (Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->endContainer(), selectedRange->endOffset(), exceptionState) > 0 && !exceptionState.hadException())
490 || (Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->startContainer(), selectedRange->startOffset(), exceptionState) < 0 && !exceptionState.hadException());
491 ASSERT(!exceptionState.hadException());
492 if (nodeFullyUnselected)
495 return allowPartial || n->isTextNode();
498 void DOMSelection::selectAllChildren(Node* n, ExceptionState& exceptionState)
503 // This doesn't (and shouldn't) select text node characters.
504 setBaseAndExtent(n, 0, n, n->countChildren(), exceptionState);
507 String DOMSelection::toString()
512 return plainText(m_frame->selection().selection().toNormalizedRange().get());
515 Node* DOMSelection::shadowAdjustedNode(const Position& position) const
517 if (position.isNull())
520 Node* containerNode = position.containerNode();
521 Node* adjustedNode = m_treeScope->ancestorInThisScope(containerNode);
526 if (containerNode == adjustedNode)
527 return containerNode;
529 ASSERT(!adjustedNode->isShadowRoot());
530 return adjustedNode->parentOrShadowHostNode();
533 int DOMSelection::shadowAdjustedOffset(const Position& position) const
535 if (position.isNull())
538 Node* containerNode = position.containerNode();
539 Node* adjustedNode = m_treeScope->ancestorInThisScope(containerNode);
544 if (containerNode == adjustedNode)
545 return position.computeOffsetInContainerNode();
547 return adjustedNode->nodeIndex();
550 bool DOMSelection::isValidForPosition(Node* node) const
555 return node->document() == m_frame->document();
558 void DOMSelection::addConsoleError(const String& message)
561 m_treeScope->document().addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
564 } // namespace WebCore