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 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
|
/*
* Copyright (C) 2004-2022 Apple Inc. All rights reserved.
* Copyright (C) 2015 Google 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 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 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 "BoundaryPoint.h"
#include "CSSComputedStyleDeclaration.h"
#include "Editing.h"
#include "ElementInlines.h"
#include "HTMLBRElement.h"
#include "HTMLBodyElement.h"
#include "HTMLHtmlElement.h"
#include "HTMLNames.h"
#include "HTMLTableElement.h"
#include "InlineIteratorLineBox.h"
#include "InlineIteratorLogicalOrderTraversal.h"
#include "InlineIteratorTextBox.h"
#include "InlineRunAndOffset.h"
#include "Logging.h"
#include "NodeTraversal.h"
#include "PositionIterator.h"
#include "RenderBlock.h"
#include "RenderBlockFlow.h"
#include "RenderBoxInlines.h"
#include "RenderFlexibleBox.h"
#include "RenderGrid.h"
#include "RenderInline.h"
#include "RenderIterator.h"
#include "RenderLineBreak.h"
#include "RenderText.h"
#include "Text.h"
#include "TextIterator.h"
#include "VisiblePosition.h"
#include "VisibleUnits.h"
#include <stdio.h>
#include <wtf/text/CString.h>
#include <wtf/text/TextStream.h>
#include <wtf/unicode/CharacterNames.h>
#if ENABLE(TREE_DEBUGGING)
#include <wtf/text/StringBuilder.h>
#endif
namespace WebCore {
using namespace HTMLNames;
static bool hasInlineRun(RenderObject& renderer)
{
if (is<RenderBox>(renderer) && InlineIterator::boxFor(downcast<RenderBox>(renderer)))
return true;
if (is<RenderText>(renderer) && InlineIterator::firstTextBoxFor(downcast<RenderText>(renderer)))
return true;
if (is<RenderLineBreak>(renderer) && InlineIterator::boxFor(downcast<RenderLineBreak>(renderer)))
return true;
return false;
}
static Node* nextRenderedEditable(Node* node)
{
while ((node = nextLeafNode(node))) {
RenderObject* renderer = node->renderer();
if (!renderer || !node->hasEditableStyle())
continue;
if (hasInlineRun(*renderer))
return node;
}
return nullptr;
}
static Node* previousRenderedEditable(Node* node)
{
while ((node = previousLeafNode(node))) {
RenderObject* renderer = node->renderer();
if (!renderer || !node->hasEditableStyle())
continue;
if (hasInlineRun(*renderer))
return node;
}
return nullptr;
}
Position::Position(Node* anchorNode, unsigned offset, LegacyEditingPositionFlag)
: m_anchorNode(anchorNode)
, m_offset(offset)
, m_anchorType(anchorTypeForLegacyEditingPosition(m_anchorNode.get(), m_offset))
, m_isLegacyEditingPosition(true)
{
ASSERT(!m_anchorNode || !m_anchorNode->isShadowRoot() || m_anchorNode == containerNode());
ASSERT(!m_anchorNode || !m_anchorNode->isPseudoElement());
}
Position::Position(Node* anchorNode, AnchorType anchorType)
: m_anchorNode(anchorNode)
, m_offset(0)
, m_anchorType(anchorType)
, m_isLegacyEditingPosition(false)
{
ASSERT(!m_anchorNode || !m_anchorNode->isShadowRoot() || m_anchorNode == containerNode());
ASSERT(!m_anchorNode || !m_anchorNode->isPseudoElement());
ASSERT(anchorType != PositionIsOffsetInAnchor);
ASSERT(!((anchorType == PositionIsBeforeChildren || anchorType == PositionIsAfterChildren)
&& (is<Text>(*m_anchorNode) || editingIgnoresContent(*m_anchorNode))));
}
Position::Position(Node* anchorNode, unsigned offset, AnchorType anchorType)
: m_anchorNode(anchorNode)
, m_offset(offset)
, m_anchorType(anchorType)
, m_isLegacyEditingPosition(false)
{
ASSERT(anchorType == PositionIsOffsetInAnchor);
}
Position::Position(Text* textNode, unsigned offset)
: m_anchorNode(textNode)
, m_offset(offset)
, m_anchorType(PositionIsOffsetInAnchor)
, m_isLegacyEditingPosition(false)
{
ASSERT(m_anchorNode);
}
void Position::moveToPosition(Node* node, unsigned offset)
{
ASSERT(!editingIgnoresContent(*node));
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(unsigned 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 nullptr;
switch (anchorType()) {
case PositionIsBeforeChildren:
case PositionIsAfterChildren:
case PositionIsOffsetInAnchor:
return m_anchorNode.get();
case PositionIsBeforeAnchor:
case PositionIsAfterAnchor:
return m_anchorNode->parentNode();
}
ASSERT_NOT_REACHED();
return nullptr;
}
Text* Position::containerText() const
{
switch (anchorType()) {
case PositionIsOffsetInAnchor:
return dynamicDowncast<Text>(m_anchorNode.get());
case PositionIsBeforeAnchor:
case PositionIsAfterAnchor:
return nullptr;
case PositionIsBeforeChildren:
case PositionIsAfterChildren:
ASSERT(!m_anchorNode || !is<Text>(*m_anchorNode));
return nullptr;
}
ASSERT_NOT_REACHED();
return nullptr;
}
Element* Position::containerOrParentElement() const
{
auto* container = containerNode();
if (!container)
return nullptr;
if (is<Element>(container))
return downcast<Element>(container);
return container->parentElement();
}
int Position::computeOffsetInContainerNode() const
{
if (!m_anchorNode)
return 0;
switch (anchorType()) {
case PositionIsBeforeChildren:
return 0;
case PositionIsAfterChildren:
return m_anchorNode->length();
case PositionIsOffsetInAnchor:
return m_offset;
case PositionIsBeforeAnchor:
return m_anchorNode->computeNodeIndex();
case PositionIsAfterAnchor:
return m_anchorNode->computeNodeIndex() + 1;
}
ASSERT_NOT_REACHED();
return 0;
}
int Position::offsetForPositionAfterAnchor() const
{
ASSERT(m_anchorType == PositionIsAfterAnchor || m_anchorType == PositionIsAfterChildren);
ASSERT(!m_isLegacyEditingPosition);
ASSERT(m_anchorNode);
return m_anchorNode ? lastOffsetForEditing(*m_anchorNode) : 0;
}
// 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 { };
// FIXME: This should only be necessary for legacy positions, but is also needed for positions before and after Tables
if (!m_offset && (m_anchorType != PositionIsAfterAnchor && m_anchorType != PositionIsAfterChildren)) {
if (m_anchorNode->parentNode() && (editingIgnoresContent(*m_anchorNode) || isRenderedTable(m_anchorNode.get())))
return positionInParentBeforeNode(m_anchorNode.get());
return Position(m_anchorNode.get(), 0, PositionIsOffsetInAnchor);
}
if (!m_anchorNode->isCharacterDataNode()
&& (m_anchorType == PositionIsAfterAnchor || m_anchorType == PositionIsAfterChildren || static_cast<unsigned>(m_offset) == m_anchorNode->countChildNodes())
&& (editingIgnoresContent(*m_anchorNode) || isRenderedTable(m_anchorNode.get()))
&& containerNode()) {
return positionInParentAfterNode(m_anchorNode.get());
}
return { containerNode(), static_cast<unsigned>(computeOffsetInContainerNode()), PositionIsOffsetInAnchor };
}
RefPtr<Node> Position::firstNode() const
{
RefPtr container { containerNode() };
if (!container)
return nullptr;
if (is<CharacterData>(*container))
return container;
if (auto* node = computeNodeAfterPosition())
return node;
if (!computeOffsetInContainerNode())
return container;
return NodeTraversal::nextSkippingChildren(*container);
}
Node* Position::computeNodeBeforePosition() const
{
if (!m_anchorNode)
return nullptr;
switch (anchorType()) {
case PositionIsBeforeChildren:
return nullptr;
case PositionIsAfterChildren:
return m_anchorNode->lastChild();
case PositionIsOffsetInAnchor:
return m_offset ? m_anchorNode->traverseToChildAt(m_offset - 1) : nullptr;
case PositionIsBeforeAnchor:
return m_anchorNode->previousSibling();
case PositionIsAfterAnchor:
return m_anchorNode.get();
}
ASSERT_NOT_REACHED();
return nullptr;
}
Node* Position::computeNodeAfterPosition() const
{
if (!m_anchorNode)
return nullptr;
switch (anchorType()) {
case PositionIsBeforeChildren:
return m_anchorNode->firstChild();
case PositionIsAfterChildren:
return nullptr;
case PositionIsOffsetInAnchor:
return m_anchorNode->traverseToChildAt(m_offset);
case PositionIsBeforeAnchor:
return m_anchorNode.get();
case PositionIsAfterAnchor:
return m_anchorNode->nextSibling();
}
ASSERT_NOT_REACHED();
return nullptr;
}
Position::AnchorType Position::anchorTypeForLegacyEditingPosition(Node* anchorNode, unsigned 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* node = anchorNode();
while (node && !is<Element>(*node))
node = node->parentNode();
return downcast<Element>(node);
}
Position Position::previous(PositionMoveType moveType) const
{
Node* node = deprecatedNode();
if (!node)
return *this;
// FIXME: Negative offsets shouldn't be allowed. We should catch this earlier.
ASSERT(deprecatedEditingOffset() >= 0);
unsigned offset = deprecatedEditingOffset();
if (anchorType() == PositionIsBeforeAnchor) {
node = containerNode();
if (!node)
return *this;
offset = computeOffsetInContainerNode();
}
if (offset > 0) {
if (Node* child = node->traverseToChildAt(offset - 1))
return lastPositionInOrAfterNode(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 makeDeprecatedLegacyPosition(node, offset - 1);
case Character:
return makeDeprecatedLegacyPosition(node, uncheckedPreviousOffset(node, offset));
case BackwardDeletion:
return makeDeprecatedLegacyPosition(node, uncheckedPreviousOffsetForBackwardDeletion(node, offset));
}
}
ContainerNode* parent = node->parentNode();
if (!parent)
return *this;
if (positionBeforeOrAfterNodeIsCandidate(*node))
return positionBeforeNode(node);
Node* previousSibling = node->previousSibling();
if (previousSibling && positionBeforeOrAfterNodeIsCandidate(*previousSibling))
return positionAfterNode(previousSibling);
return makeContainerOffsetPosition(parent, node->computeNodeIndex());
}
Position Position::next(PositionMoveType moveType) const
{
ASSERT(moveType != BackwardDeletion);
Node* node = deprecatedNode();
if (!node)
return *this;
// FIXME: Negative offsets shouldn't be allowed. We should catch this earlier.
ASSERT(deprecatedEditingOffset() >= 0);
unsigned offset = deprecatedEditingOffset();
if (anchorType() == PositionIsAfterAnchor) {
node = containerNode();
if (!node)
return *this;
offset = computeOffsetInContainerNode();
}
Node* child = node->traverseToChildAt(offset);
if (child || (!node->hasChildNodes() && offset < static_cast<unsigned>(lastOffsetForEditing(*node)))) {
if (child)
return firstPositionInOrBeforeNode(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 makeDeprecatedLegacyPosition(node, (moveType == Character) ? uncheckedNextOffset(node, offset) : offset + 1);
}
ContainerNode* parent = node->parentNode();
if (!parent)
return *this;
if (isRenderedTable(node) || editingIgnoresContent(*node))
return positionAfterNode(node);
Node* nextSibling = node->nextSibling();
if (nextSibling && positionBeforeOrAfterNodeIsCandidate(*nextSibling))
return positionBeforeNode(nextSibling);
return makeContainerOffsetPosition(parent, node->computeNodeIndex() + 1);
}
int Position::uncheckedPreviousOffset(const Node* n, unsigned current)
{
return n->renderer() ? n->renderer()->previousOffset(current) : current - 1;
}
int Position::uncheckedPreviousOffsetForBackwardDeletion(const Node* n, unsigned current)
{
return n->renderer() ? n->renderer()->previousOffsetForBackwardDeletion(current) : current - 1;
}
int Position::uncheckedNextOffset(const Node* n, unsigned current)
{
return n->renderer() ? n->renderer()->nextOffset(current) : current + 1;
}
bool Position::atFirstEditingPositionForNode() const
{
if (isNull())
return true;
// FIXME: Position before anchor shouldn't be considered as at the first editing position for node
// since that position resides outside of the node.
switch (m_anchorType) {
case PositionIsOffsetInAnchor:
return !m_offset;
case PositionIsBeforeChildren:
case PositionIsBeforeAnchor:
return true;
case PositionIsAfterChildren:
case PositionIsAfterAnchor:
return !lastOffsetForEditing(*deprecatedNode());
}
ASSERT_NOT_REACHED();
return false;
}
bool Position::atLastEditingPositionForNode() const
{
if (isNull())
return true;
// FIXME: Position after anchor shouldn't be considered as at the first editing position for node since that position resides outside of the node.
return m_anchorType == PositionIsAfterAnchor || m_anchorType == PositionIsAfterChildren || m_offset >= static_cast<unsigned>(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()->hasEditableStyle())
return true;
Position prevPosition = upstream(CanCrossEditingBoundary);
if (atLastEditingPositionForNode() && prevPosition.isNotNull() && !prevPosition.deprecatedNode()->hasEditableStyle())
return true;
return nextPosition.isNotNull() && !nextPosition.deprecatedNode()->hasEditableStyle()
&& prevPosition.isNotNull() && !prevPosition.deprecatedNode()->hasEditableStyle();
}
Node* Position::parentEditingBoundary() const
{
if (!m_anchorNode)
return nullptr;
Node* documentElement = m_anchorNode->document().documentElement();
if (!documentElement)
return nullptr;
Node* boundary = m_anchorNode.get();
while (boundary != documentElement && boundary->nonShadowBoundaryParentNode() && m_anchorNode->hasEditableStyle() == boundary->parentNode()->hasEditableStyle())
boundary = boundary->nonShadowBoundaryParentNode();
return boundary;
}
bool Position::atStartOfTree() const
{
if (isNull())
return true;
Node* container = containerNode();
if (container && container->parentNode())
return false;
switch (m_anchorType) {
case PositionIsOffsetInAnchor:
return !m_offset;
case PositionIsBeforeAnchor:
return !m_anchorNode->previousSibling();
case PositionIsAfterAnchor:
return false;
case PositionIsBeforeChildren:
return true;
case PositionIsAfterChildren:
return !lastOffsetForEditing(*m_anchorNode);
}
ASSERT_NOT_REACHED();
return false;
}
bool Position::atEndOfTree() const
{
if (isNull())
return true;
Node* container = containerNode();
if (container && container->parentNode())
return false;
switch (m_anchorType) {
case PositionIsOffsetInAnchor:
return m_offset >= static_cast<unsigned>(lastOffsetForEditing(*m_anchorNode));
case PositionIsBeforeAnchor:
return false;
case PositionIsAfterAnchor:
return !m_anchorNode->nextSibling();
case PositionIsBeforeChildren:
return !lastOffsetForEditing(*m_anchorNode);
case PositionIsAfterChildren:
return true;
}
ASSERT_NOT_REACHED();
return false;
}
// return first preceding DOM position rendered at a different location, or "this"
Position Position::previousCharacterPosition(Affinity affinity) const
{
if (isNull())
return { };
Node* fromRootEditableElement = deprecatedNode()->rootEditableElement();
bool atStartOfLine = isStartOfLine(VisiblePosition(*this, affinity));
bool rendered = isCandidate();
Position currentPosition = *this;
while (!currentPosition.atStartOfTree()) {
currentPosition = currentPosition.previous();
if (currentPosition.deprecatedNode()->rootEditableElement() != fromRootEditableElement)
return *this;
if (atStartOfLine || !rendered) {
if (currentPosition.isCandidate())
return currentPosition;
} else if (rendersInDifferentPosition(currentPosition))
return currentPosition;
}
return *this;
}
// return first following position rendered at a different location, or "this"
Position Position::nextCharacterPosition(Affinity affinity) const
{
if (isNull())
return { };
Node* fromRootEditableElement = deprecatedNode()->rootEditableElement();
bool atEndOfLine = isEndOfLine({ *this, affinity });
bool rendered = isCandidate();
Position currentPosition = *this;
while (!currentPosition.atEndOfTree()) {
currentPosition = currentPosition.next();
if (currentPosition.deprecatedNode()->rootEditableElement() != fromRootEditableElement)
return *this;
if (atEndOfLine || !rendered) {
if (currentPosition.isCandidate())
return currentPosition;
} else if (rendersInDifferentPosition(currentPosition))
return currentPosition;
}
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 (is<HTMLTableElement>(*node))
return false;
if (!node->renderer()->isReplacedOrInlineBlock() || !canHaveChildrenForEditing(*node) || !downcast<RenderBox>(*node->renderer()).height())
return false;
// There is a VisiblePosition inside an empty inline-block container.
if (!node->hasChildNodes())
return true;
return !Position::hasRenderedNonAnonymousDescendantsWithHeight(downcast<RenderElement>(*node->renderer()));
}
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 { };
// 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 ? makeDeprecatedLegacyPosition(m_anchorNode.get(), caretMaxOffset(*m_anchorNode)) : *this;
PositionIterator currentPosition = lastVisible;
bool startEditable = startNode->hasEditableStyle();
Node* lastNode = startNode;
bool boundaryCrossed = false;
for (; !currentPosition.atStart(); currentPosition.decrement()) {
auto& currentNode = *currentPosition.node();
// Don't check for an editability change if we haven't moved to a different node,
// to avoid the expense of computing hasEditableStyle().
if (¤tNode != lastNode) {
// Don't change editability.
bool currentEditable = currentNode.hasEditableStyle();
if (startEditable != currentEditable) {
if (rule == CannotCrossEditingBoundary)
break;
boundaryCrossed = true;
}
lastNode = ¤tNode;
}
// 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(¤tNode) && ¤tNode != boundary)
return lastVisible;
// skip position in unrendered or invisible node
RenderObject* renderer = currentNode.renderer();
if (!renderer || renderer->style().visibility() != Visibility::Visible)
continue;
if (rule == CanCrossEditingBoundary && boundaryCrossed) {
lastVisible = currentPosition;
break;
}
// track last visible streamer position
if (isStreamer(currentPosition))
lastVisible = currentPosition;
// 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 computeNodeIndex() call.
if (endsOfNodeAreVisuallyDistinctPositions(¤tNode) && currentPosition.atStartOfNode())
return lastVisible;
// Return position after tables and nodes which have content that can be ignored.
if (editingIgnoresContent(currentNode) || isRenderedTable(¤tNode)) {
if (currentPosition.atEndOfNode())
return positionAfterNode(¤tNode);
continue;
}
// return current position if it is in rendered text
if (is<RenderText>(*renderer)) {
auto& textRenderer = downcast<RenderText>(*renderer);
auto [firstTextBox, orderCache] = InlineIterator::firstTextBoxInLogicalOrderFor(textRenderer);
if (!firstTextBox)
continue;
if (¤tNode != 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 makeDeprecatedLegacyPosition(¤tNode, renderer->caretMaxOffset());
}
unsigned textOffset = currentPosition.offsetInLeafNode();
for (auto box = firstTextBox; box;) {
if (textOffset > box->start() && textOffset <= box->end())
return currentPosition;
auto nextBox = InlineIterator::nextTextBoxInLogicalOrder(box, orderCache);
if (textOffset == box->end() + 1 && nextBox && box->lineBox() != nextBox->lineBox())
return currentPosition;
box = nextBox;
}
}
}
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).
// FIXME: This function should never be called when the line box tree is dirty. See https://bugs.webkit.org/show_bug.cgi?id=97264
Position Position::downstream(EditingBoundaryCrossingRule rule) const
{
Node* startNode = deprecatedNode();
if (!startNode)
return { };
// 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 ? makeDeprecatedLegacyPosition(m_anchorNode.get(), caretMaxOffset(*m_anchorNode)) : *this;
PositionIterator currentPosition = lastVisible;
bool startEditable = startNode->hasEditableStyle();
Node* lastNode = startNode;
bool boundaryCrossed = false;
for (; !currentPosition.atEnd(); currentPosition.increment()) {
auto& currentNode = *currentPosition.node();
// Don't check for an editability change if we haven't moved to a different node,
// to avoid the expense of computing hasEditableStyle().
if (¤tNode != lastNode) {
// Don't change editability.
bool currentEditable = currentNode.hasEditableStyle();
if (startEditable != currentEditable) {
if (rule == CannotCrossEditingBoundary)
break;
boundaryCrossed = true;
}
lastNode = ¤tNode;
}
// stop before going above the body, up into the head
// return the last visible streamer position
if (is<HTMLBodyElement>(currentNode) && currentPosition.atEndOfNode())
break;
// Do not move to a visually distinct position.
if (endsOfNodeAreVisuallyDistinctPositions(¤tNode) && ¤tNode != 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->computeNodeIndex() + 1].
if (boundary && boundary->parentNode() == ¤tNode)
return lastVisible;
// skip position in unrendered or invisible node
auto* renderer = currentNode.renderer();
if (!renderer || renderer->style().visibility() != Visibility::Visible)
continue;
if (rule == CanCrossEditingBoundary && boundaryCrossed) {
lastVisible = currentPosition;
break;
}
// track last visible streamer position
if (isStreamer(currentPosition))
lastVisible = currentPosition;
// Return position before tables and nodes which have content that can be ignored.
if (editingIgnoresContent(currentNode) || isRenderedTable(¤tNode)) {
if (currentPosition.atStartOfNode())
return positionBeforeNode(¤tNode);
continue;
}
// return current position if it is in rendered text
if (is<RenderText>(*renderer)) {
auto& textRenderer = downcast<RenderText>(*renderer);
auto [firstTextBox, orderCache] = InlineIterator::firstTextBoxInLogicalOrderFor(textRenderer);
if (!firstTextBox)
continue;
if (¤tNode != startNode) {
ASSERT(currentPosition.atStartOfNode());
return makeContainerOffsetPosition(¤tNode, textRenderer.caretMinOffset());
}
unsigned textOffset = currentPosition.offsetInLeafNode();
for (auto box = firstTextBox; box;) {
if (!box->length() && textOffset == box->start())
return currentPosition;
if (textOffset >= box->start() && textOffset < box->end())
return currentPosition;
auto nextBox = InlineIterator::nextTextBoxInLogicalOrder(box, orderCache);
if (textOffset == box->end() && nextBox && box->lineBox() != nextBox->lineBox())
return currentPosition;
box = nextBox;
}
}
}
return lastVisible;
}
unsigned Position::positionCountBetweenPositions(const Position& a, const Position& b)
{
if (a.isNull() || b.isNull())
return UINT_MAX;
Position endPos;
Position pos;
if (a > b) {
endPos = a;
pos = b;
} else if (a < b) {
endPos = b;
pos = a;
} else
return 0;
unsigned posCount = 0;
while (!pos.atEndOfTree() && pos != endPos) {
pos = pos.next();
++posCount;
}
return posCount;
}
static int boundingBoxLogicalHeight(RenderObject *o, const IntRect &rect)
{
return o->style().isHorizontalWritingMode() ? rect.height() : rect.width();
}
bool Position::hasRenderedNonAnonymousDescendantsWithHeight(const RenderElement& renderer)
{
RenderObject* stop = renderer.nextInPreOrderAfterChildren();
for (RenderObject* o = renderer.firstChild(); o && o != stop; o = o->nextInPreOrder()) {
if (!o->nonPseudoNode())
continue;
if (is<RenderText>(*o)) {
if (boundingBoxLogicalHeight(o, downcast<RenderText>(*o).linesBoundingBox()))
return true;
continue;
}
if (is<RenderLineBreak>(*o)) {
if (boundingBoxLogicalHeight(o, downcast<RenderLineBreak>(*o).linesBoundingBox()))
return true;
continue;
}
if (is<RenderBox>(*o)) {
if (roundToInt(downcast<RenderBox>(*o).logicalHeight()))
return true;
continue;
}
if (is<RenderInline>(*o)) {
const RenderInline& renderInline = downcast<RenderInline>(*o);
if (isEmptyInline(renderInline) && boundingBoxLogicalHeight(o, renderInline.linesBoundingBox()))
return true;
continue;
}
}
return false;
}
bool Position::nodeIsUserSelectNone(Node* node)
{
if (!node)
return false;
return node->renderer() && (node->renderer()->style().effectiveUserSelect() == UserSelect::None);
}
bool Position::nodeIsUserSelectAll(const Node* node)
{
if (!node)
return false;
return node->renderer() && (node->renderer()->style().effectiveUserSelect() == UserSelect::All);
}
Node* Position::rootUserSelectAllForNode(Node* node)
{
if (!node || !nodeIsUserSelectAll(node))
return nullptr;
Node* parent = node->parentNode();
if (!parent)
return node;
Node* candidateRoot = node;
while (parent) {
if (!parent->renderer()) {
parent = parent->parentNode();
continue;
}
if (!nodeIsUserSelectAll(parent))
break;
candidateRoot = parent;
parent = candidateRoot->parentNode();
}
return candidateRoot;
}
// This function should be kept in sync with PositionIterator::isCandidate().
bool Position::isCandidate() const
{
if (isNull())
return false;
auto* renderer = deprecatedNode()->renderer();
if (!renderer)
return false;
if (renderer->style().visibility() != Visibility::Visible)
return false;
if (renderer->isBR()) {
// FIXME: The condition should be m_anchorType == PositionIsBeforeAnchor, but for now we still need to support legacy positions.
return !m_offset && m_anchorType != PositionIsAfterAnchor && !nodeIsUserSelectNone(deprecatedNode()->parentNode());
}
if (is<RenderText>(*renderer))
return !nodeIsUserSelectNone(deprecatedNode()) && downcast<RenderText>(*renderer).containsCaretOffset(m_offset);
if (positionBeforeOrAfterNodeIsCandidate(*deprecatedNode())) {
return ((atFirstEditingPositionForNode() && m_anchorType == PositionIsBeforeAnchor)
|| (atLastEditingPositionForNode() && m_anchorType == PositionIsAfterAnchor))
&& !nodeIsUserSelectNone(deprecatedNode()->parentNode());
}
if (is<HTMLHtmlElement>(*m_anchorNode))
return false;
if (is<RenderBlockFlow>(*renderer) || is<RenderGrid>(*renderer) || is<RenderFlexibleBox>(*renderer)) {
auto& block = downcast<RenderBlock>(*renderer);
if (block.logicalHeight() || is<HTMLBodyElement>(*m_anchorNode) || m_anchorNode->isRootEditableElement()) {
if (!Position::hasRenderedNonAnonymousDescendantsWithHeight(block))
return atFirstEditingPositionForNode() && !Position::nodeIsUserSelectNone(deprecatedNode());
return m_anchorNode->hasEditableStyle() && !Position::nodeIsUserSelectNone(deprecatedNode()) && atEditingBoundary();
}
return false;
}
return m_anchorNode->hasEditableStyle() && !Position::nodeIsUserSelectNone(deprecatedNode()) && atEditingBoundary();
}
bool Position::isRenderedCharacter() const
{
if (!is<Text>(deprecatedNode()))
return false;
RenderText* renderer = downcast<Text>(*deprecatedNode()).renderer();
if (!renderer)
return false;
return renderer->containsRenderedCharacterOffset(m_offset);
}
static bool inSameEnclosingBlockFlowElement(Node* a, Node* b)
{
return a && b && deprecatedEnclosingBlockFlowElement(a) == deprecatedEnclosingBlockFlowElement(b);
}
bool Position::rendersInDifferentPosition(const Position& position) const
{
if (isNull() || position.isNull())
return false;
auto* renderer = deprecatedNode()->renderer();
if (!renderer)
return false;
auto* positionRenderer = position.deprecatedNode()->renderer();
if (!positionRenderer)
return false;
if (renderer->style().visibility() != Visibility::Visible || positionRenderer->style().visibility() != Visibility::Visible)
return false;
if (deprecatedNode() == position.deprecatedNode()) {
if (is<HTMLBRElement>(*deprecatedNode()))
return false;
if (m_offset == static_cast<unsigned>(position.deprecatedEditingOffset()))
return false;
if (!is<Text>(*deprecatedNode()))
return true;
}
if (is<HTMLBRElement>(*deprecatedNode()) && position.isCandidate())
return true;
if (is<HTMLBRElement>(*position.deprecatedNode()) && isCandidate())
return true;
if (!inSameEnclosingBlockFlowElement(deprecatedNode(), position.deprecatedNode()))
return true;
if (is<RenderText>(*renderer) && !downcast<RenderText>(*renderer).containsCaretOffset(m_offset))
return false;
if (is<RenderText>(*positionRenderer) && !downcast<RenderText>(*positionRenderer).containsCaretOffset(position.m_offset))
return false;
unsigned thisRenderedOffset = is<RenderText>(*renderer) ? downcast<RenderText>(*renderer).countRenderedCharacterOffsetsUntil(m_offset) : m_offset;
unsigned positionRenderedOffset = is<RenderText>(*positionRenderer) ? downcast<RenderText>(*positionRenderer).countRenderedCharacterOffsetsUntil(position.m_offset) : position.m_offset;
if (renderer == positionRenderer && thisRenderedOffset == positionRenderedOffset)
return false;
auto box1 = inlineBoxAndOffset(Affinity::Downstream).box;
auto box2 = position.inlineBoxAndOffset(Affinity::Downstream).box;
LOG(Editing, "renderer: %p\n", renderer);
LOG(Editing, "thisRenderedOffset: %d\n", thisRenderedOffset);
LOG(Editing, "posRenderer: %p\n", positionRenderer);
LOG(Editing, "posRenderedOffset: %d\n", positionRenderedOffset);
LOG(Editing, "node min/max: %d:%d\n", caretMinOffset(*deprecatedNode()), caretMaxOffset(*deprecatedNode()));
LOG(Editing, "pos node min/max: %d:%d\n", caretMinOffset(*position.deprecatedNode()), caretMaxOffset(*position.deprecatedNode()));
LOG(Editing, "----------------------------------------------------------------------\n");
if (!box1 || !box2)
return false;
if (box1->lineBox() != box2->lineBox())
return true;
if (nextRenderedEditable(deprecatedNode()) == position.deprecatedNode()
&& thisRenderedOffset == static_cast<unsigned>(caretMaxOffset(*deprecatedNode())) && !positionRenderedOffset) {
return false;
}
if (previousRenderedEditable(deprecatedNode()) == position.deprecatedNode()
&& !thisRenderedOffset && positionRenderedOffset == static_cast<unsigned>(caretMaxOffset(*position.deprecatedNode()))) {
return false;
}
return true;
}
// This assumes that it starts in editable content.
Position Position::leadingWhitespacePosition(Affinity affinity, bool considerNonCollapsibleWhitespace) const
{
ASSERT(isEditablePosition(*this));
if (isNull())
return { };
if (is<HTMLBRElement>(*upstream().deprecatedNode()))
return { };
Position prev = previousCharacterPosition(affinity);
if (prev != *this && inSameEnclosingBlockFlowElement(deprecatedNode(), prev.deprecatedNode()) && is<Text>(*prev.deprecatedNode())) {
UChar c = downcast<Text>(*prev.deprecatedNode()).data()[prev.deprecatedEditingOffset()];
if (considerNonCollapsibleWhitespace ? (isASCIIWhitespace(c) || c == noBreakSpace) : deprecatedIsCollapsibleWhitespace(c)) {
if (isEditablePosition(prev))
return prev;
}
}
return { };
}
// This assumes that it starts in editable content.
Position Position::trailingWhitespacePosition(Affinity, bool considerNonCollapsibleWhitespace) const
{
ASSERT(isEditablePosition(*this));
if (isNull())
return { };
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(CannotCrossEditingBoundary).isNotNull())
if (considerNonCollapsibleWhitespace ? (isASCIIWhitespace(c) || c == noBreakSpace) : deprecatedIsCollapsibleWhitespace(c))
return *this;
return { };
}
InlineBoxAndOffset Position::inlineBoxAndOffset(Affinity affinity) const
{
return inlineBoxAndOffset(affinity, primaryDirection());
}
static bool isNonTextLeafChild(RenderObject& object)
{
if (is<RenderText>(object))
return false;
return !downcast<RenderElement>(object).firstChild();
}
static InlineIterator::TextBoxIterator searchAheadForBetterMatch(RenderText& renderer)
{
RenderBlock* container = renderer.containingBlock();
RenderObject* next = &renderer;
while ((next = next->nextInPreOrder(container))) {
if (is<RenderBlock>(*next))
return { };
if (next->isBR())
return { };
if (isNonTextLeafChild(*next))
return { };
if (is<RenderText>(*next)) {
if (auto [box, orderCache] = InlineIterator::firstTextBoxInLogicalOrderFor(downcast<RenderText>(*next)); box)
return box;
}
}
return { };
}
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;
}
InlineBoxAndOffset Position::inlineBoxAndOffset(Affinity affinity, TextDirection primaryDirection) const
{
auto caretOffset = static_cast<unsigned>(deprecatedEditingOffset());
auto node = deprecatedNode();
if (!node)
return { { }, caretOffset };
auto renderer = node->renderer();
if (!renderer)
return { { }, caretOffset };
InlineIterator::LeafBoxIterator box;
if (renderer->isBR()) {
auto& lineBreakRenderer = downcast<RenderLineBreak>(*renderer);
if (!caretOffset)
box = InlineIterator::boxFor(lineBreakRenderer);
} else if (is<RenderText>(*renderer)) {
auto& textRenderer = downcast<RenderText>(*renderer);
auto textBox = InlineIterator::firstTextBoxFor(textRenderer);
InlineIterator::TextBoxIterator candidate;
for (; textBox; ++textBox) {
unsigned caretMinOffset = textBox->minimumCaretOffset();
unsigned caretMaxOffset = textBox->maximumCaretOffset();
if (caretOffset < caretMinOffset || caretOffset > caretMaxOffset || (caretOffset == caretMaxOffset && textBox->isLineBreak()))
continue;
if (caretOffset > caretMinOffset && caretOffset < caretMaxOffset)
return { textBox, caretOffset };
if ((caretOffset == caretMaxOffset) ^ (affinity == Affinity::Downstream))
break;
if ((caretOffset == caretMinOffset) ^ (affinity == Affinity::Upstream))
break;
if (caretOffset == caretMaxOffset) {
auto nextOnLine = textBox->nextOnLine();
if (nextOnLine && nextOnLine->isLineBreak())
break;
}
candidate = textBox;
}
if (candidate && !candidate->nextTextBox() && affinity == Affinity::Downstream) {
textBox = searchAheadForBetterMatch(textRenderer);
if (textBox)
caretOffset = textBox->minimumCaretOffset();
}
box = textBox ? textBox : candidate;
} else {
if (canHaveChildrenForEditing(*deprecatedNode()) && is<RenderBlockFlow>(*renderer) && hasRenderedNonAnonymousDescendantsWithHeight(downcast<RenderBlockFlow>(*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);
// FIXME: Can returning nullptr really be correct here?
if (equivalent == *this || downstreamIgnoringEditingBoundaries(equivalent) == *this)
return { { }, caretOffset };
}
return equivalent.inlineBoxAndOffset(Affinity::Upstream, primaryDirection);
}
if (is<RenderBox>(*renderer)) {
box = InlineIterator::boxFor(downcast<RenderBox>(*renderer));
if (box && caretOffset > box->minimumCaretOffset() && caretOffset < box->maximumCaretOffset())
return { box, caretOffset };
}
}
if (!box)
return { { }, caretOffset };
unsigned char level = box->bidiLevel();
if (box->direction() == primaryDirection) {
if (caretOffset == box->rightmostCaretOffset()) {
auto nextBox = box->nextOnLine();
if (!nextBox || nextBox->bidiLevel() >= level)
return { box, caretOffset };
level = nextBox->bidiLevel();
auto previousRun = box->previousOnLine();
for (; previousRun; previousRun.traversePreviousOnLine()) {
if (previousRun->bidiLevel() <= level)
break;
}
if (previousRun && previousRun->bidiLevel() == level) // For example, abc FED 123 ^ CBA
return { box, caretOffset };
// For example, abc 123 ^ CBA
for (; nextBox; nextBox.traverseNextOnLine()) {
if (nextBox->bidiLevel() < level)
break;
box = nextBox;
}
caretOffset = box->rightmostCaretOffset();
} else {
auto previousRun = box->previousOnLine();
if (!previousRun || previousRun->bidiLevel() >= level)
return { box, caretOffset };
level = previousRun->bidiLevel();
auto nextBox = box->nextOnLine();
for (; nextBox; nextBox.traverseNextOnLine()) {
if (nextBox->bidiLevel() <= level)
break;
}
if (nextBox && nextBox->bidiLevel() == level)
return { box, caretOffset };
for (; previousRun; previousRun.traversePreviousOnLine()) {
if (previousRun->bidiLevel() < level)
break;
box = previousRun;
}
caretOffset = box->leftmostCaretOffset();
}
return { box, caretOffset };
}
if (caretOffset == box->leftmostCaretOffset()) {
auto previousRun = box->previousOnLineIgnoringLineBreak();
if (!previousRun || previousRun->bidiLevel() < level) {
// Left edge of a secondary box. Set to the right edge of the entire box.
for (auto nextBox = box->nextOnLineIgnoringLineBreak(); nextBox; nextBox.traverseNextOnLineIgnoringLineBreak()) {
if (nextBox->bidiLevel() < level)
break;
box = nextBox;
}
caretOffset = box->rightmostCaretOffset();
} else if (previousRun->bidiLevel() > level) {
// Right edge of a "tertiary" box. Set to the left edge of that box.
for (auto tertiaryRun = box->previousOnLineIgnoringLineBreak(); tertiaryRun; tertiaryRun.traversePreviousOnLineIgnoringLineBreak()) {
if (tertiaryRun->bidiLevel() <= level)
break;
box = tertiaryRun;
}
caretOffset = box->leftmostCaretOffset();
}
} else {
auto nextBox = box->nextOnLineIgnoringLineBreak();
if (!nextBox || nextBox->bidiLevel() < level) {
// Right edge of a secondary box. Set to the left edge of the entire box.
for (auto previousRun = box->previousOnLineIgnoringLineBreak(); previousRun; previousRun.traversePreviousOnLineIgnoringLineBreak()) {
if (previousRun->bidiLevel() < level)
break;
box = previousRun;
}
caretOffset = box->leftmostCaretOffset();
} else if (nextBox->bidiLevel() > level) {
// Left edge of a "tertiary" box. Set to the right edge of that box.
for (auto tertiaryRun = box->nextOnLineIgnoringLineBreak(); tertiaryRun; tertiaryRun.traverseNextOnLineIgnoringLineBreak()) {
if (tertiaryRun->bidiLevel() <= level)
break;
box = tertiaryRun;
}
caretOffset = box->rightmostCaretOffset();
}
}
return { box, caretOffset };
}
TextDirection Position::primaryDirection() const
{
if (!m_anchorNode || !m_anchorNode->renderer())
return TextDirection::LTR;
if (auto* blockFlow = lineageOfType<RenderBlockFlow>(*m_anchorNode->renderer()).first())
return blockFlow->style().direction();
return TextDirection::LTR;
}
#if ENABLE(TREE_DEBUGGING)
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);
}
String Position::debugDescription() const
{
if (isNull())
return "<null>"_s;
return makeString("offset ", m_offset, " of ", deprecatedNode()->debugDescription());
}
void Position::showAnchorTypeAndOffset() const
{
if (m_isLegacyEditingPosition)
fputs("legacy, ", stderr);
switch (anchorType()) {
case PositionIsOffsetInAnchor:
fputs("offset", stderr);
break;
case PositionIsBeforeChildren:
fputs("beforeChildren", stderr);
break;
case PositionIsAfterChildren:
fputs("afterChildren", stderr);
break;
case PositionIsBeforeAnchor:
fputs("before", stderr);
break;
case PositionIsAfterAnchor:
fputs("after", stderr);
break;
}
fprintf(stderr, ", offset:%d\n", m_offset);
}
void Position::showTreeForThis() const
{
if (anchorNode()) {
anchorNode()->showTreeForThis();
showAnchorTypeAndOffset();
}
}
#endif
bool Position::equals(const Position& other) const
{
if (!m_anchorNode)
return !m_anchorNode == !other.m_anchorNode;
if (!other.m_anchorNode)
return false;
switch (anchorType()) {
case PositionIsBeforeChildren:
ASSERT(!is<Text>(*m_anchorNode));
switch (other.anchorType()) {
case PositionIsBeforeChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return m_anchorNode == other.m_anchorNode;
case PositionIsAfterChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return m_anchorNode == other.m_anchorNode && !m_anchorNode->hasChildNodes();
case PositionIsOffsetInAnchor:
return m_anchorNode == other.m_anchorNode && !other.m_offset;
case PositionIsBeforeAnchor:
return m_anchorNode->firstChild() == other.m_anchorNode;
case PositionIsAfterAnchor:
return false;
}
break;
case PositionIsAfterChildren:
ASSERT(!is<Text>(*m_anchorNode));
switch (other.anchorType()) {
case PositionIsBeforeChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return m_anchorNode == other.m_anchorNode && !m_anchorNode->hasChildNodes();
case PositionIsAfterChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return m_anchorNode == other.m_anchorNode;
case PositionIsOffsetInAnchor:
return m_anchorNode == other.m_anchorNode && m_anchorNode->countChildNodes() == static_cast<unsigned>(m_offset);
case PositionIsBeforeAnchor:
return false;
case PositionIsAfterAnchor:
return m_anchorNode->lastChild() == other.m_anchorNode;
}
break;
case PositionIsOffsetInAnchor:
switch (other.anchorType()) {
case PositionIsBeforeChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return m_anchorNode == other.m_anchorNode && !m_offset;
case PositionIsAfterChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return m_anchorNode == other.m_anchorNode && m_offset == other.m_anchorNode->countChildNodes();
case PositionIsOffsetInAnchor:
return m_anchorNode == other.m_anchorNode && m_offset == other.m_offset;
case PositionIsBeforeAnchor:
return m_anchorNode->traverseToChildAt(m_offset) == other.m_anchorNode;
case PositionIsAfterAnchor:
return m_offset && m_anchorNode->traverseToChildAt(m_offset - 1) == other.m_anchorNode;
}
break;
case PositionIsBeforeAnchor:
switch (other.anchorType()) {
case PositionIsBeforeChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return m_anchorNode == other.m_anchorNode->firstChild();
case PositionIsAfterChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return false;
case PositionIsOffsetInAnchor:
return m_anchorNode == other.m_anchorNode->traverseToChildAt(other.m_offset);
case PositionIsBeforeAnchor:
return m_anchorNode == other.m_anchorNode;
case PositionIsAfterAnchor:
return m_anchorNode->previousSibling() == other.m_anchorNode;
}
break;
case PositionIsAfterAnchor:
switch (other.anchorType()) {
case PositionIsBeforeChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return false;
case PositionIsAfterChildren:
ASSERT(!is<Text>(*other.m_anchorNode));
return m_anchorNode == other.m_anchorNode->lastChild();
case PositionIsOffsetInAnchor:
return other.m_offset && m_anchorNode == other.m_anchorNode->traverseToChildAt(other.m_offset - 1);
case PositionIsBeforeAnchor:
return m_anchorNode->nextSibling() == other.m_anchorNode;
case PositionIsAfterAnchor:
return m_anchorNode == other.m_anchorNode;
}
break;
}
ASSERT_NOT_REACHED();
return false;
}
static TextStream& operator<<(TextStream& stream, Position::AnchorType anchorType)
{
switch (anchorType) {
case Position::PositionIsOffsetInAnchor:
stream << "offset in anchor";
break;
case Position::PositionIsBeforeAnchor:
stream << "before anchor";
break;
case Position::PositionIsAfterAnchor:
stream << "after anchor";
break;
case Position::PositionIsBeforeChildren:
stream << "before children";
break;
case Position::PositionIsAfterChildren:
stream << "after children";
break;
}
return stream;
}
TextStream& operator<<(TextStream& stream, const Position& position)
{
TextStream::GroupScope scope(stream);
stream << "Position " << &position;
stream.dumpProperty("anchor node", position.anchorNode());
stream.dumpProperty("offset", position.offsetInContainerNode());
stream.dumpProperty("anchor type", position.anchorType());
return stream;
}
Node* commonInclusiveAncestor(const Position& a, const Position& b)
{
auto nodeA = a.containerNode();
auto nodeB = b.containerNode();
if (!nodeA || !nodeB)
return nullptr;
return commonInclusiveAncestor<ComposedTree>(*nodeA, *nodeB);
}
Position positionInParentBeforeNode(Node* node)
{
auto* ancestor = node->parentNode();
while (ancestor && editingIgnoresContent(*ancestor)) {
node = ancestor;
ancestor = ancestor->parentNode();
}
ASSERT(ancestor);
return Position(ancestor, node->computeNodeIndex(), Position::PositionIsOffsetInAnchor);
}
Position positionInParentAfterNode(Node* node)
{
auto* ancestor = node->parentNode();
while (ancestor && editingIgnoresContent(*ancestor)) {
node = ancestor;
ancestor = ancestor->parentNode();
}
ASSERT(ancestor);
return Position(ancestor, node->computeNodeIndex() + 1, Position::PositionIsOffsetInAnchor);
}
Position makeContainerOffsetPosition(const BoundaryPoint& point)
{
return makeContainerOffsetPosition(point.container.ptr(), point.offset);
}
Position makeDeprecatedLegacyPosition(const BoundaryPoint& point)
{
return makeDeprecatedLegacyPosition(point.container.ptr(), point.offset);
}
std::optional<BoundaryPoint> makeBoundaryPoint(const Position& position)
{
RefPtr container { position.containerNode() };
if (!container)
return std::nullopt;
return BoundaryPoint { container.releaseNonNull(), static_cast<unsigned>(position.computeOffsetInContainerNode()) };
}
template<TreeType treeType> std::partial_ordering treeOrder(const Position& a, const Position& b)
{
if (a.isNull() || b.isNull())
return a.isNull() && b.isNull() ? std::partial_ordering::equivalent : std::partial_ordering::unordered;
auto aContainer = a.containerNode();
auto bContainer = b.containerNode();
if (!aContainer || !bContainer) {
if (!commonInclusiveAncestor<treeType>(*a.anchorNode(), *b.anchorNode()))
return std::partial_ordering::unordered;
if (!aContainer && !bContainer && a.anchorType() == b.anchorType())
return std::partial_ordering::equivalent;
if (bContainer)
return a.anchorType() == Position::PositionIsBeforeAnchor ? std::partial_ordering::less : std::partial_ordering::greater;
return b.anchorType() == Position::PositionIsBeforeAnchor ? std::partial_ordering::greater : std::partial_ordering::less;
}
// FIXME: Avoid computing node offset for cases where we don't need to.
return treeOrder<treeType>(*makeBoundaryPoint(a), *makeBoundaryPoint(b));
}
std::partial_ordering documentOrder(const Position& a, const Position& b)
{
return treeOrder<ComposedTree>(a, b);
}
template std::partial_ordering treeOrder<ComposedTree>(const Position&, const Position&);
template std::partial_ordering treeOrder<ShadowIncludingTree>(const Position&, const Position&);
} // namespace WebCore
#if ENABLE(TREE_DEBUGGING)
void showTree(const WebCore::Position& pos)
{
pos.showTreeForThis();
}
void showTree(const WebCore::Position* pos)
{
if (pos)
pos->showTreeForThis();
}
#endif
|