80edf63d5a7c41da4a4e42e6d8b6a3ab29e794c1
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / page / DOMSelection.cpp
1 /*
2  * Copyright (C) 2007, 2009 Apple Inc. All rights reserved.
3  * Copyright (C) 2012 Google Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
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.
17  *
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.
28  */
29
30
31 #include "config.h"
32 #include "core/page/DOMSelection.h"
33
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"
47
48 namespace WebCore {
49
50 static Node* selectionShadowAncestor(LocalFrame* frame)
51 {
52     Node* node = frame->selection().selection().base().anchorNode();
53     if (!node)
54         return 0;
55
56     if (!node->isInShadowTree())
57         return 0;
58
59     return frame->document()->ancestorInThisScope(node);
60 }
61
62 DOMSelection::DOMSelection(const TreeScope* treeScope)
63     : DOMWindowProperty(treeScope->rootNode().document().frame())
64     , m_treeScope(treeScope)
65 {
66     ScriptWrappable::init(this);
67 }
68
69 void DOMSelection::clearTreeScope()
70 {
71     m_treeScope = 0;
72 }
73
74 const VisibleSelection& DOMSelection::visibleSelection() const
75 {
76     ASSERT(m_frame);
77     return m_frame->selection().selection();
78 }
79
80 static Position anchorPosition(const VisibleSelection& selection)
81 {
82     Position anchor = selection.isBaseFirst() ? selection.start() : selection.end();
83     return anchor.parentAnchoredEquivalent();
84 }
85
86 static Position focusPosition(const VisibleSelection& selection)
87 {
88     Position focus = selection.isBaseFirst() ? selection.end() : selection.start();
89     return focus.parentAnchoredEquivalent();
90 }
91
92 static Position basePosition(const VisibleSelection& selection)
93 {
94     return selection.base().parentAnchoredEquivalent();
95 }
96
97 static Position extentPosition(const VisibleSelection& selection)
98 {
99     return selection.extent().parentAnchoredEquivalent();
100 }
101
102 Node* DOMSelection::anchorNode() const
103 {
104     if (!m_frame)
105         return 0;
106
107     return shadowAdjustedNode(anchorPosition(visibleSelection()));
108 }
109
110 int DOMSelection::anchorOffset() const
111 {
112     if (!m_frame)
113         return 0;
114
115     return shadowAdjustedOffset(anchorPosition(visibleSelection()));
116 }
117
118 Node* DOMSelection::focusNode() const
119 {
120     if (!m_frame)
121         return 0;
122
123     return shadowAdjustedNode(focusPosition(visibleSelection()));
124 }
125
126 int DOMSelection::focusOffset() const
127 {
128     if (!m_frame)
129         return 0;
130
131     return shadowAdjustedOffset(focusPosition(visibleSelection()));
132 }
133
134 Node* DOMSelection::baseNode() const
135 {
136     if (!m_frame)
137         return 0;
138
139     return shadowAdjustedNode(basePosition(visibleSelection()));
140 }
141
142 int DOMSelection::baseOffset() const
143 {
144     if (!m_frame)
145         return 0;
146
147     return shadowAdjustedOffset(basePosition(visibleSelection()));
148 }
149
150 Node* DOMSelection::extentNode() const
151 {
152     if (!m_frame)
153         return 0;
154
155     return shadowAdjustedNode(extentPosition(visibleSelection()));
156 }
157
158 int DOMSelection::extentOffset() const
159 {
160     if (!m_frame)
161         return 0;
162
163     return shadowAdjustedOffset(extentPosition(visibleSelection()));
164 }
165
166 bool DOMSelection::isCollapsed() const
167 {
168     if (!m_frame || selectionShadowAncestor(m_frame))
169         return true;
170     return !m_frame->selection().isRange();
171 }
172
173 String DOMSelection::type() const
174 {
175     if (!m_frame)
176         return String();
177
178     FrameSelection& selection = m_frame->selection();
179
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())
184         return "None";
185     if (selection.isCaret())
186         return "Caret";
187     return "Range";
188 }
189
190 int DOMSelection::rangeCount() const
191 {
192     if (!m_frame)
193         return 0;
194     return m_frame->selection().isNone() ? 0 : 1;
195 }
196
197 void DOMSelection::collapse(Node* node, int offset, ExceptionState& exceptionState)
198 {
199     if (!m_frame)
200         return;
201
202     if (offset < 0) {
203         exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is not a valid offset.");
204         return;
205     }
206
207     if (!isValidForPosition(node))
208         return;
209
210     // FIXME: Eliminate legacy editing positions
211     m_frame->selection().moveTo(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
212 }
213
214 void DOMSelection::collapseToEnd(ExceptionState& exceptionState)
215 {
216     if (!m_frame)
217         return;
218
219     const VisibleSelection& selection = m_frame->selection().selection();
220
221     if (selection.isNone()) {
222         exceptionState.throwDOMException(InvalidStateError, "there is no selection.");
223         return;
224     }
225
226     m_frame->selection().moveTo(VisiblePosition(selection.end(), DOWNSTREAM));
227 }
228
229 void DOMSelection::collapseToStart(ExceptionState& exceptionState)
230 {
231     if (!m_frame)
232         return;
233
234     const VisibleSelection& selection = m_frame->selection().selection();
235
236     if (selection.isNone()) {
237         exceptionState.throwDOMException(InvalidStateError, "there is no selection.");
238         return;
239     }
240
241     m_frame->selection().moveTo(VisiblePosition(selection.start(), DOWNSTREAM));
242 }
243
244 void DOMSelection::empty()
245 {
246     if (!m_frame)
247         return;
248     m_frame->selection().clear();
249 }
250
251 void DOMSelection::setBaseAndExtent(Node* baseNode, int baseOffset, Node* extentNode, int extentOffset, ExceptionState& exceptionState)
252 {
253     if (!m_frame)
254         return;
255
256     if (baseOffset < 0) {
257         exceptionState.throwDOMException(IndexSizeError, String::number(baseOffset) + " is not a valid base offset.");
258         return;
259     }
260
261     if (extentOffset < 0) {
262         exceptionState.throwDOMException(IndexSizeError, String::number(extentOffset) + " is not a valid extent offset.");
263         return;
264     }
265
266     if (!isValidForPosition(baseNode) || !isValidForPosition(extentNode))
267         return;
268
269     // FIXME: Eliminate legacy editing positions
270     VisiblePosition visibleBase = VisiblePosition(createLegacyEditingPosition(baseNode, baseOffset), DOWNSTREAM);
271     VisiblePosition visibleExtent = VisiblePosition(createLegacyEditingPosition(extentNode, extentOffset), DOWNSTREAM);
272
273     m_frame->selection().moveTo(visibleBase, visibleExtent);
274 }
275
276 void DOMSelection::modify(const String& alterString, const String& directionString, const String& granularityString)
277 {
278     if (!m_frame)
279         return;
280
281     FrameSelection::EAlteration alter;
282     if (equalIgnoringCase(alterString, "extend"))
283         alter = FrameSelection::AlterationExtend;
284     else if (equalIgnoringCase(alterString, "move"))
285         alter = FrameSelection::AlterationMove;
286     else
287         return;
288
289     SelectionDirection direction;
290     if (equalIgnoringCase(directionString, "forward"))
291         direction = DirectionForward;
292     else if (equalIgnoringCase(directionString, "backward"))
293         direction = DirectionBackward;
294     else if (equalIgnoringCase(directionString, "left"))
295         direction = DirectionLeft;
296     else if (equalIgnoringCase(directionString, "right"))
297         direction = DirectionRight;
298     else
299         return;
300
301     TextGranularity granularity;
302     if (equalIgnoringCase(granularityString, "character"))
303         granularity = CharacterGranularity;
304     else if (equalIgnoringCase(granularityString, "word"))
305         granularity = WordGranularity;
306     else if (equalIgnoringCase(granularityString, "sentence"))
307         granularity = SentenceGranularity;
308     else if (equalIgnoringCase(granularityString, "line"))
309         granularity = LineGranularity;
310     else if (equalIgnoringCase(granularityString, "paragraph"))
311         granularity = ParagraphGranularity;
312     else if (equalIgnoringCase(granularityString, "lineboundary"))
313         granularity = LineBoundary;
314     else if (equalIgnoringCase(granularityString, "sentenceboundary"))
315         granularity = SentenceBoundary;
316     else if (equalIgnoringCase(granularityString, "paragraphboundary"))
317         granularity = ParagraphBoundary;
318     else if (equalIgnoringCase(granularityString, "documentboundary"))
319         granularity = DocumentBoundary;
320     else
321         return;
322
323     m_frame->selection().modify(alter, direction, granularity);
324 }
325
326 void DOMSelection::extend(Node* node, int offset, ExceptionState& exceptionState)
327 {
328     if (!m_frame)
329         return;
330
331     if (!node) {
332         exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
333         return;
334     }
335
336     if (offset < 0) {
337         exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is not a valid offset.");
338         return;
339     }
340     if (offset > (node->offsetInCharacters() ? caretMaxOffset(node) : (int)node->countChildren())) {
341         exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is larger than the given node's length.");
342         return;
343     }
344
345     if (!isValidForPosition(node))
346         return;
347
348     // FIXME: Eliminate legacy editing positions
349     m_frame->selection().setExtent(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
350 }
351
352 PassRefPtr<Range> DOMSelection::getRangeAt(int index, ExceptionState& exceptionState)
353 {
354     if (!m_frame)
355         return nullptr;
356
357     if (index < 0 || index >= rangeCount()) {
358         exceptionState.throwDOMException(IndexSizeError, String::number(index) + " is not a valid index.");
359         return nullptr;
360     }
361
362     // If you're hitting this, you've added broken multi-range selection support
363     ASSERT(rangeCount() == 1);
364
365     if (Node* shadowAncestor = selectionShadowAncestor(m_frame)) {
366         ASSERT(!shadowAncestor->isShadowRoot());
367         ContainerNode* container = shadowAncestor->parentOrShadowHostNode();
368         int offset = shadowAncestor->nodeIndex();
369         return Range::create(shadowAncestor->document(), container, offset, container, offset);
370     }
371
372     return m_frame->selection().firstRange();
373 }
374
375 void DOMSelection::removeAllRanges()
376 {
377     if (!m_frame)
378         return;
379     m_frame->selection().clear();
380 }
381
382 void DOMSelection::addRange(Range* newRange)
383 {
384     if (!m_frame)
385         return;
386
387     // FIXME: Should we throw DOMException for error cases below?
388     if (!newRange) {
389         addConsoleError("The given range is null.");
390         return;
391     }
392
393     if (!newRange->startContainer()) {
394         addConsoleError("The given range has no container. Perhaps 'detach()' has been invoked on it?");
395         return;
396     }
397
398     FrameSelection& selection = m_frame->selection();
399
400     if (selection.isNone()) {
401         selection.setSelectedRange(newRange, VP_DEFAULT_AFFINITY);
402         return;
403     }
404
405     RefPtr<Range> originalRange = selection.selection().toNormalizedRange();
406
407     if (originalRange->startContainer()->document() != newRange->startContainer()->document()) {
408         addConsoleError("The given range does not belong to the current selection's document.");
409         return;
410     }
411     if (originalRange->startContainer()->treeScope() != newRange->startContainer()->treeScope()) {
412         addConsoleError("The given range and the current selection belong to two different document fragments.");
413         return;
414     }
415
416     // FIXME: Emit a console error if the combined ranges would form a discontiguous selection.
417     if (newRange->compareBoundaryPoints(Range::START_TO_START, originalRange.get(), ASSERT_NO_EXCEPTION) == -1) {
418         // We don't support discontiguous selection. We don't do anything if newRange and originalRange don't intersect.
419         if (newRange->compareBoundaryPoints(Range::START_TO_END, originalRange.get(), ASSERT_NO_EXCEPTION) > -1) {
420             if (newRange->compareBoundaryPoints(Range::END_TO_END, originalRange.get(), ASSERT_NO_EXCEPTION) == -1) {
421                 // The original originalRange and newRange intersect.
422                 selection.setSelection(VisibleSelection(newRange->startPosition(), originalRange->endPosition(), DOWNSTREAM));
423             } else {
424                 // newRange contains the original originalRange.
425                 selection.setSelection(VisibleSelection(newRange));
426             }
427         }
428     } else {
429         // We don't support discontiguous selection. We don't do anything if newRange and originalRange don't intersect.
430         if (newRange->compareBoundaryPoints(Range::END_TO_START, originalRange.get(), ASSERT_NO_EXCEPTION) < 1) {
431             if (newRange->compareBoundaryPoints(Range::END_TO_END, originalRange.get(), ASSERT_NO_EXCEPTION) == -1) {
432                 // The original range contains newRange.
433                 selection.setSelection(VisibleSelection(originalRange.get()));
434             } else {
435                 // The original range and r intersect.
436                 selection.setSelection(VisibleSelection(originalRange->startPosition(), newRange->endPosition(), DOWNSTREAM));
437             }
438         }
439     }
440 }
441
442 void DOMSelection::deleteFromDocument()
443 {
444     if (!m_frame)
445         return;
446
447     FrameSelection& selection = m_frame->selection();
448
449     if (selection.isNone())
450         return;
451
452     if (isCollapsed())
453         selection.modify(FrameSelection::AlterationExtend, DirectionBackward, CharacterGranularity);
454
455     RefPtr<Range> selectedRange = selection.selection().toNormalizedRange();
456     if (!selectedRange)
457         return;
458
459     selectedRange->deleteContents(ASSERT_NO_EXCEPTION);
460
461     setBaseAndExtent(selectedRange->startContainer(ASSERT_NO_EXCEPTION), selectedRange->startOffset(), selectedRange->startContainer(), selectedRange->startOffset(), ASSERT_NO_EXCEPTION);
462 }
463
464 bool DOMSelection::containsNode(const Node* n, bool allowPartial) const
465 {
466     if (!m_frame)
467         return false;
468
469     FrameSelection& selection = m_frame->selection();
470
471     if (!n || m_frame->document() != n->document() || selection.isNone())
472         return false;
473
474     unsigned nodeIndex = n->nodeIndex();
475     RefPtr<Range> selectedRange = selection.selection().toNormalizedRange();
476
477     ContainerNode* parentNode = n->parentNode();
478     if (!parentNode)
479         return false;
480
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())
485         return false;
486     if (nodeFullySelected)
487         return true;
488
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)
493         return false;
494
495     return allowPartial || n->isTextNode();
496 }
497
498 void DOMSelection::selectAllChildren(Node* n, ExceptionState& exceptionState)
499 {
500     if (!n)
501         return;
502
503     // This doesn't (and shouldn't) select text node characters.
504     setBaseAndExtent(n, 0, n, n->countChildren(), exceptionState);
505 }
506
507 String DOMSelection::toString()
508 {
509     if (!m_frame)
510         return String();
511
512     return plainText(m_frame->selection().selection().toNormalizedRange().get());
513 }
514
515 Node* DOMSelection::shadowAdjustedNode(const Position& position) const
516 {
517     if (position.isNull())
518         return 0;
519
520     Node* containerNode = position.containerNode();
521     Node* adjustedNode = m_treeScope->ancestorInThisScope(containerNode);
522
523     if (!adjustedNode)
524         return 0;
525
526     if (containerNode == adjustedNode)
527         return containerNode;
528
529     ASSERT(!adjustedNode->isShadowRoot());
530     return adjustedNode->parentOrShadowHostNode();
531 }
532
533 int DOMSelection::shadowAdjustedOffset(const Position& position) const
534 {
535     if (position.isNull())
536         return 0;
537
538     Node* containerNode = position.containerNode();
539     Node* adjustedNode = m_treeScope->ancestorInThisScope(containerNode);
540
541     if (!adjustedNode)
542         return 0;
543
544     if (containerNode == adjustedNode)
545         return position.computeOffsetInContainerNode();
546
547     return adjustedNode->nodeIndex();
548 }
549
550 bool DOMSelection::isValidForPosition(Node* node) const
551 {
552     ASSERT(m_frame);
553     if (!node)
554         return true;
555     return node->document() == m_frame->document();
556 }
557
558 void DOMSelection::addConsoleError(const String& message)
559 {
560     if (m_treeScope)
561         m_treeScope->document().addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
562 }
563
564 } // namespace WebCore