-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTextIterator.cpp
2695 lines (2318 loc) · 93.7 KB
/
TextIterator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
* Copyright (C) 2005 Alexey Proskuryakov.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "TextIterator.h"
#include "Document.h"
#include "Font.h"
#include "Frame.h"
#include "HTMLElement.h"
#include "HTMLTextFormControlElement.h"
#include "HTMLNames.h"
#include "htmlediting.h"
#include "InlineTextBox.h"
#include "Range.h"
#include "RenderTableCell.h"
#include "RenderTableRow.h"
#include "RenderTextControl.h"
#include "RenderTextFragment.h"
#include "ShadowRoot.h"
#include "TextBoundaries.h"
#include "TextBreakIterator.h"
#include "VisiblePosition.h"
#include "visible_units.h"
#include <wtf/text/CString.h>
#include <wtf/unicode/CharacterNames.h>
#if USE(ICU_UNICODE) && !UCONFIG_NO_COLLATION
#include "TextBreakIteratorInternalICU.h"
#include <unicode/usearch.h>
#endif
using namespace WTF::Unicode;
using namespace std;
namespace WebCore {
using namespace HTMLNames;
// Buffer that knows how to compare with a search target.
// Keeps enough of the previous text to be able to search in the future, but no more.
// Non-breaking spaces are always equal to normal spaces.
// Case folding is also done if the CaseInsensitive option is specified.
// Matches are further filtered if the AtWordStarts option is specified, although some
// matches inside a word are permitted if TreatMedialCapitalAsWordStart is specified as well.
class SearchBuffer {
WTF_MAKE_NONCOPYABLE(SearchBuffer);
public:
SearchBuffer(const String& target, FindOptions);
~SearchBuffer();
// Returns number of characters appended; guaranteed to be in the range [1, length].
size_t append(const UChar*, size_t length);
bool needsMoreContext() const;
void prependContext(const UChar*, size_t length);
void reachedBreak();
// Result is the size in characters of what was found.
// And <startOffset> is the number of characters back to the start of what was found.
size_t search(size_t& startOffset);
bool atBreak() const;
#if USE(ICU_UNICODE) && !UCONFIG_NO_COLLATION
private:
bool isBadMatch(const UChar*, size_t length) const;
bool isWordStartMatch(size_t start, size_t length) const;
String m_target;
FindOptions m_options;
Vector<UChar> m_buffer;
size_t m_overlap;
size_t m_prefixLength;
bool m_atBreak;
bool m_needsMoreContext;
bool m_targetRequiresKanaWorkaround;
Vector<UChar> m_normalizedTarget;
mutable Vector<UChar> m_normalizedMatch;
#else
private:
void append(UChar, bool isCharacterStart);
size_t length() const;
String m_target;
FindOptions m_options;
Vector<UChar> m_buffer;
Vector<bool> m_isCharacterStartBuffer;
bool m_isBufferFull;
size_t m_cursor;
#endif
};
// --------
static const unsigned bitsInWord = sizeof(unsigned) * 8;
static const unsigned bitInWordMask = bitsInWord - 1;
BitStack::BitStack()
: m_size(0)
{
}
BitStack::~BitStack()
{
}
void BitStack::push(bool bit)
{
unsigned index = m_size / bitsInWord;
unsigned shift = m_size & bitInWordMask;
if (!shift && index == m_words.size()) {
m_words.grow(index + 1);
m_words[index] = 0;
}
unsigned& word = m_words[index];
unsigned mask = 1U << shift;
if (bit)
word |= mask;
else
word &= ~mask;
++m_size;
}
void BitStack::pop()
{
if (m_size)
--m_size;
}
bool BitStack::top() const
{
if (!m_size)
return false;
unsigned shift = (m_size - 1) & bitInWordMask;
return m_words.last() & (1U << shift);
}
unsigned BitStack::size() const
{
return m_size;
}
// --------
#if !ASSERT_DISABLED
static unsigned depthCrossingShadowBoundaries(Node* node)
{
unsigned depth = 0;
for (Node* parent = node->parentOrHostNode(); parent; parent = parent->parentOrHostNode())
++depth;
return depth;
}
#endif
// This function is like Range::pastLastNode, except for the fact that it can climb up out of shadow trees.
static Node* nextInPreOrderCrossingShadowBoundaries(Node* rangeEndContainer, int rangeEndOffset)
{
if (!rangeEndContainer)
return 0;
if (rangeEndOffset >= 0 && !rangeEndContainer->offsetInCharacters()) {
if (Node* next = rangeEndContainer->childNode(rangeEndOffset))
return next;
}
for (Node* node = rangeEndContainer; node; node = node->parentOrHostNode()) {
if (Node* next = node->nextSibling())
return next;
}
return 0;
}
// --------
static inline bool fullyClipsContents(Node* node)
{
RenderObject* renderer = node->renderer();
if (!renderer || !renderer->isBox() || !renderer->hasOverflowClip())
return false;
return toRenderBox(renderer)->size().isEmpty();
}
static inline bool ignoresContainerClip(Node* node)
{
RenderObject* renderer = node->renderer();
if (!renderer || renderer->isText())
return false;
return renderer->style()->hasOutOfFlowPosition();
}
static void pushFullyClippedState(BitStack& stack, Node* node)
{
ASSERT(stack.size() == depthCrossingShadowBoundaries(node));
// Push true if this node full clips its contents, or if a parent already has fully
// clipped and this is not a node that ignores its container's clip.
stack.push(fullyClipsContents(node) || (stack.top() && !ignoresContainerClip(node)));
}
static void setUpFullyClippedStack(BitStack& stack, Node* node)
{
// Put the nodes in a vector so we can iterate in reverse order.
Vector<Node*, 100> ancestry;
for (Node* parent = node->parentOrHostNode(); parent; parent = parent->parentOrHostNode())
ancestry.append(parent);
// Call pushFullyClippedState on each node starting with the earliest ancestor.
size_t size = ancestry.size();
for (size_t i = 0; i < size; ++i)
pushFullyClippedState(stack, ancestry[size - i - 1]);
pushFullyClippedState(stack, node);
ASSERT(stack.size() == 1 + depthCrossingShadowBoundaries(node));
}
// --------
TextIterator::TextIterator()
: m_startContainer(0)
, m_startOffset(0)
, m_endContainer(0)
, m_endOffset(0)
, m_positionNode(0)
, m_textCharacters(0)
, m_textLength(0)
, m_remainingTextBox(0)
, m_firstLetterText(0)
, m_lastCharacter(0)
, m_sortedTextBoxesPosition(0)
, m_emitsCharactersBetweenAllVisiblePositions(false)
, m_entersTextControls(false)
, m_emitsTextWithoutTranscoding(false)
, m_emitsOriginalText(false)
, m_handledFirstLetter(false)
, m_ignoresStyleVisibility(false)
, m_emitsObjectReplacementCharacters(false)
, m_stopsOnFormControls(false)
, m_shouldStop(false)
{
}
TextIterator::TextIterator(const Range* r, TextIteratorBehavior behavior)
: m_startContainer(0)
, m_startOffset(0)
, m_endContainer(0)
, m_endOffset(0)
, m_positionNode(0)
, m_textCharacters(0)
, m_textLength(0)
, m_remainingTextBox(0)
, m_firstLetterText(0)
, m_sortedTextBoxesPosition(0)
, m_emitsCharactersBetweenAllVisiblePositions(behavior & TextIteratorEmitsCharactersBetweenAllVisiblePositions)
, m_entersTextControls(behavior & TextIteratorEntersTextControls)
, m_emitsTextWithoutTranscoding(behavior & TextIteratorEmitsTextsWithoutTranscoding)
, m_emitsOriginalText(behavior & TextIteratorEmitsOriginalText)
, m_handledFirstLetter(false)
, m_ignoresStyleVisibility(behavior & TextIteratorIgnoresStyleVisibility)
, m_emitsObjectReplacementCharacters(behavior & TextIteratorEmitsObjectReplacementCharacters)
, m_stopsOnFormControls(behavior & TextIteratorStopsOnFormControls)
, m_shouldStop(false)
{
if (!r)
return;
// get and validate the range endpoints
Node* startContainer = r->startContainer();
if (!startContainer)
return;
int startOffset = r->startOffset();
Node* endContainer = r->endContainer();
int endOffset = r->endOffset();
// Callers should be handing us well-formed ranges. If we discover that this isn't
// the case, we could consider changing this assertion to an early return.
ASSERT(r->boundaryPointsValid());
// remember range - this does not change
m_startContainer = startContainer;
m_startOffset = startOffset;
m_endContainer = endContainer;
m_endOffset = endOffset;
// set up the current node for processing
m_node = r->firstNode();
if (!m_node)
return;
setUpFullyClippedStack(m_fullyClippedStack, m_node);
m_offset = m_node == m_startContainer ? m_startOffset : 0;
m_handledNode = false;
m_handledChildren = false;
// calculate first out of bounds node
m_pastEndNode = nextInPreOrderCrossingShadowBoundaries(endContainer, endOffset);
// initialize node processing state
m_needsAnotherNewline = false;
m_textBox = 0;
// initialize record of previous node processing
m_hasEmitted = false;
m_lastTextNode = 0;
m_lastTextNodeEndedWithCollapsedSpace = false;
m_lastCharacter = 0;
#ifndef NDEBUG
// need this just because of the assert in advance()
m_positionNode = m_node;
#endif
// identify the first run
advance();
}
TextIterator::~TextIterator()
{
}
void TextIterator::advance()
{
if (m_shouldStop)
return;
// reset the run information
m_positionNode = 0;
m_textLength = 0;
// handle remembered node that needed a newline after the text node's newline
if (m_needsAnotherNewline) {
// Emit the extra newline, and position it *inside* m_node, after m_node's
// contents, in case it's a block, in the same way that we position the first
// newline. The range for the emitted newline should start where the line
// break begins.
// FIXME: It would be cleaner if we emitted two newlines during the last
// iteration, instead of using m_needsAnotherNewline.
Node* baseNode = m_node->lastChild() ? m_node->lastChild() : m_node;
emitCharacter('\n', baseNode->parentNode(), baseNode, 1, 1);
m_needsAnotherNewline = false;
return;
}
if (!m_textBox && m_remainingTextBox) {
m_textBox = m_remainingTextBox;
m_remainingTextBox = 0;
m_firstLetterText = 0;
m_offset = 0;
}
// handle remembered text box
if (m_textBox) {
handleTextBox();
if (m_positionNode)
return;
}
while (m_node && m_node != m_pastEndNode) {
if (!m_shouldStop && m_stopsOnFormControls && HTMLFormControlElement::enclosingFormControlElement(m_node))
m_shouldStop = true;
// if the range ends at offset 0 of an element, represent the
// position, but not the content, of that element e.g. if the
// node is a blockflow element, emit a newline that
// precedes the element
if (m_node == m_endContainer && m_endOffset == 0) {
representNodeOffsetZero();
m_node = 0;
return;
}
RenderObject* renderer = m_node->renderer();
if (!renderer) {
m_handledNode = true;
m_handledChildren = true;
} else {
// handle current node according to its type
if (!m_handledNode) {
if (renderer->isText() && m_node->nodeType() == Node::TEXT_NODE) // FIXME: What about CDATA_SECTION_NODE?
m_handledNode = handleTextNode();
else if (renderer && (renderer->isImage() || renderer->isWidget() ||
(renderer->node() && renderer->node()->isElementNode() &&
(static_cast<Element*>(renderer->node())->isFormControlElement()
|| static_cast<Element*>(renderer->node())->hasTagName(legendTag)
|| static_cast<Element*>(renderer->node())->hasTagName(meterTag)
|| static_cast<Element*>(renderer->node())->hasTagName(progressTag)))))
m_handledNode = handleReplacedElement();
else
m_handledNode = handleNonTextNode();
if (m_positionNode)
return;
}
}
// find a new current node to handle in depth-first manner,
// calling exitNode() as we come back thru a parent node
Node* next = m_handledChildren ? 0 : m_node->firstChild();
m_offset = 0;
if (!next) {
next = m_node->nextSibling();
if (!next) {
bool pastEnd = m_node->traverseNextNode() == m_pastEndNode;
Node* parentNode = m_node->parentOrHostNode();
while (!next && parentNode) {
if ((pastEnd && parentNode == m_endContainer) || m_endContainer->isDescendantOf(parentNode))
return;
bool haveRenderer = m_node->renderer();
m_node = parentNode;
m_fullyClippedStack.pop();
parentNode = m_node->parentOrHostNode();
if (haveRenderer)
exitNode();
if (m_positionNode) {
m_handledNode = true;
m_handledChildren = true;
return;
}
next = m_node->nextSibling();
}
}
m_fullyClippedStack.pop();
}
// set the new current node
m_node = next;
if (m_node)
pushFullyClippedState(m_fullyClippedStack, m_node);
m_handledNode = false;
m_handledChildren = false;
m_handledFirstLetter = false;
m_firstLetterText = 0;
// how would this ever be?
if (m_positionNode)
return;
}
}
bool TextIterator::handleTextNode()
{
if (m_fullyClippedStack.top() && !m_ignoresStyleVisibility)
return false;
RenderText* renderer = toRenderText(m_node->renderer());
m_lastTextNode = m_node;
String str = renderer->text();
// handle pre-formatted text
if (!renderer->style()->collapseWhiteSpace()) {
int runStart = m_offset;
if (m_lastTextNodeEndedWithCollapsedSpace && hasVisibleTextNode(renderer)) {
emitCharacter(' ', m_node, 0, runStart, runStart);
return false;
}
if (!m_handledFirstLetter && renderer->isTextFragment() && !m_offset) {
handleTextNodeFirstLetter(static_cast<RenderTextFragment*>(renderer));
if (m_firstLetterText) {
String firstLetter = m_firstLetterText->text();
emitText(m_node, m_firstLetterText, m_offset, m_offset + firstLetter.length());
m_firstLetterText = 0;
m_textBox = 0;
return false;
}
}
if (renderer->style()->visibility() != VISIBLE && !m_ignoresStyleVisibility)
return false;
int strLength = str.length();
int end = (m_node == m_endContainer) ? m_endOffset : INT_MAX;
int runEnd = min(strLength, end);
if (runStart >= runEnd)
return true;
emitText(m_node, runStart, runEnd);
return true;
}
if (renderer->firstTextBox())
m_textBox = renderer->firstTextBox();
bool shouldHandleFirstLetter = !m_handledFirstLetter && renderer->isTextFragment() && !m_offset;
if (shouldHandleFirstLetter)
handleTextNodeFirstLetter(static_cast<RenderTextFragment*>(renderer));
if (!renderer->firstTextBox() && str.length() > 0 && !shouldHandleFirstLetter) {
if (renderer->style()->visibility() != VISIBLE && !m_ignoresStyleVisibility)
return false;
m_lastTextNodeEndedWithCollapsedSpace = true; // entire block is collapsed space
return true;
}
if (m_firstLetterText)
renderer = m_firstLetterText;
// Used when text boxes are out of order (Hebrew/Arabic w/ embeded LTR text)
if (renderer->containsReversedText()) {
m_sortedTextBoxes.clear();
for (InlineTextBox* textBox = renderer->firstTextBox(); textBox; textBox = textBox->nextTextBox()) {
m_sortedTextBoxes.append(textBox);
}
std::sort(m_sortedTextBoxes.begin(), m_sortedTextBoxes.end(), InlineTextBox::compareByStart);
m_sortedTextBoxesPosition = 0;
m_textBox = m_sortedTextBoxes.isEmpty() ? 0 : m_sortedTextBoxes[0];
}
handleTextBox();
return true;
}
void TextIterator::handleTextBox()
{
RenderText* renderer = m_firstLetterText ? m_firstLetterText : toRenderText(m_node->renderer());
if (renderer->style()->visibility() != VISIBLE && !m_ignoresStyleVisibility) {
m_textBox = 0;
return;
}
String str = renderer->text();
unsigned start = m_offset;
unsigned end = (m_node == m_endContainer) ? static_cast<unsigned>(m_endOffset) : UINT_MAX;
while (m_textBox) {
unsigned textBoxStart = m_textBox->start();
unsigned runStart = max(textBoxStart, start);
// Check for collapsed space at the start of this run.
InlineTextBox* firstTextBox = renderer->containsReversedText() ? (m_sortedTextBoxes.isEmpty() ? 0 : m_sortedTextBoxes[0]) : renderer->firstTextBox();
bool needSpace = m_lastTextNodeEndedWithCollapsedSpace
|| (m_textBox == firstTextBox && textBoxStart == runStart && runStart > 0);
if (needSpace && !isCollapsibleWhitespace(m_lastCharacter) && m_lastCharacter) {
if (m_lastTextNode == m_node && runStart > 0 && str[runStart - 1] == ' ') {
unsigned spaceRunStart = runStart - 1;
while (spaceRunStart > 0 && str[spaceRunStart - 1] == ' ')
--spaceRunStart;
emitText(m_node, renderer, spaceRunStart, spaceRunStart + 1);
} else
emitCharacter(' ', m_node, 0, runStart, runStart);
return;
}
unsigned textBoxEnd = textBoxStart + m_textBox->len();
unsigned runEnd = min(textBoxEnd, end);
// Determine what the next text box will be, but don't advance yet
InlineTextBox* nextTextBox = 0;
if (renderer->containsReversedText()) {
if (m_sortedTextBoxesPosition + 1 < m_sortedTextBoxes.size())
nextTextBox = m_sortedTextBoxes[m_sortedTextBoxesPosition + 1];
} else
nextTextBox = m_textBox->nextTextBox();
ASSERT(!nextTextBox || nextTextBox->renderer() == renderer);
if (runStart < runEnd) {
// Handle either a single newline character (which becomes a space),
// or a run of characters that does not include a newline.
// This effectively translates newlines to spaces without copying the text.
if (str[runStart] == '\n') {
emitCharacter(' ', m_node, 0, runStart, runStart + 1);
m_offset = runStart + 1;
} else {
size_t subrunEnd = str.find('\n', runStart);
if (subrunEnd == notFound || subrunEnd > runEnd)
subrunEnd = runEnd;
m_offset = subrunEnd;
emitText(m_node, renderer, runStart, subrunEnd);
}
// If we are doing a subrun that doesn't go to the end of the text box,
// come back again to finish handling this text box; don't advance to the next one.
if (static_cast<unsigned>(m_positionEndOffset) < textBoxEnd)
return;
// Advance and return
unsigned nextRunStart = nextTextBox ? nextTextBox->start() : str.length();
if (nextRunStart > runEnd)
m_lastTextNodeEndedWithCollapsedSpace = true; // collapsed space between runs or at the end
m_textBox = nextTextBox;
if (renderer->containsReversedText())
++m_sortedTextBoxesPosition;
return;
}
// Advance and continue
m_textBox = nextTextBox;
if (renderer->containsReversedText())
++m_sortedTextBoxesPosition;
}
if (!m_textBox && m_remainingTextBox) {
m_textBox = m_remainingTextBox;
m_remainingTextBox = 0;
m_firstLetterText = 0;
m_offset = 0;
handleTextBox();
}
}
static inline RenderText* firstRenderTextInFirstLetter(RenderObject* firstLetter)
{
if (!firstLetter)
return 0;
// FIXME: Should this check descendent objects?
for (RenderObject* current = firstLetter->firstChild(); current; current = current->nextSibling()) {
if (current->isText())
return toRenderText(current);
}
return 0;
}
void TextIterator::handleTextNodeFirstLetter(RenderTextFragment* renderer)
{
if (renderer->firstLetter()) {
RenderObject* r = renderer->firstLetter();
if (r->style()->visibility() != VISIBLE && !m_ignoresStyleVisibility)
return;
if (RenderText* firstLetter = firstRenderTextInFirstLetter(r)) {
m_handledFirstLetter = true;
m_remainingTextBox = m_textBox;
m_textBox = firstLetter->firstTextBox();
m_sortedTextBoxes.clear();
m_firstLetterText = firstLetter;
}
}
m_handledFirstLetter = true;
}
bool TextIterator::handleReplacedElement()
{
if (m_fullyClippedStack.top())
return false;
RenderObject* renderer = m_node->renderer();
if (renderer->style()->visibility() != VISIBLE && !m_ignoresStyleVisibility)
return false;
if (m_lastTextNodeEndedWithCollapsedSpace) {
emitCharacter(' ', m_lastTextNode->parentNode(), m_lastTextNode, 1, 1);
return false;
}
if (m_entersTextControls && renderer->isTextControl()) {
if (HTMLElement* innerTextElement = toRenderTextControl(renderer)->textFormControlElement()->innerTextElement()) {
m_node = innerTextElement->shadowRoot();
pushFullyClippedState(m_fullyClippedStack, m_node);
m_offset = 0;
return false;
}
}
m_hasEmitted = true;
if (m_emitsObjectReplacementCharacters && renderer && renderer->isReplaced()) {
emitCharacter(objectReplacementCharacter, m_node->parentNode(), m_node, 0, 1);
return true;
}
if (m_emitsCharactersBetweenAllVisiblePositions) {
// We want replaced elements to behave like punctuation for boundary
// finding, and to simply take up space for the selection preservation
// code in moveParagraphs, so we use a comma.
emitCharacter(',', m_node->parentNode(), m_node, 0, 1);
return true;
}
m_positionNode = m_node->parentNode();
m_positionOffsetBaseNode = m_node;
m_positionStartOffset = 0;
m_positionEndOffset = 1;
m_textCharacters = 0;
m_textLength = 0;
m_lastCharacter = 0;
return true;
}
bool TextIterator::hasVisibleTextNode(RenderText* renderer)
{
if (renderer->style()->visibility() == VISIBLE)
return true;
if (renderer->isTextFragment()) {
RenderTextFragment* fragment = static_cast<RenderTextFragment*>(renderer);
if (fragment->firstLetter() && fragment->firstLetter()->style()->visibility() == VISIBLE)
return true;
}
return false;
}
static bool shouldEmitTabBeforeNode(Node* node)
{
RenderObject* r = node->renderer();
// Table cells are delimited by tabs.
if (!r || !isTableCell(node))
return false;
// Want a tab before every cell other than the first one
RenderTableCell* rc = toRenderTableCell(r);
RenderTable* t = rc->table();
return t && (t->cellBefore(rc) || t->cellAbove(rc));
}
static bool shouldEmitNewlineForNode(Node* node)
{
// br elements are represented by a single newline.
RenderObject* r = node->renderer();
if (!r)
return node->hasTagName(brTag);
return r->isBR();
}
static bool shouldEmitNewlinesBeforeAndAfterNode(Node* node)
{
// Block flow (versus inline flow) is represented by having
// a newline both before and after the element.
RenderObject* r = node->renderer();
if (!r) {
return (node->hasTagName(blockquoteTag)
|| node->hasTagName(ddTag)
|| node->hasTagName(divTag)
|| node->hasTagName(dlTag)
|| node->hasTagName(dtTag)
|| node->hasTagName(h1Tag)
|| node->hasTagName(h2Tag)
|| node->hasTagName(h3Tag)
|| node->hasTagName(h4Tag)
|| node->hasTagName(h5Tag)
|| node->hasTagName(h6Tag)
|| node->hasTagName(hrTag)
|| node->hasTagName(liTag)
|| node->hasTagName(listingTag)
|| node->hasTagName(olTag)
|| node->hasTagName(pTag)
|| node->hasTagName(preTag)
|| node->hasTagName(trTag)
|| node->hasTagName(ulTag));
}
// Need to make an exception for table cells, because they are blocks, but we
// want them tab-delimited rather than having newlines before and after.
if (isTableCell(node))
return false;
// Need to make an exception for table row elements, because they are neither
// "inline" or "RenderBlock", but we want newlines for them.
if (r->isTableRow()) {
RenderTable* t = toRenderTableRow(r)->table();
if (t && !t->isInline())
return true;
}
return !r->isInline() && r->isRenderBlock() && !r->isFloatingOrOutOfFlowPositioned() && !r->isBody();
}
static bool shouldEmitNewlineAfterNode(Node* node)
{
// FIXME: It should be better but slower to create a VisiblePosition here.
if (!shouldEmitNewlinesBeforeAndAfterNode(node))
return false;
// Check if this is the very last renderer in the document.
// If so, then we should not emit a newline.
while ((node = node->traverseNextSibling()))
if (node->renderer())
return true;
return false;
}
static bool shouldEmitNewlineBeforeNode(Node* node)
{
return shouldEmitNewlinesBeforeAndAfterNode(node);
}
static bool shouldEmitExtraNewlineForNode(Node* node)
{
// When there is a significant collapsed bottom margin, emit an extra
// newline for a more realistic result. We end up getting the right
// result even without margin collapsing. For example: <div><p>text</p></div>
// will work right even if both the <div> and the <p> have bottom margins.
RenderObject* r = node->renderer();
if (!r || !r->isBox())
return false;
// NOTE: We only do this for a select set of nodes, and fwiw WinIE appears
// not to do this at all
if (node->hasTagName(h1Tag)
|| node->hasTagName(h2Tag)
|| node->hasTagName(h3Tag)
|| node->hasTagName(h4Tag)
|| node->hasTagName(h5Tag)
|| node->hasTagName(h6Tag)
|| node->hasTagName(pTag)) {
RenderStyle* style = r->style();
if (style) {
int bottomMargin = toRenderBox(r)->collapsedMarginAfter();
int fontSize = style->fontDescription().computedPixelSize();
if (bottomMargin * 2 >= fontSize)
return true;
}
}
return false;
}
static int collapsedSpaceLength(RenderText* renderer, int textEnd)
{
const UChar* characters = renderer->text()->characters();
int length = renderer->text()->length();
for (int i = textEnd; i < length; ++i) {
if (!renderer->style()->isCollapsibleWhiteSpace(characters[i]))
return i - textEnd;
}
return length - textEnd;
}
static int maxOffsetIncludingCollapsedSpaces(Node* node)
{
int offset = caretMaxOffset(node);
if (node->renderer() && node->renderer()->isText())
offset += collapsedSpaceLength(toRenderText(node->renderer()), offset);
return offset;
}
// Whether or not we should emit a character as we enter m_node (if it's a container) or as we hit it (if it's atomic).
bool TextIterator::shouldRepresentNodeOffsetZero()
{
if (m_emitsCharactersBetweenAllVisiblePositions && m_node->renderer() && m_node->renderer()->isTable())
return true;
// Leave element positioned flush with start of a paragraph
// (e.g. do not insert tab before a table cell at the start of a paragraph)
if (m_lastCharacter == '\n')
return false;
// Otherwise, show the position if we have emitted any characters
if (m_hasEmitted)
return true;
// We've not emitted anything yet. Generally, there is no need for any positioning then.
// The only exception is when the element is visually not in the same line as
// the start of the range (e.g. the range starts at the end of the previous paragraph).
// NOTE: Creating VisiblePositions and comparing them is relatively expensive, so we
// make quicker checks to possibly avoid that. Another check that we could make is
// is whether the inline vs block flow changed since the previous visible element.
// I think we're already in a special enough case that that won't be needed, tho.
// No character needed if this is the first node in the range.
if (m_node == m_startContainer)
return false;
// If we are outside the start container's subtree, assume we need to emit.
// FIXME: m_startContainer could be an inline block
if (!m_node->isDescendantOf(m_startContainer))
return true;
// If we started as m_startContainer offset 0 and the current node is a descendant of
// the start container, we already had enough context to correctly decide whether to
// emit after a preceding block. We chose not to emit (m_hasEmitted is false),
// so don't second guess that now.
// NOTE: Is this really correct when m_node is not a leftmost descendant? Probably
// immaterial since we likely would have already emitted something by now.
if (m_startOffset == 0)
return false;
// If this node is unrendered or invisible the VisiblePosition checks below won't have much meaning.
// Additionally, if the range we are iterating over contains huge sections of unrendered content,
// we would create VisiblePositions on every call to this function without this check.
if (!m_node->renderer() || m_node->renderer()->style()->visibility() != VISIBLE
|| (m_node->renderer()->isBlockFlow() && !toRenderBlock(m_node->renderer())->height() && !m_node->hasTagName(bodyTag)))
return false;
// The startPos.isNotNull() check is needed because the start could be before the body,
// and in that case we'll get null. We don't want to put in newlines at the start in that case.
// The currPos.isNotNull() check is needed because positions in non-HTML content
// (like SVG) do not have visible positions, and we don't want to emit for them either.
VisiblePosition startPos = VisiblePosition(Position(m_startContainer, m_startOffset, Position::PositionIsOffsetInAnchor), DOWNSTREAM);
VisiblePosition currPos = VisiblePosition(positionBeforeNode(m_node), DOWNSTREAM);
return startPos.isNotNull() && currPos.isNotNull() && !inSameLine(startPos, currPos);
}
bool TextIterator::shouldEmitSpaceBeforeAndAfterNode(Node* node)
{
return node->renderer() && node->renderer()->isTable() && (node->renderer()->isInline() || m_emitsCharactersBetweenAllVisiblePositions);
}
void TextIterator::representNodeOffsetZero()
{
// Emit a character to show the positioning of m_node.
// When we haven't been emitting any characters, shouldRepresentNodeOffsetZero() can
// create VisiblePositions, which is expensive. So, we perform the inexpensive checks
// on m_node to see if it necessitates emitting a character first and will early return
// before encountering shouldRepresentNodeOffsetZero()s worse case behavior.
if (shouldEmitTabBeforeNode(m_node)) {
if (shouldRepresentNodeOffsetZero())
emitCharacter('\t', m_node->parentNode(), m_node, 0, 0);
} else if (shouldEmitNewlineBeforeNode(m_node)) {
if (shouldRepresentNodeOffsetZero())
emitCharacter('\n', m_node->parentNode(), m_node, 0, 0);
} else if (shouldEmitSpaceBeforeAndAfterNode(m_node)) {
if (shouldRepresentNodeOffsetZero())
emitCharacter(' ', m_node->parentNode(), m_node, 0, 0);
}
}
bool TextIterator::handleNonTextNode()
{
if (shouldEmitNewlineForNode(m_node))
emitCharacter('\n', m_node->parentNode(), m_node, 0, 1);
else if (m_emitsCharactersBetweenAllVisiblePositions && m_node->renderer() && m_node->renderer()->isHR())
emitCharacter(' ', m_node->parentNode(), m_node, 0, 1);
else
representNodeOffsetZero();
return true;
}
void TextIterator::exitNode()
{
// prevent emitting a newline when exiting a collapsed block at beginning of the range
// FIXME: !m_hasEmitted does not necessarily mean there was a collapsed block... it could
// have been an hr (e.g.). Also, a collapsed block could have height (e.g. a table) and
// therefore look like a blank line.
if (!m_hasEmitted)
return;
// Emit with a position *inside* m_node, after m_node's contents, in
// case it is a block, because the run should start where the
// emitted character is positioned visually.
Node* baseNode = m_node->lastChild() ? m_node->lastChild() : m_node;
// FIXME: This shouldn't require the m_lastTextNode to be true, but we can't change that without making
// the logic in _web_attributedStringFromRange match. We'll get that for free when we switch to use
// TextIterator in _web_attributedStringFromRange.
// See <rdar://problem/5428427> for an example of how this mismatch will cause problems.
if (m_lastTextNode && shouldEmitNewlineAfterNode(m_node)) {
// use extra newline to represent margin bottom, as needed
bool addNewline = shouldEmitExtraNewlineForNode(m_node);
// FIXME: We need to emit a '\n' as we leave an empty block(s) that
// contain a VisiblePosition when doing selection preservation.
if (m_lastCharacter != '\n') {
// insert a newline with a position following this block's contents.
emitCharacter('\n', baseNode->parentNode(), baseNode, 1, 1);
// remember whether to later add a newline for the current node
ASSERT(!m_needsAnotherNewline);
m_needsAnotherNewline = addNewline;
} else if (addNewline)
// insert a newline with a position following this block's contents.
emitCharacter('\n', baseNode->parentNode(), baseNode, 1, 1);
}
// If nothing was emitted, see if we need to emit a space.
if (!m_positionNode && shouldEmitSpaceBeforeAndAfterNode(m_node))
emitCharacter(' ', baseNode->parentNode(), baseNode, 1, 1);
}
void TextIterator::emitCharacter(UChar c, Node* textNode, Node* offsetBaseNode, int textStartOffset, int textEndOffset)
{
m_hasEmitted = true;
// remember information with which to construct the TextIterator::range()
// NOTE: textNode is often not a text node, so the range will specify child nodes of positionNode
m_positionNode = textNode;
m_positionOffsetBaseNode = offsetBaseNode;
m_positionStartOffset = textStartOffset;
m_positionEndOffset = textEndOffset;
// remember information with which to construct the TextIterator::characters() and length()
m_singleCharacterBuffer = c;
m_textCharacters = &m_singleCharacterBuffer;
m_textLength = 1;