-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvisible_units.cpp
1414 lines (1183 loc) · 52.6 KB
/
visible_units.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 Apple Inc. All rights reserved.
*
* 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 "visible_units.h"
#include "Document.h"
#include "Element.h"
#include "HTMLNames.h"
#include "InlineTextBox.h"
#include "Position.h"
#include "RenderBlock.h"
#include "RenderObject.h"
#include "RenderedPosition.h"
#include "Text.h"
#include "TextBoundaries.h"
#include "TextIterator.h"
#include "VisiblePosition.h"
#include "VisibleSelection.h"
#include "htmlediting.h"
#include <wtf/unicode/Unicode.h>
namespace WebCore {
using namespace HTMLNames;
using namespace WTF::Unicode;
static Node* previousLeafWithSameEditability(Node* node, EditableType editableType)
{
bool editable = node->rendererIsEditable(editableType);
node = node->previousLeafNode();
while (node) {
if (editable == node->rendererIsEditable(editableType))
return node;
node = node->previousLeafNode();
}
return 0;
}
static Node* nextLeafWithSameEditability(Node* node, EditableType editableType = ContentIsEditable)
{
if (!node)
return 0;
bool editable = node->rendererIsEditable(editableType);
node = node->nextLeafNode();
while (node) {
if (editable == node->rendererIsEditable(editableType))
return node;
node = node->nextLeafNode();
}
return 0;
}
// FIXME: consolidate with code in previousLinePosition.
static Position previousRootInlineBoxCandidatePosition(Node* node, const VisiblePosition& visiblePosition, EditableType editableType)
{
Node* highestRoot = highestEditableRoot(visiblePosition.deepEquivalent(), editableType);
Node* previousNode = previousLeafWithSameEditability(node, editableType);
while (previousNode && inSameLine(firstPositionInOrBeforeNode(previousNode), visiblePosition))
previousNode = previousLeafWithSameEditability(previousNode, editableType);
while (previousNode && !previousNode->isShadowRoot()) {
if (highestEditableRoot(firstPositionInOrBeforeNode(previousNode), editableType) != highestRoot)
break;
Position pos = previousNode->hasTagName(brTag) ? positionBeforeNode(previousNode) :
createLegacyEditingPosition(previousNode, caretMaxOffset(previousNode));
if (pos.isCandidate())
return pos;
previousNode = previousLeafWithSameEditability(previousNode, editableType);
}
return Position();
}
static Position nextRootInlineBoxCandidatePosition(Node* node, const VisiblePosition& visiblePosition, EditableType editableType)
{
Node* highestRoot = highestEditableRoot(visiblePosition.deepEquivalent(), editableType);
Node* nextNode = nextLeafWithSameEditability(node, editableType);
while (nextNode && inSameLine(firstPositionInOrBeforeNode(nextNode), visiblePosition))
nextNode = nextLeafWithSameEditability(nextNode, ContentIsEditable);
while (nextNode && !nextNode->isShadowRoot()) {
if (highestEditableRoot(firstPositionInOrBeforeNode(nextNode), editableType) != highestRoot)
break;
Position pos;
pos = createLegacyEditingPosition(nextNode, caretMinOffset(nextNode));
if (pos.isCandidate())
return pos;
nextNode = nextLeafWithSameEditability(nextNode, editableType);
}
return Position();
}
class CachedLogicallyOrderedLeafBoxes {
public:
CachedLogicallyOrderedLeafBoxes();
const InlineTextBox* previousTextBox(const RootInlineBox*, const InlineTextBox*);
const InlineTextBox* nextTextBox(const RootInlineBox*, const InlineTextBox*);
size_t size() const { return m_leafBoxes.size(); }
const InlineBox* firstBox() const { return m_leafBoxes[0]; }
private:
const Vector<InlineBox*>& collectBoxes(const RootInlineBox*);
int boxIndexInLeaves(const InlineTextBox*);
const RootInlineBox* m_rootInlineBox;
Vector<InlineBox*> m_leafBoxes;
};
CachedLogicallyOrderedLeafBoxes::CachedLogicallyOrderedLeafBoxes() : m_rootInlineBox(0) { };
const InlineTextBox* CachedLogicallyOrderedLeafBoxes::previousTextBox(const RootInlineBox* root, const InlineTextBox* box)
{
if (!root)
return 0;
collectBoxes(root);
// If box is null, root is box's previous RootInlineBox, and previousBox is the last logical box in root.
int boxIndex = m_leafBoxes.size() - 1;
if (box)
boxIndex = boxIndexInLeaves(box) - 1;
for (int i = boxIndex; i >= 0; --i) {
if (m_leafBoxes[i]->isInlineTextBox())
return toInlineTextBox(m_leafBoxes[i]);
}
return 0;
}
const InlineTextBox* CachedLogicallyOrderedLeafBoxes::nextTextBox(const RootInlineBox* root, const InlineTextBox* box)
{
if (!root)
return 0;
collectBoxes(root);
// If box is null, root is box's next RootInlineBox, and nextBox is the first logical box in root.
// Otherwise, root is box's RootInlineBox, and nextBox is the next logical box in the same line.
size_t nextBoxIndex = 0;
if (box)
nextBoxIndex = boxIndexInLeaves(box) + 1;
for (size_t i = nextBoxIndex; i < m_leafBoxes.size(); ++i) {
if (m_leafBoxes[i]->isInlineTextBox())
return toInlineTextBox(m_leafBoxes[i]);
}
return 0;
}
const Vector<InlineBox*>& CachedLogicallyOrderedLeafBoxes::collectBoxes(const RootInlineBox* root)
{
if (m_rootInlineBox != root) {
m_rootInlineBox = root;
m_leafBoxes.clear();
root->collectLeafBoxesInLogicalOrder(m_leafBoxes);
}
return m_leafBoxes;
}
int CachedLogicallyOrderedLeafBoxes::boxIndexInLeaves(const InlineTextBox* box)
{
for (size_t i = 0; i < m_leafBoxes.size(); ++i) {
if (box == m_leafBoxes[i])
return i;
}
return 0;
}
static const InlineTextBox* logicallyPreviousBox(const VisiblePosition& visiblePosition, const InlineTextBox* textBox,
bool& previousBoxInDifferentBlock, CachedLogicallyOrderedLeafBoxes& leafBoxes)
{
const InlineBox* startBox = textBox;
const InlineTextBox* previousBox = leafBoxes.previousTextBox(startBox->root(), textBox);
if (previousBox)
return previousBox;
previousBox = leafBoxes.previousTextBox(startBox->root()->prevRootBox(), 0);
if (previousBox)
return previousBox;
while (1) {
Node* startNode = startBox->renderer() ? startBox->renderer()->node() : 0;
if (!startNode)
break;
Position position = previousRootInlineBoxCandidatePosition(startNode, visiblePosition, ContentIsEditable);
if (position.isNull())
break;
RenderedPosition renderedPosition(position, DOWNSTREAM);
RootInlineBox* previousRoot = renderedPosition.rootBox();
if (!previousRoot)
break;
previousBox = leafBoxes.previousTextBox(previousRoot, 0);
if (previousBox) {
previousBoxInDifferentBlock = true;
return previousBox;
}
if (!leafBoxes.size())
break;
startBox = leafBoxes.firstBox();
}
return 0;
}
static const InlineTextBox* logicallyNextBox(const VisiblePosition& visiblePosition, const InlineTextBox* textBox,
bool& nextBoxInDifferentBlock, CachedLogicallyOrderedLeafBoxes& leafBoxes)
{
const InlineBox* startBox = textBox;
const InlineTextBox* nextBox = leafBoxes.nextTextBox(startBox->root(), textBox);
if (nextBox)
return nextBox;
nextBox = leafBoxes.nextTextBox(startBox->root()->nextRootBox(), 0);
if (nextBox)
return nextBox;
while (1) {
Node* startNode = startBox->renderer() ? startBox->renderer()->node() : 0;
if (!startNode)
break;
Position position = nextRootInlineBoxCandidatePosition(startNode, visiblePosition, ContentIsEditable);
if (position.isNull())
break;
RenderedPosition renderedPosition(position, DOWNSTREAM);
RootInlineBox* nextRoot = renderedPosition.rootBox();
if (!nextRoot)
break;
nextBox = leafBoxes.nextTextBox(nextRoot, 0);
if (nextBox) {
nextBoxInDifferentBlock = true;
return nextBox;
}
if (!leafBoxes.size())
break;
startBox = leafBoxes.firstBox();
}
return 0;
}
static TextBreakIterator* wordBreakIteratorForMinOffsetBoundary(const VisiblePosition& visiblePosition, const InlineTextBox* textBox,
int& previousBoxLength, bool& previousBoxInDifferentBlock, Vector<UChar, 1024>& string, CachedLogicallyOrderedLeafBoxes& leafBoxes)
{
previousBoxInDifferentBlock = false;
// FIXME: Handle the case when we don't have an inline text box.
const InlineTextBox* previousBox = logicallyPreviousBox(visiblePosition, textBox, previousBoxInDifferentBlock, leafBoxes);
int len = 0;
string.clear();
if (previousBox) {
previousBoxLength = previousBox->len();
string.append(previousBox->textRenderer()->text()->characters() + previousBox->start(), previousBoxLength);
len += previousBoxLength;
}
string.append(textBox->textRenderer()->text()->characters() + textBox->start(), textBox->len());
len += textBox->len();
return wordBreakIterator(string.data(), len);
}
static TextBreakIterator* wordBreakIteratorForMaxOffsetBoundary(const VisiblePosition& visiblePosition, const InlineTextBox* textBox,
bool& nextBoxInDifferentBlock, Vector<UChar, 1024>& string, CachedLogicallyOrderedLeafBoxes& leafBoxes)
{
nextBoxInDifferentBlock = false;
// FIXME: Handle the case when we don't have an inline text box.
const InlineTextBox* nextBox = logicallyNextBox(visiblePosition, textBox, nextBoxInDifferentBlock, leafBoxes);
int len = 0;
string.clear();
string.append(textBox->textRenderer()->text()->characters() + textBox->start(), textBox->len());
len += textBox->len();
if (nextBox) {
string.append(nextBox->textRenderer()->text()->characters() + nextBox->start(), nextBox->len());
len += nextBox->len();
}
return wordBreakIterator(string.data(), len);
}
bool isLogicalStartOfWord(TextBreakIterator* iter, int position, bool hardLineBreak)
{
bool boundary = hardLineBreak ? true : isTextBreak(iter, position);
if (!boundary)
return false;
textBreakFollowing(iter, position);
// isWordTextBreak returns true after moving across a word and false after moving across a punctuation/space.
return isWordTextBreak(iter);
}
bool islogicalEndOfWord(TextBreakIterator* iter, int position, bool hardLineBreak)
{
bool boundary = isTextBreak(iter, position);
return (hardLineBreak || boundary) && isWordTextBreak(iter);
}
enum CursorMovementDirection { MoveLeft, MoveRight };
static VisiblePosition visualWordPosition(const VisiblePosition& visiblePosition, CursorMovementDirection direction,
bool skipsSpaceWhenMovingRight)
{
if (visiblePosition.isNull())
return VisiblePosition();
TextDirection blockDirection = directionOfEnclosingBlock(visiblePosition.deepEquivalent());
InlineBox* previouslyVisitedBox = 0;
VisiblePosition current = visiblePosition;
TextBreakIterator* iter = 0;
CachedLogicallyOrderedLeafBoxes leafBoxes;
Vector<UChar, 1024> string;
while (1) {
VisiblePosition adjacentCharacterPosition = direction == MoveRight ? current.right(true) : current.left(true);
if (adjacentCharacterPosition == current || adjacentCharacterPosition.isNull())
return VisiblePosition();
InlineBox* box;
int offsetInBox;
adjacentCharacterPosition.deepEquivalent().getInlineBoxAndOffset(UPSTREAM, box, offsetInBox);
if (!box)
break;
if (!box->isInlineTextBox()) {
current = adjacentCharacterPosition;
continue;
}
InlineTextBox* textBox = toInlineTextBox(box);
int previousBoxLength = 0;
bool previousBoxInDifferentBlock = false;
bool nextBoxInDifferentBlock = false;
bool movingIntoNewBox = previouslyVisitedBox != box;
if (offsetInBox == box->caretMinOffset())
iter = wordBreakIteratorForMinOffsetBoundary(visiblePosition, textBox, previousBoxLength, previousBoxInDifferentBlock, string, leafBoxes);
else if (offsetInBox == box->caretMaxOffset())
iter = wordBreakIteratorForMaxOffsetBoundary(visiblePosition, textBox, nextBoxInDifferentBlock, string, leafBoxes);
else if (movingIntoNewBox) {
iter = wordBreakIterator(textBox->textRenderer()->text()->characters() + textBox->start(), textBox->len());
previouslyVisitedBox = box;
}
if (!iter)
break;
textBreakFirst(iter);
int offsetInIterator = offsetInBox - textBox->start() + previousBoxLength;
bool isWordBreak;
bool boxHasSameDirectionalityAsBlock = box->direction() == blockDirection;
bool movingBackward = (direction == MoveLeft && box->direction() == LTR) || (direction == MoveRight && box->direction() == RTL);
if ((skipsSpaceWhenMovingRight && boxHasSameDirectionalityAsBlock)
|| (!skipsSpaceWhenMovingRight && movingBackward)) {
bool logicalStartInRenderer = offsetInBox == static_cast<int>(textBox->start()) && previousBoxInDifferentBlock;
isWordBreak = isLogicalStartOfWord(iter, offsetInIterator, logicalStartInRenderer);
} else {
bool logicalEndInRenderer = offsetInBox == static_cast<int>(textBox->start() + textBox->len()) && nextBoxInDifferentBlock;
isWordBreak = islogicalEndOfWord(iter, offsetInIterator, logicalEndInRenderer);
}
if (isWordBreak)
return adjacentCharacterPosition;
current = adjacentCharacterPosition;
}
return VisiblePosition();
}
VisiblePosition leftWordPosition(const VisiblePosition& visiblePosition, bool skipsSpaceWhenMovingRight)
{
VisiblePosition leftWordBreak = visualWordPosition(visiblePosition, MoveLeft, skipsSpaceWhenMovingRight);
leftWordBreak = visiblePosition.honorEditingBoundaryAtOrBefore(leftWordBreak);
// FIXME: How should we handle a non-editable position?
if (leftWordBreak.isNull() && isEditablePosition(visiblePosition.deepEquivalent())) {
TextDirection blockDirection = directionOfEnclosingBlock(visiblePosition.deepEquivalent());
leftWordBreak = blockDirection == LTR ? startOfEditableContent(visiblePosition) : endOfEditableContent(visiblePosition);
}
return leftWordBreak;
}
VisiblePosition rightWordPosition(const VisiblePosition& visiblePosition, bool skipsSpaceWhenMovingRight)
{
VisiblePosition rightWordBreak = visualWordPosition(visiblePosition, MoveRight, skipsSpaceWhenMovingRight);
rightWordBreak = visiblePosition.honorEditingBoundaryAtOrBefore(rightWordBreak);
// FIXME: How should we handle a non-editable position?
if (rightWordBreak.isNull() && isEditablePosition(visiblePosition.deepEquivalent())) {
TextDirection blockDirection = directionOfEnclosingBlock(visiblePosition.deepEquivalent());
rightWordBreak = blockDirection == LTR ? endOfEditableContent(visiblePosition) : startOfEditableContent(visiblePosition);
}
return rightWordBreak;
}
enum BoundarySearchContextAvailability { DontHaveMoreContext, MayHaveMoreContext };
typedef unsigned (*BoundarySearchFunction)(const UChar*, unsigned length, unsigned offset, BoundarySearchContextAvailability, bool& needMoreContext);
static VisiblePosition previousBoundary(const VisiblePosition& c, BoundarySearchFunction searchFunction)
{
Position pos = c.deepEquivalent();
Node* boundary = pos.parentEditingBoundary();
if (!boundary)
return VisiblePosition();
Document* d = boundary->document();
Position start = createLegacyEditingPosition(boundary, 0).parentAnchoredEquivalent();
Position end = pos.parentAnchoredEquivalent();
RefPtr<Range> searchRange = Range::create(d);
Vector<UChar, 1024> string;
unsigned suffixLength = 0;
ExceptionCode ec = 0;
if (requiresContextForWordBoundary(c.characterBefore())) {
RefPtr<Range> forwardsScanRange(d->createRange());
forwardsScanRange->setEndAfter(boundary, ec);
forwardsScanRange->setStart(end.deprecatedNode(), end.deprecatedEditingOffset(), ec);
TextIterator forwardsIterator(forwardsScanRange.get());
while (!forwardsIterator.atEnd()) {
const UChar* characters = forwardsIterator.characters();
int length = forwardsIterator.length();
int i = endOfFirstWordBoundaryContext(characters, length);
string.append(characters, i);
suffixLength += i;
if (i < length)
break;
forwardsIterator.advance();
}
}
searchRange->setStart(start.deprecatedNode(), start.deprecatedEditingOffset(), ec);
searchRange->setEnd(end.deprecatedNode(), end.deprecatedEditingOffset(), ec);
ASSERT(!ec);
if (ec)
return VisiblePosition();
SimplifiedBackwardsTextIterator it(searchRange.get());
unsigned next = 0;
bool inTextSecurityMode = start.deprecatedNode() && start.deprecatedNode()->renderer() && start.deprecatedNode()->renderer()->style()->textSecurity() != TSNONE;
bool needMoreContext = false;
while (!it.atEnd()) {
// iterate to get chunks until the searchFunction returns a non-zero value.
if (!inTextSecurityMode)
string.prepend(it.characters(), it.length());
else {
// Treat bullets used in the text security mode as regular characters when looking for boundaries
String iteratorString(it.characters(), it.length());
iteratorString.fill('x');
string.prepend(iteratorString.characters(), iteratorString.length());
}
next = searchFunction(string.data(), string.size(), string.size() - suffixLength, MayHaveMoreContext, needMoreContext);
if (next != 0)
break;
it.advance();
}
if (needMoreContext) {
// The last search returned the beginning of the buffer and asked for more context,
// but there is no earlier text. Force a search with what's available.
next = searchFunction(string.data(), string.size(), string.size() - suffixLength, DontHaveMoreContext, needMoreContext);
ASSERT(!needMoreContext);
}
if (!next)
return VisiblePosition(it.atEnd() ? it.range()->startPosition() : pos, DOWNSTREAM);
Node* node = it.range()->startContainer(ec);
if ((node->isTextNode() && static_cast<int>(next) <= node->maxCharacterOffset()) || (node->renderer() && node->renderer()->isBR() && !next))
// The next variable contains a usable index into a text node
return VisiblePosition(createLegacyEditingPosition(node, next), DOWNSTREAM);
// Use the character iterator to translate the next value into a DOM position.
BackwardsCharacterIterator charIt(searchRange.get());
charIt.advance(string.size() - suffixLength - next);
// FIXME: charIt can get out of shadow host.
return VisiblePosition(charIt.range()->endPosition(), DOWNSTREAM);
}
static VisiblePosition nextBoundary(const VisiblePosition& c, BoundarySearchFunction searchFunction)
{
Position pos = c.deepEquivalent();
Node* boundary = pos.parentEditingBoundary();
if (!boundary)
return VisiblePosition();
Document* d = boundary->document();
RefPtr<Range> searchRange(d->createRange());
Position start(pos.parentAnchoredEquivalent());
Vector<UChar, 1024> string;
unsigned prefixLength = 0;
ExceptionCode ec = 0;
if (requiresContextForWordBoundary(c.characterAfter())) {
RefPtr<Range> backwardsScanRange(d->createRange());
backwardsScanRange->setEnd(start.deprecatedNode(), start.deprecatedEditingOffset(), ec);
SimplifiedBackwardsTextIterator backwardsIterator(backwardsScanRange.get());
while (!backwardsIterator.atEnd()) {
const UChar* characters = backwardsIterator.characters();
int length = backwardsIterator.length();
int i = startOfLastWordBoundaryContext(characters, length);
string.prepend(characters + i, length - i);
prefixLength += length - i;
if (i > 0)
break;
backwardsIterator.advance();
}
}
searchRange->selectNodeContents(boundary, ec);
searchRange->setStart(start.deprecatedNode(), start.deprecatedEditingOffset(), ec);
TextIterator it(searchRange.get(), TextIteratorEmitsCharactersBetweenAllVisiblePositions);
unsigned next = 0;
bool inTextSecurityMode = start.deprecatedNode() && start.deprecatedNode()->renderer() && start.deprecatedNode()->renderer()->style()->textSecurity() != TSNONE;
bool needMoreContext = false;
while (!it.atEnd()) {
// Keep asking the iterator for chunks until the search function
// returns an end value not equal to the length of the string passed to it.
if (!inTextSecurityMode)
string.append(it.characters(), it.length());
else {
// Treat bullets used in the text security mode as regular characters when looking for boundaries
String iteratorString(it.characters(), it.length());
iteratorString.fill('x');
string.append(iteratorString.characters(), iteratorString.length());
}
next = searchFunction(string.data(), string.size(), prefixLength, MayHaveMoreContext, needMoreContext);
if (next != string.size())
break;
it.advance();
}
if (needMoreContext) {
// The last search returned the end of the buffer and asked for more context,
// but there is no further text. Force a search with what's available.
next = searchFunction(string.data(), string.size(), prefixLength, DontHaveMoreContext, needMoreContext);
ASSERT(!needMoreContext);
}
if (it.atEnd() && next == string.size()) {
pos = it.range()->startPosition();
} else if (next != prefixLength) {
// Use the character iterator to translate the next value into a DOM position.
CharacterIterator charIt(searchRange.get(), TextIteratorEmitsCharactersBetweenAllVisiblePositions);
charIt.advance(next - prefixLength - 1);
RefPtr<Range> characterRange = charIt.range();
pos = characterRange->endPosition();
if (*charIt.characters() == '\n') {
// FIXME: workaround for collapsed range (where only start position is correct) emitted for some emitted newlines (see rdar://5192593)
VisiblePosition visPos = VisiblePosition(pos);
if (visPos == VisiblePosition(characterRange->startPosition())) {
charIt.advance(1);
pos = charIt.range()->startPosition();
}
}
}
// generate VisiblePosition, use UPSTREAM affinity if possible
return VisiblePosition(pos, VP_UPSTREAM_IF_POSSIBLE);
}
// ---------
static unsigned startWordBoundary(const UChar* characters, unsigned length, unsigned offset, BoundarySearchContextAvailability mayHaveMoreContext, bool& needMoreContext)
{
ASSERT(offset);
if (mayHaveMoreContext && !startOfLastWordBoundaryContext(characters, offset)) {
needMoreContext = true;
return 0;
}
needMoreContext = false;
int start, end;
U16_BACK_1(characters, 0, offset);
findWordBoundary(characters, length, offset, &start, &end);
return start;
}
VisiblePosition startOfWord(const VisiblePosition &c, EWordSide side)
{
// FIXME: This returns a null VP for c at the start of the document
// and side == LeftWordIfOnBoundary
VisiblePosition p = c;
if (side == RightWordIfOnBoundary) {
// at paragraph end, the startofWord is the current position
if (isEndOfParagraph(c))
return c;
p = c.next();
if (p.isNull())
return c;
}
return previousBoundary(p, startWordBoundary);
}
static unsigned endWordBoundary(const UChar* characters, unsigned length, unsigned offset, BoundarySearchContextAvailability mayHaveMoreContext, bool& needMoreContext)
{
ASSERT(offset <= length);
if (mayHaveMoreContext && endOfFirstWordBoundaryContext(characters + offset, length - offset) == static_cast<int>(length - offset)) {
needMoreContext = true;
return length;
}
needMoreContext = false;
int start, end;
findWordBoundary(characters, length, offset, &start, &end);
return end;
}
VisiblePosition endOfWord(const VisiblePosition &c, EWordSide side)
{
VisiblePosition p = c;
if (side == LeftWordIfOnBoundary) {
if (isStartOfParagraph(c))
return c;
p = c.previous();
if (p.isNull())
return c;
} else if (isEndOfParagraph(c))
return c;
return nextBoundary(p, endWordBoundary);
}
static unsigned previousWordPositionBoundary(const UChar* characters, unsigned length, unsigned offset, BoundarySearchContextAvailability mayHaveMoreContext, bool& needMoreContext)
{
if (mayHaveMoreContext && !startOfLastWordBoundaryContext(characters, offset)) {
needMoreContext = true;
return 0;
}
needMoreContext = false;
return findNextWordFromIndex(characters, length, offset, false);
}
VisiblePosition previousWordPosition(const VisiblePosition &c)
{
VisiblePosition prev = previousBoundary(c, previousWordPositionBoundary);
return c.honorEditingBoundaryAtOrBefore(prev);
}
static unsigned nextWordPositionBoundary(const UChar* characters, unsigned length, unsigned offset, BoundarySearchContextAvailability mayHaveMoreContext, bool& needMoreContext)
{
if (mayHaveMoreContext && endOfFirstWordBoundaryContext(characters + offset, length - offset) == static_cast<int>(length - offset)) {
needMoreContext = true;
return length;
}
needMoreContext = false;
return findNextWordFromIndex(characters, length, offset, true);
}
VisiblePosition nextWordPosition(const VisiblePosition &c)
{
VisiblePosition next = nextBoundary(c, nextWordPositionBoundary);
return c.honorEditingBoundaryAtOrAfter(next);
}
bool isStartOfWord(const VisiblePosition& p)
{
return p.isNotNull() && p == startOfWord(p, RightWordIfOnBoundary);
}
// ---------
enum LineEndpointComputationMode { UseLogicalOrdering, UseInlineBoxOrdering };
static VisiblePosition startPositionForLine(const VisiblePosition& c, LineEndpointComputationMode mode)
{
if (c.isNull())
return VisiblePosition();
RootInlineBox* rootBox = RenderedPosition(c).rootBox();
if (!rootBox) {
// There are VisiblePositions at offset 0 in blocks without
// RootInlineBoxes, like empty editable blocks and bordered blocks.
Position p = c.deepEquivalent();
if (p.deprecatedNode()->renderer() && p.deprecatedNode()->renderer()->isRenderBlock() && !p.deprecatedEditingOffset())
return c;
return VisiblePosition();
}
Node* startNode;
InlineBox* startBox;
if (mode == UseLogicalOrdering) {
startNode = rootBox->getLogicalStartBoxWithNode(startBox);
if (!startNode)
return VisiblePosition();
} else {
// Generated content (e.g. list markers and CSS :before and :after pseudoelements) have no corresponding DOM element,
// and so cannot be represented by a VisiblePosition. Use whatever follows instead.
startBox = rootBox->firstLeafChild();
while (true) {
if (!startBox)
return VisiblePosition();
RenderObject* startRenderer = startBox->renderer();
if (!startRenderer)
return VisiblePosition();
startNode = startRenderer->node();
if (startNode)
break;
startBox = startBox->nextLeafChild();
}
}
return startNode->isTextNode() ? Position(toText(startNode), toInlineTextBox(startBox)->start())
: positionBeforeNode(startNode);
}
static VisiblePosition startOfLine(const VisiblePosition& c, LineEndpointComputationMode mode)
{
// TODO: this is the current behavior that might need to be fixed.
// Please refer to https://bugs.webkit.org/show_bug.cgi?id=49107 for detail.
VisiblePosition visPos = startPositionForLine(c, mode);
if (mode == UseLogicalOrdering) {
if (Node* editableRoot = highestEditableRoot(c.deepEquivalent())) {
if (!editableRoot->contains(visPos.deepEquivalent().containerNode()))
return firstPositionInNode(editableRoot);
}
}
return c.honorEditingBoundaryAtOrBefore(visPos);
}
// FIXME: Rename this function to reflect the fact it ignores bidi levels.
VisiblePosition startOfLine(const VisiblePosition& currentPosition)
{
return startOfLine(currentPosition, UseInlineBoxOrdering);
}
VisiblePosition logicalStartOfLine(const VisiblePosition& currentPosition)
{
return startOfLine(currentPosition, UseLogicalOrdering);
}
static VisiblePosition endPositionForLine(const VisiblePosition& c, LineEndpointComputationMode mode)
{
if (c.isNull())
return VisiblePosition();
RootInlineBox* rootBox = RenderedPosition(c).rootBox();
if (!rootBox) {
// There are VisiblePositions at offset 0 in blocks without
// RootInlineBoxes, like empty editable blocks and bordered blocks.
Position p = c.deepEquivalent();
if (p.deprecatedNode()->renderer() && p.deprecatedNode()->renderer()->isRenderBlock() && !p.deprecatedEditingOffset())
return c;
return VisiblePosition();
}
Node* endNode;
InlineBox* endBox;
if (mode == UseLogicalOrdering) {
endNode = rootBox->getLogicalEndBoxWithNode(endBox);
if (!endNode)
return VisiblePosition();
} else {
// Generated content (e.g. list markers and CSS :before and :after pseudoelements) have no corresponding DOM element,
// and so cannot be represented by a VisiblePosition. Use whatever precedes instead.
endBox = rootBox->lastLeafChild();
while (true) {
if (!endBox)
return VisiblePosition();
RenderObject* endRenderer = endBox->renderer();
if (!endRenderer)
return VisiblePosition();
endNode = endRenderer->node();
if (endNode)
break;
endBox = endBox->prevLeafChild();
}
}
Position pos;
if (endNode->hasTagName(brTag))
pos = positionBeforeNode(endNode);
else if (endBox->isInlineTextBox() && endNode->isTextNode()) {
InlineTextBox* endTextBox = toInlineTextBox(endBox);
int endOffset = endTextBox->start();
if (!endTextBox->isLineBreak())
endOffset += endTextBox->len();
pos = Position(toText(endNode), endOffset);
} else
pos = positionAfterNode(endNode);
return VisiblePosition(pos, VP_UPSTREAM_IF_POSSIBLE);
}
static bool inSameLogicalLine(const VisiblePosition& a, const VisiblePosition& b)
{
return a.isNotNull() && logicalStartOfLine(a) == logicalStartOfLine(b);
}
static VisiblePosition endOfLine(const VisiblePosition& c, LineEndpointComputationMode mode)
{
// TODO: this is the current behavior that might need to be fixed.
// Please refer to https://bugs.webkit.org/show_bug.cgi?id=49107 for detail.
VisiblePosition visPos = endPositionForLine(c, mode);
if (mode == UseLogicalOrdering) {
// Make sure the end of line is at the same line as the given input position. For a wrapping line, the logical end
// position for the not-last-2-lines might incorrectly hand back the logical beginning of the next line.
// For example, <div contenteditable dir="rtl" style="line-break:before-white-space">abcdefg abcdefg abcdefg
// a abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg </div>
// In this case, use the previous position of the computed logical end position.
if (!inSameLogicalLine(c, visPos))
visPos = visPos.previous();
if (Node* editableRoot = highestEditableRoot(c.deepEquivalent())) {
if (!editableRoot->contains(visPos.deepEquivalent().containerNode()))
return lastPositionInNode(editableRoot);
}
return c.honorEditingBoundaryAtOrAfter(visPos);
}
// Make sure the end of line is at the same line as the given input position. Else use the previous position to
// obtain end of line. This condition happens when the input position is before the space character at the end
// of a soft-wrapped non-editable line. In this scenario, endPositionForLine would incorrectly hand back a position
// in the next line instead. This fix is to account for the discrepancy between lines with webkit-line-break:after-white-space style
// versus lines without that style, which would break before a space by default.
if (!inSameLine(c, visPos)) {
visPos = c.previous();
if (visPos.isNull())
return VisiblePosition();
visPos = endPositionForLine(visPos, UseInlineBoxOrdering);
}
return c.honorEditingBoundaryAtOrAfter(visPos);
}
// FIXME: Rename this function to reflect the fact it ignores bidi levels.
VisiblePosition endOfLine(const VisiblePosition& currentPosition)
{
return endOfLine(currentPosition, UseInlineBoxOrdering);
}
VisiblePosition logicalEndOfLine(const VisiblePosition& currentPosition)
{
return endOfLine(currentPosition, UseLogicalOrdering);
}
bool inSameLine(const VisiblePosition &a, const VisiblePosition &b)
{
return a.isNotNull() && startOfLine(a) == startOfLine(b);
}
bool isStartOfLine(const VisiblePosition &p)
{
return p.isNotNull() && p == startOfLine(p);
}
bool isEndOfLine(const VisiblePosition &p)
{
return p.isNotNull() && p == endOfLine(p);
}
static inline IntPoint absoluteLineDirectionPointToLocalPointInBlock(RootInlineBox* root, int lineDirectionPoint)
{
ASSERT(root);
RenderBlock* containingBlock = root->block();
FloatPoint absoluteBlockPoint = containingBlock->localToAbsolute(FloatPoint());
if (containingBlock->hasOverflowClip())
absoluteBlockPoint -= containingBlock->scrolledContentOffset();
if (root->block()->isHorizontalWritingMode())
return IntPoint(lineDirectionPoint - absoluteBlockPoint.x(), root->blockDirectionPointInLine());
return IntPoint(root->blockDirectionPointInLine(), lineDirectionPoint - absoluteBlockPoint.y());
}
VisiblePosition previousLinePosition(const VisiblePosition &visiblePosition, int lineDirectionPoint, EditableType editableType)
{
Position p = visiblePosition.deepEquivalent();
Node* node = p.deprecatedNode();
if (!node)
return VisiblePosition();
node->document()->updateLayoutIgnorePendingStylesheets();
RenderObject *renderer = node->renderer();
if (!renderer)
return VisiblePosition();
RootInlineBox *root = 0;
InlineBox* box;
int ignoredCaretOffset;
visiblePosition.getInlineBoxAndOffset(box, ignoredCaretOffset);
if (box) {
root = box->root()->prevRootBox();
// We want to skip zero height boxes.
// This could happen in case it is a TrailingFloatsRootInlineBox.
if (!root || !root->logicalHeight() || !root->firstLeafChild())
root = 0;
}
if (!root) {
Position position = previousRootInlineBoxCandidatePosition(node, visiblePosition, editableType);
if (position.isNotNull()) {
RenderedPosition renderedPosition(position);
root = renderedPosition.rootBox();
if (!root)
return position;
}
}
if (root) {
// FIXME: Can be wrong for multi-column layout and with transforms.
IntPoint pointInLine = absoluteLineDirectionPointToLocalPointInBlock(root, lineDirectionPoint);
RenderObject* renderer = root->closestLeafChildForPoint(pointInLine, isEditablePosition(p))->renderer();
Node* node = renderer->node();
if (node && editingIgnoresContent(node))
return positionInParentBeforeNode(node);
return renderer->positionForPoint(pointInLine);
}
// Could not find a previous line. This means we must already be on the first line.
// Move to the start of the content in this block, which effectively moves us
// to the start of the line we're on.
Element* rootElement = node->rendererIsEditable(editableType) ? node->rootEditableElement(editableType) : node->document()->documentElement();
if (!rootElement)
return VisiblePosition();
return VisiblePosition(firstPositionInNode(rootElement), DOWNSTREAM);
}
VisiblePosition nextLinePosition(const VisiblePosition &visiblePosition, int lineDirectionPoint, EditableType editableType)
{
Position p = visiblePosition.deepEquivalent();
Node* node = p.deprecatedNode();
if (!node)
return VisiblePosition();
node->document()->updateLayoutIgnorePendingStylesheets();
RenderObject *renderer = node->renderer();
if (!renderer)
return VisiblePosition();
RootInlineBox *root = 0;
InlineBox* box;
int ignoredCaretOffset;
visiblePosition.getInlineBoxAndOffset(box, ignoredCaretOffset);
if (box) {
root = box->root()->nextRootBox();
// We want to skip zero height boxes.
// This could happen in case it is a TrailingFloatsRootInlineBox.