Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / editing / TextIterator.h
1 /*
2  * Copyright (C) 2004, 2006, 2009 Apple 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 #ifndef TextIterator_h
27 #define TextIterator_h
28
29 #include "core/dom/Range.h"
30 #include "core/editing/FindOptions.h"
31 #include "platform/heap/Handle.h"
32 #include "wtf/Vector.h"
33
34 namespace WebCore {
35
36 class InlineTextBox;
37 class RenderText;
38 class RenderTextFragment;
39
40 enum TextIteratorBehavior {
41     TextIteratorDefaultBehavior = 0,
42     TextIteratorEmitsCharactersBetweenAllVisiblePositions = 1 << 0,
43     TextIteratorEntersTextControls = 1 << 1,
44     TextIteratorIgnoresStyleVisibility = 1 << 2,
45     TextIteratorEmitsOriginalText = 1 << 3,
46     TextIteratorStopsOnFormControls = 1 << 4,
47     TextIteratorEmitsImageAltText = 1 << 5,
48     TextIteratorEntersAuthorShadowRoots = 1 << 6
49 };
50 typedef unsigned TextIteratorBehaviorFlags;
51
52 String plainText(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
53 PassRefPtrWillBeRawPtr<Range> findPlainText(const Range*, const String&, FindOptions);
54 void findPlainText(const Position& inputStart, const Position& inputEnd, const String&, FindOptions, Position& resultStart, Position& resultEnd);
55
56 class BitStack {
57 public:
58     BitStack();
59     ~BitStack();
60
61     void push(bool);
62     void pop();
63
64     bool top() const;
65     unsigned size() const;
66
67 private:
68     unsigned m_size;
69     Vector<unsigned, 1> m_words;
70 };
71
72 // Iterates through the DOM range, returning all the text, and 0-length boundaries
73 // at points where replaced elements break up the text flow.  The text comes back in
74 // chunks so as to optimize for performance of the iteration.
75
76 class TextIterator {
77 public:
78     explicit TextIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
79     // [start, end] indicates the document range that the iteration should take place within (both ends inclusive).
80     TextIterator(const Position& start, const Position& end, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
81     ~TextIterator();
82
83     bool atEnd() const { return !m_positionNode || m_shouldStop; }
84     void advance();
85
86     int length() const { return m_textLength; }
87     UChar characterAt(unsigned index) const;
88     String substring(unsigned position, unsigned length) const;
89     void appendTextToStringBuilder(StringBuilder&, unsigned position = 0, unsigned maxLength = UINT_MAX) const;
90
91     template<typename BufferType>
92     void appendTextTo(BufferType& output, unsigned position = 0)
93     {
94         ASSERT_WITH_SECURITY_IMPLICATION(position <= static_cast<unsigned>(length()));
95         unsigned lengthToAppend = length() - position;
96         if (!lengthToAppend)
97             return;
98         if (m_singleCharacterBuffer) {
99             ASSERT(!position);
100             ASSERT(length() == 1);
101             output.append(&m_singleCharacterBuffer, 1);
102         } else {
103             string().appendTo(output, startOffset() + position, lengthToAppend);
104         }
105     }
106
107     PassRefPtrWillBeRawPtr<Range> range() const;
108     Node* node() const;
109
110     static int rangeLength(const Range*, bool spacesForReplacedElements = false);
111     static PassRefPtrWillBeRawPtr<Range> subrange(Range* entireRange, int characterOffset, int characterCount);
112
113 private:
114     enum IterationProgress {
115         HandledNone,
116         HandledAuthorShadowRoots,
117         HandledUserAgentShadowRoot,
118         HandledNode,
119         HandledChildren
120     };
121
122     void initialize(const Position& start, const Position& end);
123
124     int startOffset() const { return m_positionStartOffset; }
125     const String& string() const { return m_text; }
126     void exitNode();
127     bool shouldRepresentNodeOffsetZero();
128     bool shouldEmitSpaceBeforeAndAfterNode(Node*);
129     void representNodeOffsetZero();
130     bool handleTextNode();
131     bool handleReplacedElement();
132     bool handleNonTextNode();
133     void handleTextBox();
134     void handleTextNodeFirstLetter(RenderTextFragment*);
135     bool hasVisibleTextNode(RenderText*);
136     void emitCharacter(UChar, Node* textNode, Node* offsetBaseNode, int textStartOffset, int textEndOffset);
137     void emitText(Node* textNode, RenderObject* renderObject, int textStartOffset, int textEndOffset);
138     void emitText(Node* textNode, int textStartOffset, int textEndOffset);
139
140     // Current position, not necessarily of the text being returned, but position
141     // as we walk through the DOM tree.
142     Node* m_node;
143     int m_offset;
144     IterationProgress m_iterationProgress;
145     BitStack m_fullyClippedStack;
146     int m_shadowDepth;
147
148     // The range.
149     Node* m_startContainer;
150     int m_startOffset;
151     Node* m_endContainer;
152     int m_endOffset;
153     Node* m_pastEndNode;
154
155     // The current text and its position, in the form to be returned from the iterator.
156     Node* m_positionNode;
157     mutable Node* m_positionOffsetBaseNode;
158     mutable int m_positionStartOffset;
159     mutable int m_positionEndOffset;
160     int m_textLength;
161     String m_text;
162
163     // Used when there is still some pending text from the current node; when these
164     // are false and 0, we go back to normal iterating.
165     bool m_needsAnotherNewline;
166     InlineTextBox* m_textBox;
167     // Used when iteration over :first-letter text to save pointer to
168     // remaining text box.
169     InlineTextBox* m_remainingTextBox;
170     // Used to point to RenderText object for :first-letter.
171     RenderText *m_firstLetterText;
172
173     // Used to do the whitespace collapsing logic.
174     Node* m_lastTextNode;
175     bool m_lastTextNodeEndedWithCollapsedSpace;
176     UChar m_lastCharacter;
177
178     // Used for whitespace characters that aren't in the DOM, so we can point at them.
179     // If non-zero, overrides m_text.
180     UChar m_singleCharacterBuffer;
181
182     // Used when text boxes are out of order (Hebrew/Arabic w/ embeded LTR text)
183     Vector<InlineTextBox*> m_sortedTextBoxes;
184     size_t m_sortedTextBoxesPosition;
185
186     // Used when deciding whether to emit a "positioning" (e.g. newline) before any other content
187     bool m_hasEmitted;
188
189     // Used by selection preservation code.  There should be one character emitted between every VisiblePosition
190     // in the Range used to create the TextIterator.
191     // FIXME <rdar://problem/6028818>: This functionality should eventually be phased out when we rewrite
192     // moveParagraphs to not clone/destroy moved content.
193     bool m_emitsCharactersBetweenAllVisiblePositions;
194     bool m_entersTextControls;
195
196     // Used in pasting inside password field.
197     bool m_emitsOriginalText;
198     // Used when deciding text fragment created by :first-letter should be looked into.
199     bool m_handledFirstLetter;
200     // Used when the visibility of the style should not affect text gathering.
201     bool m_ignoresStyleVisibility;
202     // Used when the iteration should stop if form controls are reached.
203     bool m_stopsOnFormControls;
204     // Used when m_stopsOnFormControls is set to determine if the iterator should keep advancing.
205     bool m_shouldStop;
206
207     bool m_emitsImageAltText;
208
209     bool m_entersAuthorShadowRoots;
210 };
211
212 // Iterates through the DOM range, returning all the text, and 0-length boundaries
213 // at points where replaced elements break up the text flow. The text comes back in
214 // chunks so as to optimize for performance of the iteration.
215 class SimplifiedBackwardsTextIterator {
216 public:
217     explicit SimplifiedBackwardsTextIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
218
219     bool atEnd() const { return !m_positionNode || m_shouldStop; }
220     void advance();
221
222     int length() const { return m_textLength; }
223
224     Node* node() const { return m_node; }
225
226     template<typename BufferType>
227     void prependTextTo(BufferType& output)
228     {
229         if (!m_textLength)
230             return;
231         if (m_singleCharacterBuffer)
232             output.prepend(&m_singleCharacterBuffer, 1);
233         else
234             m_textContainer.prependTo(output, m_textOffset, m_textLength);
235     }
236
237     PassRefPtrWillBeRawPtr<Range> range() const;
238
239 private:
240     void exitNode();
241     bool handleTextNode();
242     RenderText* handleFirstLetter(int& startOffset, int& offsetInNode);
243     bool handleReplacedElement();
244     bool handleNonTextNode();
245     void emitCharacter(UChar, Node*, int startOffset, int endOffset);
246     bool advanceRespectingRange(Node*);
247
248     // Current position, not necessarily of the text being returned, but position
249     // as we walk through the DOM tree.
250     Node* m_node;
251     int m_offset;
252     bool m_handledNode;
253     bool m_handledChildren;
254     BitStack m_fullyClippedStack;
255
256     // End of the range.
257     Node* m_startNode;
258     int m_startOffset;
259     // Start of the range.
260     Node* m_endNode;
261     int m_endOffset;
262
263     // The current text and its position, in the form to be returned from the iterator.
264     Node* m_positionNode;
265     int m_positionStartOffset;
266     int m_positionEndOffset;
267
268     String m_textContainer; // We're interested in the range [m_textOffset, m_textOffset + m_textLength) of m_textContainer.
269     int m_textOffset;
270     int m_textLength;
271
272     // Used to do the whitespace logic.
273     Node* m_lastTextNode;
274     UChar m_lastCharacter;
275
276     // Used for whitespace characters that aren't in the DOM, so we can point at them.
277     UChar m_singleCharacterBuffer;
278
279     // Whether m_node has advanced beyond the iteration range (i.e. m_startNode).
280     bool m_havePassedStartNode;
281
282     // Should handle first-letter renderer in the next call to handleTextNode.
283     bool m_shouldHandleFirstLetter;
284
285     // Used when the iteration should stop if form controls are reached.
286     bool m_stopsOnFormControls;
287
288     // Used when m_stopsOnFormControls is set to determine if the iterator should keep advancing.
289     bool m_shouldStop;
290
291     // Used in pasting inside password field.
292     bool m_emitsOriginalText;
293 };
294
295 // Builds on the text iterator, adding a character position so we can walk one
296 // character at a time, or faster, as needed. Useful for searching.
297 class CharacterIterator {
298 public:
299     explicit CharacterIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
300     CharacterIterator(const Position& start, const Position& end, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
301
302     void advance(int numCharacters);
303
304     bool atBreak() const { return m_atBreak; }
305     bool atEnd() const { return m_textIterator.atEnd(); }
306
307     int length() const { return m_textIterator.length() - m_runOffset; }
308     UChar characterAt(unsigned index) const { return m_textIterator.characterAt(m_runOffset + index); }
309
310     template<typename BufferType>
311     void appendTextTo(BufferType& output) { m_textIterator.appendTextTo(output, m_runOffset); }
312
313     int characterOffset() const { return m_offset; }
314     PassRefPtrWillBeRawPtr<Range> range() const;
315
316 private:
317     void initialize();
318
319     int m_offset;
320     int m_runOffset;
321     bool m_atBreak;
322
323     TextIterator m_textIterator;
324 };
325
326 class BackwardsCharacterIterator {
327 public:
328     explicit BackwardsCharacterIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
329
330     void advance(int);
331
332     bool atEnd() const { return m_textIterator.atEnd(); }
333
334     PassRefPtrWillBeRawPtr<Range> range() const;
335
336 private:
337     int m_offset;
338     int m_runOffset;
339     bool m_atBreak;
340
341     SimplifiedBackwardsTextIterator m_textIterator;
342 };
343
344 // Very similar to the TextIterator, except that the chunks of text returned are "well behaved",
345 // meaning they never end split up a word.  This is useful for spellcheck or (perhaps one day) searching.
346 class WordAwareIterator {
347     STACK_ALLOCATED();
348 public:
349     explicit WordAwareIterator(const Range*);
350     ~WordAwareIterator();
351
352     bool atEnd() const { return !m_didLookAhead && m_textIterator.atEnd(); }
353     void advance();
354
355     String substring(unsigned position, unsigned length) const;
356     UChar characterAt(unsigned index) const;
357     int length() const;
358
359 private:
360     Vector<UChar> m_buffer;
361     // Did we have to look ahead in the textIterator to confirm the current chunk?
362     bool m_didLookAhead;
363     RefPtrWillBeMember<Range> m_range;
364     TextIterator m_textIterator;
365 };
366
367 }
368
369 #endif