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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
|
/*
* Copyright (C) 2004, 2005, 2006, 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 "Position.h"
#include "CSSComputedStyleDeclaration.h"
#include "Logging.h"
#include "PositionIterator.h"
#include "RenderBlock.h"
#include "Text.h"
#include "TextIterator.h"
#include "VisiblePosition.h"
#include "htmlediting.h"
#include "visible_units.h"
#include <stdio.h>
#include <wtf/text/CString.h>
#include <wtf/unicode/CharacterNames.h>
namespace WebCore {
using namespace HTMLNames;
static Node* nextRenderedEditable(Node* node)
{
while ((node = node->nextLeafNode())) {
if (!node->isContentEditable())
continue;
RenderObject* renderer = node->renderer();
if (!renderer)
continue;
if ((renderer->isBox() && toRenderBox(renderer)->inlineBoxWrapper()) || (renderer->isText() && toRenderText(renderer)->firstTextBox()))
return node;
}
return 0;
}
static Node* previousRenderedEditable(Node* node)
{
while ((node = node->previousLeafNode())) {
if (!node->isContentEditable())
continue;
RenderObject* renderer = node->renderer();
if (!renderer)
continue;
if ((renderer->isBox() && toRenderBox(renderer)->inlineBoxWrapper()) || (renderer->isText() && toRenderText(renderer)->firstTextBox()))
return node;
}
return 0;
}
Position::Position(PassRefPtr<Node> anchorNode, int offset)
: m_anchorNode(anchorNode)
, m_offset(offset)
, m_anchorType(anchorTypeForLegacyEditingPosition(m_anchorNode.get(), m_offset))
, m_isLegacyEditingPosition(true)
{
}
Position::Position(PassRefPtr<Node> anchorNode, AnchorType anchorType)
: m_anchorNode(anchorNode)
, m_offset(0)
, m_anchorType(anchorType)
, m_isLegacyEditingPosition(false)
{
ASSERT(anchorType != PositionIsOffsetInAnchor);
}
Position::Position(PassRefPtr<Node> anchorNode, int offset, AnchorType anchorType)
: m_anchorNode(anchorNode)
, m_offset(offset)
, m_anchorType(anchorType)
, m_isLegacyEditingPosition(false)
{
ASSERT(anchorType == PositionIsOffsetInAnchor);
}
void Position::moveToPosition(PassRefPtr<Node> node, int offset)
{
ASSERT(anchorType() == PositionIsOffsetInAnchor || m_isLegacyEditingPosition);
m_anchorNode = node;
m_offset = offset;
if (m_isLegacyEditingPosition)
m_anchorType = anchorTypeForLegacyEditingPosition(m_anchorNode.get(), m_offset);
}
void Position::moveToOffset(int offset)
{
ASSERT(anchorType() == PositionIsOffsetInAnchor || m_isLegacyEditingPosition);
m_offset = offset;
if (m_isLegacyEditingPosition)
m_anchorType = anchorTypeForLegacyEditingPosition(m_anchorNode.get(), m_offset);
}
Node* Position::containerNode() const
{
if (!m_anchorNode)
return 0;
switch (anchorType()) {
case PositionIsOffsetInAnchor:
return m_anchorNode.get();
case PositionIsBeforeAnchor:
case PositionIsAfterAnchor:
return m_anchorNode->parentNode();
}
ASSERT_NOT_REACHED();
return 0;
}
int Position::computeOffsetInContainerNode() const
{
if (!m_anchorNode)
return 0;
switch (anchorType()) {
case PositionIsOffsetInAnchor:
return std::min(lastOffsetInNode(m_anchorNode.get()), m_offset);
case PositionIsBeforeAnchor:
return m_anchorNode->nodeIndex();
case PositionIsAfterAnchor:
return m_anchorNode->nodeIndex() + 1;
}
ASSERT_NOT_REACHED();
return 0;
}
int Position::offsetForPositionAfterAnchor() const
{
ASSERT(m_anchorType == PositionIsAfterAnchor);
ASSERT(!m_isLegacyEditingPosition);
return lastOffsetForEditing(m_anchorNode.get());
}
// Neighbor-anchored positions are invalid DOM positions, so they need to be
// fixed up before handing them off to the Range object.
Position Position::parentAnchoredEquivalent() const
{
if (!m_anchorNode)
return Position();
// FIXME: This should only be necessary for legacy positions, but is also needed for positions before and after Tables
if (m_offset <= 0) {
if (m_anchorNode->parentNode() && (editingIgnoresContent(m_anchorNode.get()) || isTableElement(m_anchorNode.get())))
return positionInParentBeforeNode(m_anchorNode.get());
return Position(m_anchorNode, 0, PositionIsOffsetInAnchor);
}
if (!m_anchorNode->offsetInCharacters() && static_cast<unsigned>(m_offset) == m_anchorNode->childNodeCount()
&& (editingIgnoresContent(m_anchorNode.get()) || isTableElement(m_anchorNode.get()))) {
return positionInParentAfterNode(m_anchorNode.get());
}
return Position(containerNode(), computeOffsetInContainerNode(), PositionIsOffsetInAnchor);
}
Node* Position::computeNodeBeforePosition() const
{
if (!m_anchorNode)
return 0;
switch (anchorType()) {
case PositionIsOffsetInAnchor:
return m_anchorNode->childNode(m_offset - 1); // -1 converts to childNode((unsigned)-1) and returns null.
case PositionIsBeforeAnchor:
return m_anchorNode->previousSibling();
case PositionIsAfterAnchor:
return m_anchorNode.get();
}
ASSERT_NOT_REACHED();
return 0;
}
Node* Position::computeNodeAfterPosition() const
{
if (!m_anchorNode)
return 0;
switch (anchorType()) {
case PositionIsOffsetInAnchor:
return m_anchorNode->childNode(m_offset);
case PositionIsBeforeAnchor:
return m_anchorNode.get();
case PositionIsAfterAnchor:
return m_anchorNode->nextSibling();
}
ASSERT_NOT_REACHED();
return 0;
}
Position::AnchorType Position::anchorTypeForLegacyEditingPosition(Node* anchorNode, int offset)
{
if (anchorNode && editingIgnoresContent(anchorNode)) {
if (offset == 0)
return Position::PositionIsBeforeAnchor;
return Position::PositionIsAfterAnchor;
}
return Position::PositionIsOffsetInAnchor;
}
// FIXME: This method is confusing (does it return anchorNode() or containerNode()?) and should be renamed or removed
Element* Position::element() const
{
Node* n = anchorNode();
while (n && !n->isElementNode())
n = n->parentNode();
return static_cast<Element*>(n);
}
PassRefPtr<CSSComputedStyleDeclaration> Position::computedStyle() const
{
Element* elem = element();
if (!elem)
return 0;
return WebCore::computedStyle(elem);
}
Position Position::previous(PositionMoveType moveType) const
{
Node* n = deprecatedNode();
if (!n)
return *this;
int o = m_offset;
// FIXME: Negative offsets shouldn't be allowed. We should catch this earlier.
ASSERT(o >= 0);
if (o > 0) {
Node* child = n->childNode(o - 1);
if (child)
return lastDeepEditingPositionForNode(child);
// There are two reasons child might be 0:
// 1) The node is node like a text node that is not an element, and therefore has no children.
// Going backward one character at a time is correct.
// 2) The old offset was a bogus offset like (<br>, 1), and there is no child.
// Going from 1 to 0 is correct.
switch (moveType) {
case CodePoint:
return Position(n, o - 1);
case Character:
return Position(n, uncheckedPreviousOffset(n, o));
case BackwardDeletion:
return Position(n, uncheckedPreviousOffsetForBackwardDeletion(n, o));
}
}
ContainerNode* parent = n->parentNode();
if (!parent)
return *this;
return Position(parent, n->nodeIndex());
}
Position Position::next(PositionMoveType moveType) const
{
ASSERT(moveType != BackwardDeletion);
Node* n = deprecatedNode();
if (!n)
return *this;
int o = m_offset;
// FIXME: Negative offsets shouldn't be allowed. We should catch this earlier.
ASSERT(o >= 0);
Node* child = n->childNode(o);
if (child || (!n->hasChildNodes() && o < lastOffsetForEditing(n))) {
if (child)
return firstDeepEditingPositionForNode(child);
// There are two reasons child might be 0:
// 1) The node is node like a text node that is not an element, and therefore has no children.
// Going forward one character at a time is correct.
// 2) The new offset is a bogus offset like (<br>, 1), and there is no child.
// Going from 0 to 1 is correct.
return Position(n, (moveType == Character) ? uncheckedNextOffset(n, o) : o + 1);
}
ContainerNode* parent = n->parentNode();
if (!parent)
return *this;
return Position(parent, n->nodeIndex() + 1);
}
int Position::uncheckedPreviousOffset(const Node* n, int current)
{
return n->renderer() ? n->renderer()->previousOffset(current) : current - 1;
}
int Position::uncheckedPreviousOffsetForBackwardDeletion(const Node* n, int current)
{
return n->renderer() ? n->renderer()->previousOffsetForBackwardDeletion(current) : current - 1;
}
int Position::uncheckedNextOffset(const Node* n, int current)
{
return n->renderer() ? n->renderer()->nextOffset(current) : current + 1;
}
bool Position::atFirstEditingPositionForNode() const
{
if (isNull())
return true;
return m_offset <= 0;
}
bool Position::atLastEditingPositionForNode() const
{
if (isNull())
return true;
return m_offset >= lastOffsetForEditing(deprecatedNode());
}
// A position is considered at editing boundary if one of the following is true:
// 1. It is the first position in the node and the next visually equivalent position
// is non editable.
// 2. It is the last position in the node and the previous visually equivalent position
// is non editable.
// 3. It is an editable position and both the next and previous visually equivalent
// positions are both non editable.
bool Position::atEditingBoundary() const
{
Position nextPosition = downstream(CanCrossEditingBoundary);
if (atFirstEditingPositionForNode() && nextPosition.isNotNull() && !nextPosition.deprecatedNode()->isContentEditable())
return true;
Position prevPosition = upstream(CanCrossEditingBoundary);
if (atLastEditingPositionForNode() && prevPosition.isNotNull() && !prevPosition.deprecatedNode()->isContentEditable())
return true;
return nextPosition.isNotNull() && !nextPosition.deprecatedNode()->isContentEditable()
&& prevPosition.isNotNull() && !prevPosition.deprecatedNode()->isContentEditable();
}
Node* Position::parentEditingBoundary() const
{
if (!m_anchorNode || !m_anchorNode->document())
return 0;
Node* documentElement = m_anchorNode->document()->documentElement();
if (!documentElement)
return 0;
Node* boundary = m_anchorNode.get();
while (boundary != documentElement && boundary->parentNode() && m_anchorNode->isContentEditable() == boundary->parentNode()->isContentEditable())
boundary = boundary->parentNode();
return boundary;
}
bool Position::atStartOfTree() const
{
if (isNull())
return true;
return !deprecatedNode()->parentNode() && m_offset <= 0;
}
bool Position::atEndOfTree() const
{
if (isNull())
return true;
return !deprecatedNode()->parentNode() && m_offset >= lastOffsetForEditing(deprecatedNode());
}
int Position::renderedOffset() const
{
if (!deprecatedNode()->isTextNode())
return m_offset;
if (!deprecatedNode()->renderer())
return m_offset;
int result = 0;
RenderText* textRenderer = toRenderText(deprecatedNode()->renderer());
for (InlineTextBox *box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
int start = box->start();
int end = box->start() + box->len();
if (m_offset < start)
return result;
if (m_offset <= end) {
result += m_offset - start;
return result;
}
result += box->len();
}
return result;
}
// return first preceding DOM position rendered at a different location, or "this"
Position Position::previousCharacterPosition(EAffinity affinity) const
{
if (isNull())
return Position();
Node* fromRootEditableElement = deprecatedNode()->rootEditableElement();
bool atStartOfLine = isStartOfLine(VisiblePosition(*this, affinity));
bool rendered = isCandidate();
Position currentPos = *this;
while (!currentPos.atStartOfTree()) {
currentPos = currentPos.previous();
if (currentPos.deprecatedNode()->rootEditableElement() != fromRootEditableElement)
return *this;
if (atStartOfLine || !rendered) {
if (currentPos.isCandidate())
return currentPos;
} else if (rendersInDifferentPosition(currentPos))
return currentPos;
}
return *this;
}
// return first following position rendered at a different location, or "this"
Position Position::nextCharacterPosition(EAffinity affinity) const
{
if (isNull())
return Position();
Node* fromRootEditableElement = deprecatedNode()->rootEditableElement();
bool atEndOfLine = isEndOfLine(VisiblePosition(*this, affinity));
bool rendered = isCandidate();
Position currentPos = *this;
while (!currentPos.atEndOfTree()) {
currentPos = currentPos.next();
if (currentPos.deprecatedNode()->rootEditableElement() != fromRootEditableElement)
return *this;
if (atEndOfLine || !rendered) {
if (currentPos.isCandidate())
return currentPos;
} else if (rendersInDifferentPosition(currentPos))
return currentPos;
}
return *this;
}
// Whether or not [node, 0] and [node, lastOffsetForEditing(node)] are their own VisiblePositions.
// If true, adjacent candidates are visually distinct.
// FIXME: Disregard nodes with renderers that have no height, as we do in isCandidate.
// FIXME: Share code with isCandidate, if possible.
static bool endsOfNodeAreVisuallyDistinctPositions(Node* node)
{
if (!node || !node->renderer())
return false;
if (!node->renderer()->isInline())
return true;
// Don't include inline tables.
if (node->hasTagName(tableTag))
return false;
// There is a VisiblePosition inside an empty inline-block container.
return node->renderer()->isReplaced() && canHaveChildrenForEditing(node) && toRenderBox(node->renderer())->height() != 0 && !node->firstChild();
}
static Node* enclosingVisualBoundary(Node* node)
{
while (node && !endsOfNodeAreVisuallyDistinctPositions(node))
node = node->parentNode();
return node;
}
// upstream() and downstream() want to return positions that are either in a
// text node or at just before a non-text node. This method checks for that.
static bool isStreamer(const PositionIterator& pos)
{
if (!pos.node())
return true;
if (isAtomicNode(pos.node()))
return true;
return pos.atStartOfNode();
}
// This function and downstream() are used for moving back and forth between visually equivalent candidates.
// For example, for the text node "foo bar" where whitespace is collapsible, there are two candidates
// that map to the VisiblePosition between 'b' and the space. This function will return the left candidate
// and downstream() will return the right one.
// Also, upstream() will return [boundary, 0] for any of the positions from [boundary, 0] to the first candidate
// in boundary, where endsOfNodeAreVisuallyDistinctPositions(boundary) is true.
Position Position::upstream(EditingBoundaryCrossingRule rule) const
{
Node* startNode = deprecatedNode();
if (!startNode)
return Position();
// iterate backward from there, looking for a qualified position
Node* boundary = enclosingVisualBoundary(startNode);
// FIXME: PositionIterator should respect Before and After positions.
PositionIterator lastVisible = m_anchorType == PositionIsAfterAnchor ? Position(m_anchorNode, caretMaxOffset(m_anchorNode.get())) : *this;
PositionIterator currentPos = lastVisible;
bool startEditable = startNode->isContentEditable();
Node* lastNode = startNode;
bool boundaryCrossed = false;
for (; !currentPos.atStart(); currentPos.decrement()) {
Node* currentNode = currentPos.node();
// Don't check for an editability change if we haven't moved to a different node,
// to avoid the expense of computing isContentEditable().
if (currentNode != lastNode) {
// Don't change editability.
bool currentEditable = currentNode->isContentEditable();
if (startEditable != currentEditable) {
if (rule == CannotCrossEditingBoundary)
break;
boundaryCrossed = true;
}
lastNode = currentNode;
}
// If we've moved to a position that is visually distinct, return the last saved position. There
// is code below that terminates early if we're *about* to move to a visually distinct position.
if (endsOfNodeAreVisuallyDistinctPositions(currentNode) && currentNode != boundary)
return lastVisible;
// skip position in unrendered or invisible node
RenderObject* renderer = currentNode->renderer();
if (!renderer || renderer->style()->visibility() != VISIBLE)
continue;
if (rule == CanCrossEditingBoundary && boundaryCrossed) {
lastVisible = currentPos;
break;
}
// track last visible streamer position
if (isStreamer(currentPos))
lastVisible = currentPos;
// Don't move past a position that is visually distinct. We could rely on code above to terminate and
// return lastVisible on the next iteration, but we terminate early to avoid doing a nodeIndex() call.
if (endsOfNodeAreVisuallyDistinctPositions(currentNode) && currentPos.atStartOfNode())
return lastVisible;
// Return position after tables and nodes which have content that can be ignored.
if (editingIgnoresContent(currentNode) || isTableElement(currentNode)) {
if (currentPos.atEndOfNode())
return lastDeepEditingPositionForNode(currentNode);
continue;
}
// return current position if it is in rendered text
if (renderer->isText() && toRenderText(renderer)->firstTextBox()) {
if (currentNode != startNode) {
// This assertion fires in layout tests in the case-transform.html test because
// of a mix-up between offsets in the text in the DOM tree with text in the
// render tree which can have a different length due to case transformation.
// Until we resolve that, disable this so we can run the layout tests!
//ASSERT(currentOffset >= renderer->caretMaxOffset());
return Position(currentNode, renderer->caretMaxOffset());
}
unsigned textOffset = currentPos.offsetInLeafNode();
RenderText* textRenderer = toRenderText(renderer);
InlineTextBox* lastTextBox = textRenderer->lastTextBox();
for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
if (textOffset <= box->start() + box->len()) {
if (textOffset > box->start())
return currentPos;
continue;
}
if (box == lastTextBox || textOffset != box->start() + box->len() + 1)
continue;
// The text continues on the next line only if the last text box is not on this line and
// none of the boxes on this line have a larger start offset.
bool continuesOnNextLine = true;
InlineBox* otherBox = box;
while (continuesOnNextLine) {
otherBox = otherBox->nextLeafChild();
if (!otherBox)
break;
if (otherBox == lastTextBox || (otherBox->renderer() == textRenderer && static_cast<InlineTextBox*>(otherBox)->start() > textOffset))
continuesOnNextLine = false;
}
otherBox = box;
while (continuesOnNextLine) {
otherBox = otherBox->prevLeafChild();
if (!otherBox)
break;
if (otherBox == lastTextBox || (otherBox->renderer() == textRenderer && static_cast<InlineTextBox*>(otherBox)->start() > textOffset))
continuesOnNextLine = false;
}
if (continuesOnNextLine)
return currentPos;
}
}
}
return lastVisible;
}
// This function and upstream() are used for moving back and forth between visually equivalent candidates.
// For example, for the text node "foo bar" where whitespace is collapsible, there are two candidates
// that map to the VisiblePosition between 'b' and the space. This function will return the right candidate
// and upstream() will return the left one.
// Also, downstream() will return the last position in the last atomic node in boundary for all of the positions
// in boundary after the last candidate, where endsOfNodeAreVisuallyDistinctPositions(boundary).
Position Position::downstream(EditingBoundaryCrossingRule rule) const
{
Node* startNode = deprecatedNode();
if (!startNode)
return Position();
// iterate forward from there, looking for a qualified position
Node* boundary = enclosingVisualBoundary(startNode);
// FIXME: PositionIterator should respect Before and After positions.
PositionIterator lastVisible = m_anchorType == PositionIsAfterAnchor ? Position(m_anchorNode, caretMaxOffset(m_anchorNode.get())) : *this;
PositionIterator currentPos = lastVisible;
bool startEditable = startNode->isContentEditable();
Node* lastNode = startNode;
bool boundaryCrossed = false;
for (; !currentPos.atEnd(); currentPos.increment()) {
Node* currentNode = currentPos.node();
// Don't check for an editability change if we haven't moved to a different node,
// to avoid the expense of computing isContentEditable().
if (currentNode != lastNode) {
// Don't change editability.
bool currentEditable = currentNode->isContentEditable();
if (startEditable != currentEditable) {
if (rule == CannotCrossEditingBoundary)
break;
boundaryCrossed = true;
}
lastNode = currentNode;
}
// stop before going above the body, up into the head
// return the last visible streamer position
if (currentNode->hasTagName(bodyTag) && currentPos.atEndOfNode())
break;
// Do not move to a visually distinct position.
if (endsOfNodeAreVisuallyDistinctPositions(currentNode) && currentNode != boundary)
return lastVisible;
// Do not move past a visually disinct position.
// Note: The first position after the last in a node whose ends are visually distinct
// positions will be [boundary->parentNode(), originalBlock->nodeIndex() + 1].
if (boundary && boundary->parentNode() == currentNode)
return lastVisible;
// skip position in unrendered or invisible node
RenderObject* renderer = currentNode->renderer();
if (!renderer || renderer->style()->visibility() != VISIBLE)
continue;
if (rule == CanCrossEditingBoundary && boundaryCrossed) {
lastVisible = currentPos;
break;
}
// track last visible streamer position
if (isStreamer(currentPos))
lastVisible = currentPos;
// Return position before tables and nodes which have content that can be ignored.
if (editingIgnoresContent(currentNode) || isTableElement(currentNode)) {
if (currentPos.offsetInLeafNode() <= renderer->caretMinOffset())
return Position(currentNode, renderer->caretMinOffset());
continue;
}
// return current position if it is in rendered text
if (renderer->isText() && toRenderText(renderer)->firstTextBox()) {
if (currentNode != startNode) {
ASSERT(currentPos.atStartOfNode());
return Position(currentNode, renderer->caretMinOffset());
}
unsigned textOffset = currentPos.offsetInLeafNode();
RenderText* textRenderer = toRenderText(renderer);
InlineTextBox* lastTextBox = textRenderer->lastTextBox();
for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
if (textOffset <= box->end()) {
if (textOffset >= box->start())
return currentPos;
continue;
}
if (box == lastTextBox || textOffset != box->start() + box->len())
continue;
// The text continues on the next line only if the last text box is not on this line and
// none of the boxes on this line have a larger start offset.
bool continuesOnNextLine = true;
InlineBox* otherBox = box;
while (continuesOnNextLine) {
otherBox = otherBox->nextLeafChild();
if (!otherBox)
break;
if (otherBox == lastTextBox || (otherBox->renderer() == textRenderer && static_cast<InlineTextBox*>(otherBox)->start() >= textOffset))
continuesOnNextLine = false;
}
otherBox = box;
while (continuesOnNextLine) {
otherBox = otherBox->prevLeafChild();
if (!otherBox)
break;
if (otherBox == lastTextBox || (otherBox->renderer() == textRenderer && static_cast<InlineTextBox*>(otherBox)->start() >= textOffset))
continuesOnNextLine = false;
}
if (continuesOnNextLine)
return currentPos;
}
}
}
return lastVisible;
}
bool Position::hasRenderedNonAnonymousDescendantsWithHeight(RenderObject* renderer)
{
RenderObject* stop = renderer->nextInPreOrderAfterChildren();
for (RenderObject *o = renderer->firstChild(); o && o != stop; o = o->nextInPreOrder())
if (o->node()) {
if ((o->isText() && toRenderText(o)->linesBoundingBox().height()) ||
(o->isBox() && toRenderBox(o)->borderBoundingBox().height()))
return true;
}
return false;
}
bool Position::nodeIsUserSelectNone(Node* node)
{
return node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_NONE;
}
bool Position::isCandidate() const
{
if (isNull())
return false;
RenderObject* renderer = deprecatedNode()->renderer();
if (!renderer)
return false;
if (renderer->style()->visibility() != VISIBLE)
return false;
if (renderer->isBR())
return !m_offset && !nodeIsUserSelectNone(deprecatedNode()->parentNode());
if (renderer->isText())
return !nodeIsUserSelectNone(deprecatedNode()) && inRenderedText();
if (isTableElement(deprecatedNode()) || editingIgnoresContent(deprecatedNode()))
return (atFirstEditingPositionForNode() || atLastEditingPositionForNode()) && !nodeIsUserSelectNone(deprecatedNode()->parentNode());
if (m_anchorNode->hasTagName(htmlTag))
return false;
if (renderer->isBlockFlow()) {
if (toRenderBlock(renderer)->height() || m_anchorNode->hasTagName(bodyTag)) {
if (!Position::hasRenderedNonAnonymousDescendantsWithHeight(renderer))
return atFirstEditingPositionForNode() && !Position::nodeIsUserSelectNone(deprecatedNode());
return m_anchorNode->isContentEditable() && !Position::nodeIsUserSelectNone(deprecatedNode()) && atEditingBoundary();
}
} else
return m_anchorNode->isContentEditable() && !Position::nodeIsUserSelectNone(deprecatedNode()) && atEditingBoundary();
return false;
}
bool Position::inRenderedText() const
{
if (isNull() || !deprecatedNode()->isTextNode())
return false;
RenderObject* renderer = deprecatedNode()->renderer();
if (!renderer)
return false;
RenderText *textRenderer = toRenderText(renderer);
for (InlineTextBox *box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
if (m_offset < static_cast<int>(box->start()) && !textRenderer->containsReversedText()) {
// The offset we're looking for is before this node
// this means the offset must be in content that is
// not rendered. Return false.
return false;
}
if (box->containsCaretOffset(m_offset))
// Return false for offsets inside composed characters.
return m_offset == 0 || m_offset == textRenderer->nextOffset(textRenderer->previousOffset(m_offset));
}
return false;
}
static unsigned caretMaxRenderedOffset(const Node* n)
{
RenderObject* r = n->renderer();
if (r)
return r->caretMaxRenderedOffset();
if (n->isCharacterDataNode())
return static_cast<const CharacterData*>(n)->length();
return 1;
}
bool Position::isRenderedCharacter() const
{
if (isNull() || !deprecatedNode()->isTextNode())
return false;
RenderObject* renderer = deprecatedNode()->renderer();
if (!renderer)
return false;
RenderText* textRenderer = toRenderText(renderer);
for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
if (m_offset < static_cast<int>(box->start()) && !textRenderer->containsReversedText()) {
// The offset we're looking for is before this node
// this means the offset must be in content that is
// not rendered. Return false.
return false;
}
if (m_offset >= static_cast<int>(box->start()) && m_offset < static_cast<int>(box->start() + box->len()))
return true;
}
return false;
}
bool Position::rendersInDifferentPosition(const Position &pos) const
{
if (isNull() || pos.isNull())
return false;
RenderObject* renderer = deprecatedNode()->renderer();
if (!renderer)
return false;
RenderObject* posRenderer = pos.deprecatedNode()->renderer();
if (!posRenderer)
return false;
if (renderer->style()->visibility() != VISIBLE ||
posRenderer->style()->visibility() != VISIBLE)
return false;
if (deprecatedNode() == pos.deprecatedNode()) {
if (deprecatedNode()->hasTagName(brTag))
return false;
if (m_offset == pos.deprecatedEditingOffset())
return false;
if (!deprecatedNode()->isTextNode() && !pos.deprecatedNode()->isTextNode()) {
if (m_offset != pos.deprecatedEditingOffset())
return true;
}
}
if (deprecatedNode()->hasTagName(brTag) && pos.isCandidate())
return true;
if (pos.deprecatedNode()->hasTagName(brTag) && isCandidate())
return true;
if (deprecatedNode()->enclosingBlockFlowElement() != pos.deprecatedNode()->enclosingBlockFlowElement())
return true;
if (deprecatedNode()->isTextNode() && !inRenderedText())
return false;
if (pos.deprecatedNode()->isTextNode() && !pos.inRenderedText())
return false;
int thisRenderedOffset = renderedOffset();
int posRenderedOffset = pos.renderedOffset();
if (renderer == posRenderer && thisRenderedOffset == posRenderedOffset)
return false;
int ignoredCaretOffset;
InlineBox* b1;
getInlineBoxAndOffset(DOWNSTREAM, b1, ignoredCaretOffset);
InlineBox* b2;
pos.getInlineBoxAndOffset(DOWNSTREAM, b2, ignoredCaretOffset);
LOG(Editing, "renderer: %p [%p]\n", renderer, b1);
LOG(Editing, "thisRenderedOffset: %d\n", thisRenderedOffset);
LOG(Editing, "posRenderer: %p [%p]\n", posRenderer, b2);
LOG(Editing, "posRenderedOffset: %d\n", posRenderedOffset);
LOG(Editing, "node min/max: %d:%d\n", caretMinOffset(deprecatedNode()), caretMaxRenderedOffset(deprecatedNode()));
LOG(Editing, "pos node min/max: %d:%d\n", caretMinOffset(pos.deprecatedNode()), caretMaxRenderedOffset(pos.deprecatedNode()));
LOG(Editing, "----------------------------------------------------------------------\n");
if (!b1 || !b2) {
return false;
}
if (b1->root() != b2->root()) {
return true;
}
if (nextRenderedEditable(deprecatedNode()) == pos.deprecatedNode()
&& thisRenderedOffset == (int)caretMaxRenderedOffset(deprecatedNode()) && !posRenderedOffset) {
return false;
}
if (previousRenderedEditable(deprecatedNode()) == pos.deprecatedNode()
&& !thisRenderedOffset && posRenderedOffset == (int)caretMaxRenderedOffset(pos.deprecatedNode())) {
return false;
}
return true;
}
// This assumes that it starts in editable content.
Position Position::leadingWhitespacePosition(EAffinity affinity, bool considerNonCollapsibleWhitespace) const
{
ASSERT(isEditablePosition(*this));
if (isNull())
return Position();
if (upstream().deprecatedNode()->hasTagName(brTag))
return Position();
Position prev = previousCharacterPosition(affinity);
if (prev != *this && prev.deprecatedNode()->inSameContainingBlockFlowElement(deprecatedNode()) && prev.deprecatedNode()->isTextNode()) {
String string = static_cast<Text *>(prev.deprecatedNode())->data();
UChar c = string[prev.deprecatedEditingOffset()];
if (considerNonCollapsibleWhitespace ? (isSpaceOrNewline(c) || c == noBreakSpace) : isCollapsibleWhitespace(c))
if (isEditablePosition(prev))
return prev;
}
return Position();
}
// This assumes that it starts in editable content.
Position Position::trailingWhitespacePosition(EAffinity, bool considerNonCollapsibleWhitespace) const
{
ASSERT(isEditablePosition(*this));
if (isNull())
return Position();
VisiblePosition v(*this);
UChar c = v.characterAfter();
// The space must not be in another paragraph and it must be editable.
if (!isEndOfParagraph(v) && v.next(true).isNotNull())
if (considerNonCollapsibleWhitespace ? (isSpaceOrNewline(c) || c == noBreakSpace) : isCollapsibleWhitespace(c))
return *this;
return Position();
}
void Position::getInlineBoxAndOffset(EAffinity affinity, InlineBox*& inlineBox, int& caretOffset) const
{
getInlineBoxAndOffset(affinity, primaryDirection(), inlineBox, caretOffset);
}
static bool isNonTextLeafChild(RenderObject* object)
{
if (object->firstChild())
return false;
if (object->isText())
return false;
return true;
}
static InlineTextBox* searchAheadForBetterMatch(RenderObject* renderer)
{
RenderBlock* container = renderer->containingBlock();
RenderObject* next = renderer;
while ((next = next->nextInPreOrder(container))) {
if (next->isRenderBlock())
return 0;
if (next->isBR())
return 0;
if (isNonTextLeafChild(next))
return 0;
if (next->isText()) {
InlineTextBox* match = 0;
int minOffset = INT_MAX;
for (InlineTextBox* box = toRenderText(next)->firstTextBox(); box; box = box->nextTextBox()) {
int caretMinOffset = box->caretMinOffset();
if (caretMinOffset < minOffset) {
match = box;
minOffset = caretMinOffset;
}
}
if (match)
return match;
}
}
return 0;
}
static Position downstreamIgnoringEditingBoundaries(Position position)
{
Position lastPosition;
while (position != lastPosition) {
lastPosition = position;
position = position.downstream(CanCrossEditingBoundary);
}
return position;
}
static Position upstreamIgnoringEditingBoundaries(Position position)
{
Position lastPosition;
while (position != lastPosition) {
lastPosition = position;
position = position.upstream(CanCrossEditingBoundary);
}
return position;
}
void Position::getInlineBoxAndOffset(EAffinity affinity, TextDirection primaryDirection, InlineBox*& inlineBox, int& caretOffset) const
{
caretOffset = m_offset;
RenderObject* renderer = deprecatedNode()->renderer();
if (!renderer->isText()) {
inlineBox = 0;
if (canHaveChildrenForEditing(deprecatedNode()) && renderer->isBlockFlow() && hasRenderedNonAnonymousDescendantsWithHeight(renderer)) {
// Try a visually equivalent position with possibly opposite editability. This helps in case |this| is in
// an editable block but surrounded by non-editable positions. It acts to negate the logic at the beginning
// of RenderObject::createVisiblePosition().
Position equivalent = downstreamIgnoringEditingBoundaries(*this);
if (equivalent == *this) {
equivalent = upstreamIgnoringEditingBoundaries(*this);
if (equivalent == *this || downstreamIgnoringEditingBoundaries(equivalent) == *this)
return;
}
equivalent.getInlineBoxAndOffset(UPSTREAM, primaryDirection, inlineBox, caretOffset);
return;
}
if (renderer->isBox()) {
inlineBox = toRenderBox(renderer)->inlineBoxWrapper();
if (!inlineBox || (caretOffset > inlineBox->caretMinOffset() && caretOffset < inlineBox->caretMaxOffset()))
return;
}
} else {
RenderText* textRenderer = toRenderText(renderer);
InlineTextBox* box;
InlineTextBox* candidate = 0;
for (box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
int caretMinOffset = box->caretMinOffset();
int caretMaxOffset = box->caretMaxOffset();
if (caretOffset < caretMinOffset || caretOffset > caretMaxOffset || (caretOffset == caretMaxOffset && box->isLineBreak()))
continue;
if (caretOffset > caretMinOffset && caretOffset < caretMaxOffset) {
inlineBox = box;
return;
}
if (((caretOffset == caretMaxOffset) ^ (affinity == DOWNSTREAM))
|| ((caretOffset == caretMinOffset) ^ (affinity == UPSTREAM)))
break;
candidate = box;
}
if (candidate && candidate == textRenderer->lastTextBox() && affinity == DOWNSTREAM) {
box = searchAheadForBetterMatch(textRenderer);
if (box)
caretOffset = box->caretMinOffset();
}
inlineBox = box ? box : candidate;
}
if (!inlineBox)
return;
unsigned char level = inlineBox->bidiLevel();
if (inlineBox->direction() == primaryDirection) {
if (caretOffset == inlineBox->caretRightmostOffset()) {
InlineBox* nextBox = inlineBox->nextLeafChild();
if (!nextBox || nextBox->bidiLevel() >= level)
return;
level = nextBox->bidiLevel();
InlineBox* prevBox = inlineBox;
do {
prevBox = prevBox->prevLeafChild();
} while (prevBox && prevBox->bidiLevel() > level);
if (prevBox && prevBox->bidiLevel() == level) // For example, abc FED 123 ^ CBA
return;
// For example, abc 123 ^ CBA
while (InlineBox* nextBox = inlineBox->nextLeafChild()) {
if (nextBox->bidiLevel() < level)
break;
inlineBox = nextBox;
}
caretOffset = inlineBox->caretRightmostOffset();
} else {
InlineBox* prevBox = inlineBox->prevLeafChild();
if (!prevBox || prevBox->bidiLevel() >= level)
return;
level = prevBox->bidiLevel();
InlineBox* nextBox = inlineBox;
do {
nextBox = nextBox->nextLeafChild();
} while (nextBox && nextBox->bidiLevel() > level);
if (nextBox && nextBox->bidiLevel() == level)
return;
while (InlineBox* prevBox = inlineBox->prevLeafChild()) {
if (prevBox->bidiLevel() < level)
break;
inlineBox = prevBox;
}
caretOffset = inlineBox->caretLeftmostOffset();
}
return;
}
if (caretOffset == inlineBox->caretLeftmostOffset()) {
InlineBox* prevBox = inlineBox->prevLeafChild();
if (!prevBox || prevBox->bidiLevel() < level) {
// Left edge of a secondary run. Set to the right edge of the entire run.
while (InlineBox* nextBox = inlineBox->nextLeafChild()) {
if (nextBox->bidiLevel() < level)
break;
inlineBox = nextBox;
}
caretOffset = inlineBox->caretRightmostOffset();
} else if (prevBox->bidiLevel() > level) {
// Right edge of a "tertiary" run. Set to the left edge of that run.
while (InlineBox* tertiaryBox = inlineBox->prevLeafChild()) {
if (tertiaryBox->bidiLevel() <= level)
break;
inlineBox = tertiaryBox;
}
caretOffset = inlineBox->caretLeftmostOffset();
}
} else {
InlineBox* nextBox = inlineBox->nextLeafChild();
if (!nextBox || nextBox->bidiLevel() < level) {
// Right edge of a secondary run. Set to the left edge of the entire run.
while (InlineBox* prevBox = inlineBox->prevLeafChild()) {
if (prevBox->bidiLevel() < level)
break;
inlineBox = prevBox;
}
caretOffset = inlineBox->caretLeftmostOffset();
} else if (nextBox->bidiLevel() > level) {
// Left edge of a "tertiary" run. Set to the right edge of that run.
while (InlineBox* tertiaryBox = inlineBox->nextLeafChild()) {
if (tertiaryBox->bidiLevel() <= level)
break;
inlineBox = tertiaryBox;
}
caretOffset = inlineBox->caretRightmostOffset();
}
}
}
TextDirection Position::primaryDirection() const
{
TextDirection primaryDirection = LTR;
for (const RenderObject* r = m_anchorNode->renderer(); r; r = r->parent()) {
if (r->isBlockFlow()) {
primaryDirection = r->style()->direction();
break;
}
}
return primaryDirection;
}
void Position::debugPosition(const char* msg) const
{
if (isNull())
fprintf(stderr, "Position [%s]: null\n", msg);
else
fprintf(stderr, "Position [%s]: %s [%p] at %d\n", msg, deprecatedNode()->nodeName().utf8().data(), deprecatedNode(), m_offset);
}
#ifndef NDEBUG
void Position::formatForDebugger(char* buffer, unsigned length) const
{
String result;
if (isNull())
result = "<null>";
else {
char s[1024];
result += "offset ";
result += String::number(m_offset);
result += " of ";
deprecatedNode()->formatForDebugger(s, sizeof(s));
result += s;
}
strncpy(buffer, result.utf8().data(), length - 1);
}
void Position::showAnchorTypeAndOffset() const
{
if (m_isLegacyEditingPosition)
fputs("legacy, ", stderr);
switch (anchorType()) {
case PositionIsOffsetInAnchor:
fputs("offset", stderr);
break;
case PositionIsAfterAnchor:
fputs("after", stderr);
break;
case PositionIsBeforeAnchor:
fputs("before", stderr);
break;
}
fprintf(stderr, ", offset:%d\n", m_offset);
}
void Position::showTreeForThis() const
{
if (anchorNode()) {
anchorNode()->showTreeForThis();
showAnchorTypeAndOffset();
}
}
#endif
} // namespace WebCore
#ifndef NDEBUG
void showTree(const WebCore::Position& pos)
{
pos.showTreeForThis();
}
void showTree(const WebCore::Position* pos)
{
if (pos)
pos->showTreeForThis();
}
#endif
|