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 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
* Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc.
* All rights reserved.
* Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
* Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
* (http://www.torchmobile.com/)
* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "core/css/resolver/StyleResolver.h"
#include "core/CSSPropertyNames.h"
#include "core/HTMLNames.h"
#include "core/MediaTypeNames.h"
#include "core/StylePropertyShorthand.h"
#include "core/animation/AnimationTimeline.h"
#include "core/animation/CSSInterpolationTypesMap.h"
#include "core/animation/ElementAnimations.h"
#include "core/animation/InterpolationEnvironment.h"
#include "core/animation/InvalidatableInterpolation.h"
#include "core/animation/KeyframeEffect.h"
#include "core/animation/LegacyStyleInterpolation.h"
#include "core/animation/animatable/AnimatableValue.h"
#include "core/animation/css/CSSAnimatableValueFactory.h"
#include "core/animation/css/CSSAnimations.h"
#include "core/css/CSSCalculationValue.h"
#include "core/css/CSSCustomIdentValue.h"
#include "core/css/CSSDefaultStyleSheets.h"
#include "core/css/CSSFontSelector.h"
#include "core/css/CSSIdentifierValue.h"
#include "core/css/CSSKeyframeRule.h"
#include "core/css/CSSKeyframesRule.h"
#include "core/css/CSSReflectValue.h"
#include "core/css/CSSRuleList.h"
#include "core/css/CSSSelector.h"
#include "core/css/CSSStyleRule.h"
#include "core/css/CSSValueList.h"
#include "core/css/ElementRuleCollector.h"
#include "core/css/FontFace.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/PageRuleCollector.h"
#include "core/css/StylePropertySet.h"
#include "core/css/StyleRuleImport.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/resolver/AnimatedStyleBuilder.h"
#include "core/css/resolver/CSSVariableResolver.h"
#include "core/css/resolver/MatchResult.h"
#include "core/css/resolver/MediaQueryResult.h"
#include "core/css/resolver/ScopedStyleResolver.h"
#include "core/css/resolver/SelectorFilterParentScope.h"
#include "core/css/resolver/SharedStyleFinder.h"
#include "core/css/resolver/StyleAdjuster.h"
#include "core/css/resolver/StyleResolverState.h"
#include "core/css/resolver/StyleResolverStats.h"
#include "core/css/resolver/StyleRuleUsageTracker.h"
#include "core/dom/CSSSelectorWatch.h"
#include "core/dom/FirstLetterPseudoElement.h"
#include "core/dom/NodeComputedStyle.h"
#include "core/dom/StyleEngine.h"
#include "core/dom/Text.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/frame/UseCounter.h"
#include "core/html/HTMLIFrameElement.h"
#include "core/html/HTMLSlotElement.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/layout/GeneratedChildren.h"
#include "core/style/StyleInheritedVariables.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGElement.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "wtf/StdLibExtras.h"
namespace {
using namespace blink;
void setAnimationUpdateIfNeeded(StyleResolverState& state, Element& element) {
// If any changes to CSS Animations were detected, stash the update away for
// application after the layout object is updated if we're in the appropriate
// scope.
if (!state.animationUpdate().isEmpty())
element.ensureElementAnimations().cssAnimations().setPendingUpdate(
state.animationUpdate());
}
// Returns whether any @apply rule sets a custom property
bool cacheCustomPropertiesForApplyAtRules(StyleResolverState& state,
const MatchedPropertiesRange& range) {
bool ruleSetsCustomProperty = false;
// TODO(timloh): @apply should also work with properties registered as
// non-inherited.
if (!state.style()->inheritedVariables())
return false;
for (const auto& matchedProperties : range) {
const StylePropertySet& properties = *matchedProperties.properties;
unsigned propertyCount = properties.propertyCount();
for (unsigned i = 0; i < propertyCount; ++i) {
StylePropertySet::PropertyReference current = properties.propertyAt(i);
if (current.id() != CSSPropertyApplyAtRule)
continue;
AtomicString name(toCSSCustomIdentValue(current.value()).value());
CSSVariableData* variableData =
state.style()->inheritedVariables()->getVariable(name);
if (!variableData)
continue;
StylePropertySet* customPropertySet = variableData->propertySet();
if (!customPropertySet)
continue;
if (customPropertySet->findPropertyIndex(CSSPropertyVariable) != -1)
ruleSetsCustomProperty = true;
state.setCustomPropertySetForApplyAtRule(name, customPropertySet);
}
}
return ruleSetsCustomProperty;
}
} // namespace
namespace blink {
using namespace HTMLNames;
ComputedStyle* StyleResolver::s_styleNotYetAvailable;
static StylePropertySet* leftToRightDeclaration() {
DEFINE_STATIC_LOCAL(MutableStylePropertySet, leftToRightDecl,
(MutableStylePropertySet::create(HTMLQuirksMode)));
if (leftToRightDecl.isEmpty())
leftToRightDecl.setProperty(CSSPropertyDirection, CSSValueLtr);
return &leftToRightDecl;
}
static StylePropertySet* rightToLeftDeclaration() {
DEFINE_STATIC_LOCAL(MutableStylePropertySet, rightToLeftDecl,
(MutableStylePropertySet::create(HTMLQuirksMode)));
if (rightToLeftDecl.isEmpty())
rightToLeftDecl.setProperty(CSSPropertyDirection, CSSValueRtl);
return &rightToLeftDecl;
}
static void collectScopedResolversForHostedShadowTrees(
const Element& element,
HeapVector<Member<ScopedStyleResolver>, 8>& resolvers) {
ElementShadow* shadow = element.shadow();
if (!shadow)
return;
// Adding scoped resolver for active shadow roots for shadow host styling.
for (ShadowRoot* shadowRoot = &shadow->youngestShadowRoot(); shadowRoot;
shadowRoot = shadowRoot->olderShadowRoot()) {
if (ScopedStyleResolver* resolver = shadowRoot->scopedStyleResolver())
resolvers.push_back(resolver);
}
}
StyleResolver::StyleResolver(Document& document) : m_document(document) {
updateMediaType();
}
StyleResolver::~StyleResolver() {}
void StyleResolver::dispose() {
m_matchedPropertiesCache.clear();
}
void StyleResolver::setRuleUsageTracker(StyleRuleUsageTracker* tracker) {
m_tracker = tracker;
}
void StyleResolver::addToStyleSharingList(Element& element) {
DCHECK(RuntimeEnabledFeatures::styleSharingEnabled());
// Never add elements to the style sharing list if we're not in a recalcStyle,
// otherwise we could leave stale pointers in there.
if (!document().inStyleRecalc())
return;
INCREMENT_STYLE_STATS_COUNTER(document().styleEngine(), sharedStyleCandidates,
1);
StyleSharingList& list = styleSharingList();
if (list.size() >= styleSharingListSize)
list.removeLast();
list.prepend(&element);
}
StyleSharingList& StyleResolver::styleSharingList() {
m_styleSharingLists.resize(styleSharingMaxDepth);
// We never put things at depth 0 into the list since that's only the <html>
// element and it has no siblings or cousins to share with.
unsigned depth =
std::max(std::min(m_styleSharingDepth, styleSharingMaxDepth), 1u) - 1u;
if (!m_styleSharingLists[depth])
m_styleSharingLists[depth] = new StyleSharingList;
return *m_styleSharingLists[depth];
}
void StyleResolver::clearStyleSharingList() {
m_styleSharingLists.resize(0);
}
static inline ScopedStyleResolver* scopedResolverFor(const Element& element) {
// Ideally, returning element->treeScope().scopedStyleResolver() should be
// enough, but ::cue and custom pseudo elements like ::-webkit-meter-bar
// pierce through a shadow dom boundary, yet they are not part of boundary
// crossing rules. The assumption here is that these rules only pierce through
// one boundary and that the scope of these elements do not have a style
// resolver due to the fact that VTT scopes and UA shadow trees don't have
// <style> elements. This is backed up by the DCHECKs below.
TreeScope* treeScope = &element.treeScope();
if (ScopedStyleResolver* resolver = treeScope->scopedStyleResolver()) {
DCHECK(element.shadowPseudoId().isEmpty());
DCHECK(!element.isVTTElement());
return resolver;
}
treeScope = treeScope->parentTreeScope();
if (!treeScope)
return nullptr;
if (element.shadowPseudoId().isEmpty() && !element.isVTTElement())
return nullptr;
return treeScope->scopedStyleResolver();
}
static void matchHostRules(const Element& element,
ElementRuleCollector& collector) {
ElementShadow* shadow = element.shadow();
if (!shadow)
return;
for (ShadowRoot* shadowRoot = &shadow->oldestShadowRoot(); shadowRoot;
shadowRoot = shadowRoot->youngerShadowRoot()) {
if (ScopedStyleResolver* resolver = shadowRoot->scopedStyleResolver()) {
collector.clearMatchedRules();
resolver->collectMatchingShadowHostRules(collector);
collector.sortAndTransferMatchedRules();
collector.finishAddingAuthorRulesForTreeScope();
}
}
}
static void matchSlottedRules(const Element& element,
ElementRuleCollector& collector) {
HTMLSlotElement* slot = element.assignedSlot();
if (!slot)
return;
HeapVector<Member<ScopedStyleResolver>> resolvers;
for (; slot; slot = slot->assignedSlot()) {
if (ScopedStyleResolver* resolver = slot->treeScope().scopedStyleResolver())
resolvers.push_back(resolver);
}
for (auto it = resolvers.rbegin(); it != resolvers.rend(); ++it) {
collector.clearMatchedRules();
(*it)->collectMatchingTreeBoundaryCrossingRules(collector);
collector.sortAndTransferMatchedRules();
collector.finishAddingAuthorRulesForTreeScope();
}
}
static void matchElementScopeRules(const Element& element,
ScopedStyleResolver* elementScopeResolver,
ElementRuleCollector& collector) {
if (elementScopeResolver) {
collector.clearMatchedRules();
elementScopeResolver->collectMatchingAuthorRules(collector);
elementScopeResolver->collectMatchingTreeBoundaryCrossingRules(collector);
collector.sortAndTransferMatchedRules();
}
if (element.isStyledElement() && element.inlineStyle() &&
!collector.isCollectingForPseudoElement()) {
// Inline style is immutable as long as there is no CSSOM wrapper.
bool isInlineStyleCacheable = !element.inlineStyle()->isMutable();
collector.addElementStyleProperties(element.inlineStyle(),
isInlineStyleCacheable);
}
collector.finishAddingAuthorRulesForTreeScope();
}
static bool shouldCheckScope(const Element& element,
const Node& scopingNode,
bool isInnerTreeScope) {
if (isInnerTreeScope && element.treeScope() != scopingNode.treeScope()) {
// Check if |element| may be affected by a ::content rule in |scopingNode|'s
// style. If |element| is a descendant of a shadow host which is ancestral
// to |scopingNode|, the |element| should be included for rule collection.
// Skip otherwise.
const TreeScope* scope = &scopingNode.treeScope();
while (scope && scope->parentTreeScope() != &element.treeScope())
scope = scope->parentTreeScope();
Element* shadowHost = scope ? scope->rootNode().ownerShadowHost() : nullptr;
return shadowHost && element.isDescendantOf(shadowHost);
}
// When |element| can be distributed to |scopingNode| via <shadow>, ::content
// rule can match, thus the case should be included.
if (!isInnerTreeScope &&
scopingNode.parentOrShadowHostNode() ==
element.treeScope().rootNode().parentOrShadowHostNode())
return true;
// Obviously cases when ancestor scope has /deep/ or ::shadow rule should be
// included. Skip otherwise.
return scopingNode.treeScope()
.scopedStyleResolver()
->hasDeepOrShadowSelector();
}
void StyleResolver::matchScopedRules(const Element& element,
ElementRuleCollector& collector) {
// Match rules from treeScopes in the reverse tree-of-trees order, since the
// cascading order for normal rules is such that when comparing rules from
// different shadow trees, the rule from the tree which comes first in the
// tree-of-trees order wins. From other treeScopes than the element's own
// scope, only tree-boundary-crossing rules may match.
ScopedStyleResolver* elementScopeResolver = scopedResolverFor(element);
if (!document().mayContainV0Shadow()) {
matchSlottedRules(element, collector);
matchElementScopeRules(element, elementScopeResolver, collector);
return;
}
bool matchElementScopeDone = !elementScopeResolver && !element.inlineStyle();
const auto& treeBoundaryCrossingScopes =
document().styleEngine().treeBoundaryCrossingScopes();
for (auto it = treeBoundaryCrossingScopes.rbegin();
it != treeBoundaryCrossingScopes.rend(); ++it) {
const TreeScope& scope = (*it)->containingTreeScope();
ScopedStyleResolver* resolver = scope.scopedStyleResolver();
DCHECK(resolver);
bool isInnerTreeScope =
element.containingTreeScope().isInclusiveAncestorOf(scope);
if (!shouldCheckScope(element, **it, isInnerTreeScope))
continue;
if (!matchElementScopeDone &&
scope.isInclusiveAncestorOf(element.containingTreeScope())) {
matchElementScopeDone = true;
// At this point, the iterator has either encountered the scope for the
// element itself (if that scope has boundary-crossing rules), or the
// iterator has moved to a scope which appears before the element's scope
// in the tree-of-trees order. Try to match all rules from the element's
// scope.
matchElementScopeRules(element, elementScopeResolver, collector);
if (resolver == elementScopeResolver) {
// Boundary-crossing rules already collected in matchElementScopeRules.
continue;
}
}
collector.clearMatchedRules();
resolver->collectMatchingTreeBoundaryCrossingRules(collector);
collector.sortAndTransferMatchedRules();
collector.finishAddingAuthorRulesForTreeScope();
}
if (!matchElementScopeDone)
matchElementScopeRules(element, elementScopeResolver, collector);
}
void StyleResolver::matchAuthorRules(const Element& element,
ElementRuleCollector& collector) {
if (document().shadowCascadeOrder() != ShadowCascadeOrder::ShadowCascadeV1) {
matchAuthorRulesV0(element, collector);
return;
}
matchHostRules(element, collector);
matchScopedRules(element, collector);
}
void StyleResolver::matchAuthorRulesV0(const Element& element,
ElementRuleCollector& collector) {
collector.clearMatchedRules();
CascadeOrder cascadeOrder = 0;
HeapVector<Member<ScopedStyleResolver>, 8> resolversInShadowTree;
collectScopedResolversForHostedShadowTrees(element, resolversInShadowTree);
// Apply :host and :host-context rules from inner scopes.
for (int j = resolversInShadowTree.size() - 1; j >= 0; --j)
resolversInShadowTree.at(j)->collectMatchingShadowHostRules(collector,
++cascadeOrder);
// Apply normal rules from element scope.
if (ScopedStyleResolver* resolver = scopedResolverFor(element))
resolver->collectMatchingAuthorRules(collector, ++cascadeOrder);
// Apply /deep/ and ::shadow rules from outer scopes, and ::content from
// inner.
collectTreeBoundaryCrossingRulesV0CascadeOrder(element, collector);
collector.sortAndTransferMatchedRules();
}
void StyleResolver::matchUARules(ElementRuleCollector& collector) {
collector.setMatchingUARules(true);
CSSDefaultStyleSheets& defaultStyleSheets = CSSDefaultStyleSheets::instance();
RuleSet* userAgentStyleSheet = m_printMediaType
? defaultStyleSheets.defaultPrintStyle()
: defaultStyleSheets.defaultStyle();
matchRuleSet(collector, userAgentStyleSheet);
// In quirks mode, we match rules from the quirks user agent sheet.
if (document().inQuirksMode())
matchRuleSet(collector, defaultStyleSheets.defaultQuirksStyle());
// If document uses view source styles (in view source mode or in xml viewer
// mode), then we match rules from the view source style sheet.
if (document().isViewSource())
matchRuleSet(collector, defaultStyleSheets.defaultViewSourceStyle());
collector.finishAddingUARules();
collector.setMatchingUARules(false);
}
void StyleResolver::matchRuleSet(ElementRuleCollector& collector,
RuleSet* rules) {
collector.clearMatchedRules();
collector.collectMatchingRules(MatchRequest(rules));
collector.sortAndTransferMatchedRules();
}
DISABLE_CFI_PERF
void StyleResolver::matchAllRules(StyleResolverState& state,
ElementRuleCollector& collector,
bool includeSMILProperties) {
matchUARules(collector);
// Now check author rules, beginning first with presentational attributes
// mapped from HTML.
if (state.element()->isStyledElement()) {
collector.addElementStyleProperties(
state.element()->presentationAttributeStyle());
// Now we check additional mapped declarations.
// Tables and table cells share an additional mapped rule that must be
// applied after all attributes, since their mapped style depends on the
// values of multiple attributes.
collector.addElementStyleProperties(
state.element()->additionalPresentationAttributeStyle());
if (state.element()->isHTMLElement()) {
bool isAuto;
TextDirection textDirection =
toHTMLElement(state.element())
->directionalityIfhasDirAutoAttribute(isAuto);
if (isAuto) {
state.setHasDirAutoAttribute(true);
collector.addElementStyleProperties(textDirection == TextDirection::kLtr
? leftToRightDeclaration()
: rightToLeftDeclaration());
}
}
}
matchAuthorRules(*state.element(), collector);
if (state.element()->isStyledElement()) {
// For Shadow DOM V1, inline style is already collected in
// matchScopedRules().
if (document().shadowCascadeOrder() !=
ShadowCascadeOrder::ShadowCascadeV1 &&
state.element()->inlineStyle()) {
// Inline style is immutable as long as there is no CSSOM wrapper.
bool isInlineStyleCacheable =
!state.element()->inlineStyle()->isMutable();
collector.addElementStyleProperties(state.element()->inlineStyle(),
isInlineStyleCacheable);
}
// Now check SMIL animation override style.
if (includeSMILProperties && state.element()->isSVGElement())
collector.addElementStyleProperties(
toSVGElement(state.element())->animatedSMILStyleProperties(),
false /* isCacheable */);
}
collector.finishAddingAuthorRulesForTreeScope();
}
void StyleResolver::collectTreeBoundaryCrossingRulesV0CascadeOrder(
const Element& element,
ElementRuleCollector& collector) {
const auto& treeBoundaryCrossingScopes =
document().styleEngine().treeBoundaryCrossingScopes();
if (treeBoundaryCrossingScopes.isEmpty())
return;
// When comparing rules declared in outer treescopes, outer's rules win.
CascadeOrder outerCascadeOrder = treeBoundaryCrossingScopes.size() * 2;
// When comparing rules declared in inner treescopes, inner's rules win.
CascadeOrder innerCascadeOrder = treeBoundaryCrossingScopes.size();
for (const auto& scopingNode : treeBoundaryCrossingScopes) {
// Skip rule collection for element when tree boundary crossing rules of
// scopingNode's scope can never apply to it.
bool isInnerTreeScope = element.containingTreeScope().isInclusiveAncestorOf(
scopingNode->containingTreeScope());
if (!shouldCheckScope(element, *scopingNode, isInnerTreeScope))
continue;
CascadeOrder cascadeOrder =
isInnerTreeScope ? innerCascadeOrder : outerCascadeOrder;
scopingNode->treeScope()
.scopedStyleResolver()
->collectMatchingTreeBoundaryCrossingRules(collector, cascadeOrder);
++innerCascadeOrder;
--outerCascadeOrder;
}
}
PassRefPtr<ComputedStyle> StyleResolver::styleForDocument(Document& document) {
const LocalFrame* frame = document.frame();
RefPtr<ComputedStyle> documentStyle = ComputedStyle::create();
documentStyle->setRtlOrdering(document.visuallyOrdered() ? EOrder::kVisual
: EOrder::kLogical);
documentStyle->setZoom(frame && !document.printing() ? frame->pageZoomFactor()
: 1);
FontDescription documentFontDescription = documentStyle->getFontDescription();
documentFontDescription.setLocale(
LayoutLocale::get(document.contentLanguage()));
documentStyle->setFontDescription(documentFontDescription);
documentStyle->setZIndex(0);
documentStyle->setIsStackingContext(true);
documentStyle->setUserModify(document.inDesignMode() ? READ_WRITE
: READ_ONLY);
// These are designed to match the user-agent stylesheet values for the
// document element so that the common case doesn't need to create a new
// ComputedStyle in Document::inheritHtmlAndBodyElementStyles.
documentStyle->setDisplay(EDisplay::Block);
documentStyle->setPosition(AbsolutePosition);
// Document::inheritHtmlAndBodyElementStyles will set the final overflow
// style values, but they should initially be auto to avoid premature
// scrollbar removal in PaintLayerScrollableArea::updateAfterStyleChange.
documentStyle->setOverflowX(EOverflow::Auto);
documentStyle->setOverflowY(EOverflow::Auto);
document.setupFontBuilder(*documentStyle);
return documentStyle.release();
}
void StyleResolver::adjustComputedStyle(StyleResolverState& state,
Element* element) {
StyleAdjuster::adjustComputedStyle(state.mutableStyleRef(),
*state.parentStyle(), element);
}
// Start loading resources referenced by this style.
void StyleResolver::loadPendingResources(StyleResolverState& state) {
state.elementStyleResources().loadPendingResources(state.style());
}
static const ComputedStyle* calculateBaseComputedStyle(
StyleResolverState& state,
const Element* animatingElement) {
if (!animatingElement)
return nullptr;
ElementAnimations* elementAnimations = animatingElement->elementAnimations();
if (!elementAnimations)
return nullptr;
if (CSSAnimations::isAnimatingCustomProperties(elementAnimations)) {
state.setIsAnimatingCustomProperties(true);
// TODO(alancutter): Use the base computed style optimisation in the
// presence of custom property animations that don't affect pre-animated
// computed values.
return nullptr;
}
return elementAnimations->baseComputedStyle();
}
static void updateBaseComputedStyle(StyleResolverState& state,
Element* animatingElement) {
if (!animatingElement || state.isAnimatingCustomProperties())
return;
ElementAnimations* elementAnimations = animatingElement->elementAnimations();
if (elementAnimations)
elementAnimations->updateBaseComputedStyle(state.style());
}
PassRefPtr<ComputedStyle> StyleResolver::styleForElement(
Element* element,
const ComputedStyle* defaultParent,
StyleSharingBehavior sharingBehavior,
RuleMatchingBehavior matchingBehavior) {
DCHECK(document().frame());
DCHECK(document().settings());
// Once an element has a layoutObject, we don't try to destroy it, since
// otherwise the layoutObject will vanish if a style recalc happens during
// loading.
if (sharingBehavior == AllowStyleSharing && !document().isRenderingReady() &&
!element->layoutObject()) {
if (!s_styleNotYetAvailable) {
s_styleNotYetAvailable = ComputedStyle::create().leakRef();
s_styleNotYetAvailable->setDisplay(EDisplay::None);
s_styleNotYetAvailable->font().update(
document().styleEngine().fontSelector());
}
document().setHasNodesWithPlaceholderStyle();
return s_styleNotYetAvailable;
}
document().styleEngine().incStyleForElementCount();
INCREMENT_STYLE_STATS_COUNTER(document().styleEngine(), elementsStyled, 1);
SelectorFilterParentScope::ensureParentStackIsPushed();
ElementResolveContext elementContext(*element);
if (RuntimeEnabledFeatures::styleSharingEnabled() &&
sharingBehavior == AllowStyleSharing &&
(defaultParent || elementContext.parentStyle())) {
if (RefPtr<ComputedStyle> sharedStyle =
document().styleEngine().findSharedStyle(elementContext))
return sharedStyle.release();
}
StyleResolverState state(document(), elementContext, defaultParent);
const ComputedStyle* baseComputedStyle =
calculateBaseComputedStyle(state, element);
if (baseComputedStyle) {
state.setStyle(ComputedStyle::clone(*baseComputedStyle));
if (!state.parentStyle())
state.setParentStyle(initialStyleForElement());
} else {
if (state.parentStyle()) {
RefPtr<ComputedStyle> style = ComputedStyle::create();
style->inheritFrom(*state.parentStyle(),
isAtShadowBoundary(element)
? ComputedStyleBase::AtShadowBoundary
: ComputedStyleBase::NotAtShadowBoundary);
state.setStyle(std::move(style));
} else {
state.setStyle(initialStyleForElement());
state.setParentStyle(ComputedStyle::clone(*state.style()));
}
}
// contenteditable attribute (implemented by -webkit-user-modify) should
// be propagated from shadow host to distributed node.
if (state.distributedToInsertionPoint()) {
if (Element* parent = element->parentElement()) {
if (ComputedStyle* styleOfShadowHost = parent->mutableComputedStyle())
state.style()->setUserModify(styleOfShadowHost->userModify());
}
}
if (element->isLink()) {
state.style()->setIsLink(true);
EInsideLink linkState = state.elementLinkState();
if (linkState != EInsideLink::kNotInsideLink) {
bool forceVisited = InspectorInstrumentation::forcePseudoState(
element, CSSSelector::PseudoVisited);
if (forceVisited)
linkState = EInsideLink::kInsideVisitedLink;
}
state.style()->setInsideLink(linkState);
}
if (!baseComputedStyle) {
document().styleEngine().ensureUAStyleForElement(*element);
ElementRuleCollector collector(state.elementContext(), m_selectorFilter,
state.style());
matchAllRules(state, collector,
matchingBehavior != MatchAllRulesExcludingSMIL);
// TODO(dominicc): Remove this counter when Issue 590014 is fixed.
if (element->hasTagName(HTMLNames::summaryTag)) {
MatchedPropertiesRange properties =
collector.matchedResult().authorRules();
for (auto it = properties.begin(); it != properties.end(); ++it) {
const CSSValue* value =
it->properties->getPropertyCSSValue(CSSPropertyDisplay);
if (value && value->isIdentifierValue() &&
toCSSIdentifierValue(*value).getValueID() == CSSValueBlock)
UseCounter::count(
element->document(),
UseCounter::SummaryElementWithDisplayBlockAuthorRule);
}
}
if (m_tracker)
addMatchedRulesToTracker(collector);
if (element->computedStyle() &&
element->computedStyle()->textAutosizingMultiplier() !=
state.style()->textAutosizingMultiplier()) {
// Preserve the text autosizing multiplier on style recalc. Autosizer will
// update it during layout if needed.
// NOTE: this must occur before applyMatchedProperties for correct
// computation of font-relative lengths.
state.style()->setTextAutosizingMultiplier(
element->computedStyle()->textAutosizingMultiplier());
state.style()->setUnique();
}
if (state.hasDirAutoAttribute())
state.style()->setSelfOrAncestorHasDirAutoAttribute(true);
applyMatchedPropertiesAndCustomPropertyAnimations(
state, collector.matchedResult(), element);
applyCallbackSelectors(state);
// Cache our original display.
state.style()->setOriginalDisplay(state.style()->display());
adjustComputedStyle(state, element);
updateBaseComputedStyle(state, element);
} else {
INCREMENT_STYLE_STATS_COUNTER(document().styleEngine(), baseStylesUsed, 1);
}
// FIXME: The CSSWG wants to specify that the effects of animations are
// applied before important rules, but this currently happens here as we
// require adjustment to have happened before deciding which properties to
// transition.
if (applyAnimatedStandardProperties(state, element)) {
INCREMENT_STYLE_STATS_COUNTER(document().styleEngine(), stylesAnimated, 1);
adjustComputedStyle(state, element);
}
if (isHTMLBodyElement(*element))
document().textLinkColors().setTextColor(state.style()->color());
setAnimationUpdateIfNeeded(state, *element);
if (state.style()->hasViewportUnits())
document().setHasViewportUnits();
if (state.style()->hasRemUnits())
document().styleEngine().setUsesRemUnit(true);
// Now return the style.
return state.takeStyle();
}
// TODO(alancutter): Create compositor keyframe values directly instead of
// intermediate AnimatableValues.
PassRefPtr<AnimatableValue> StyleResolver::createAnimatableValueSnapshot(
Element& element,
const ComputedStyle& baseStyle,
const ComputedStyle* parentStyle,
CSSPropertyID property,
const CSSValue* value) {
// TODO(alancutter): Avoid creating a StyleResolverState just to apply a
// single value on a ComputedStyle.
StyleResolverState state(element.document(), &element, parentStyle);
state.setStyle(ComputedStyle::clone(baseStyle));
if (value) {
StyleBuilder::applyProperty(property, state, *value);
state.fontBuilder().createFont(
state.document().styleEngine().fontSelector(), state.mutableStyleRef());
}
return CSSAnimatableValueFactory::create(property, *state.style());
}
PseudoElement* StyleResolver::createPseudoElement(Element* parent,
PseudoId pseudoId) {
if (pseudoId == PseudoIdFirstLetter)
return FirstLetterPseudoElement::create(parent);
return PseudoElement::create(parent, pseudoId);
}
PseudoElement* StyleResolver::createPseudoElementIfNeeded(Element& parent,
PseudoId pseudoId) {
LayoutObject* parentLayoutObject = parent.layoutObject();
if (!parentLayoutObject)
return nullptr;
// The first letter pseudo element has to look up the tree and see if any
// of the ancestors are first letter.
if (pseudoId < FirstInternalPseudoId && pseudoId != PseudoIdFirstLetter &&
!parentLayoutObject->style()->hasPseudoStyle(pseudoId))
return nullptr;
if (pseudoId == PseudoIdBackdrop && !parent.isInTopLayer())
return nullptr;
if (pseudoId == PseudoIdFirstLetter &&
(parent.isSVGElement() ||
!FirstLetterPseudoElement::firstLetterTextLayoutObject(parent)))
return nullptr;
if (!canHaveGeneratedChildren(*parentLayoutObject))
return nullptr;
ComputedStyle* parentStyle = parentLayoutObject->mutableStyle();
if (ComputedStyle* cachedStyle =
parentStyle->getCachedPseudoStyle(pseudoId)) {
if (!pseudoElementLayoutObjectIsNeeded(cachedStyle))
return nullptr;
return createPseudoElement(&parent, pseudoId);
}
StyleResolverState state(document(), &parent, parentStyle);
if (!pseudoStyleForElementInternal(parent, pseudoId, parentStyle, state))
return nullptr;
RefPtr<ComputedStyle> style = state.takeStyle();
DCHECK(style);
parentStyle->addCachedPseudoStyle(style);
if (!pseudoElementLayoutObjectIsNeeded(style.get()))
return nullptr;
PseudoElement* pseudo = createPseudoElement(&parent, pseudoId);
setAnimationUpdateIfNeeded(state, *pseudo);
if (ElementAnimations* elementAnimations = pseudo->elementAnimations())
elementAnimations->cssAnimations().maybeApplyPendingUpdate(pseudo);
return pseudo;
}
bool StyleResolver::pseudoStyleForElementInternal(
Element& element,
const PseudoStyleRequest& pseudoStyleRequest,
const ComputedStyle* parentStyle,
StyleResolverState& state) {
DCHECK(document().frame());
DCHECK(document().settings());
DCHECK(pseudoStyleRequest.pseudoId != PseudoIdFirstLineInherited);
DCHECK(state.parentStyle());
SelectorFilterParentScope::ensureParentStackIsPushed();
Element* pseudoElement = element.pseudoElement(pseudoStyleRequest.pseudoId);
const ComputedStyle* baseComputedStyle =
calculateBaseComputedStyle(state, pseudoElement);
if (baseComputedStyle) {
state.setStyle(ComputedStyle::clone(*baseComputedStyle));
} else if (pseudoStyleRequest.allowsInheritance(state.parentStyle())) {
RefPtr<ComputedStyle> style = ComputedStyle::create();
style->inheritFrom(*state.parentStyle());
state.setStyle(std::move(style));
} else {
state.setStyle(initialStyleForElement());
state.setParentStyle(ComputedStyle::clone(*state.style()));
}
state.style()->setStyleType(pseudoStyleRequest.pseudoId);
// Since we don't use pseudo-elements in any of our quirk/print
// user agent rules, don't waste time walking those rules.
if (!baseComputedStyle) {
// Check UA, user and author rules.
ElementRuleCollector collector(state.elementContext(), m_selectorFilter,
state.style());
collector.setPseudoStyleRequest(pseudoStyleRequest);
matchUARules(collector);
matchAuthorRules(*state.element(), collector);
collector.finishAddingAuthorRulesForTreeScope();
if (m_tracker)
addMatchedRulesToTracker(collector);
if (!collector.matchedResult().hasMatchedProperties())
return false;
applyMatchedPropertiesAndCustomPropertyAnimations(
state, collector.matchedResult(), pseudoElement);
applyCallbackSelectors(state);
// Cache our original display.
state.style()->setOriginalDisplay(state.style()->display());
// FIXME: Passing 0 as the Element* introduces a lot of complexity
// in the adjustComputedStyle code.
adjustComputedStyle(state, 0);
updateBaseComputedStyle(state, pseudoElement);
}
// FIXME: The CSSWG wants to specify that the effects of animations are
// applied before important rules, but this currently happens here as we
// require adjustment to have happened before deciding which properties to
// transition.
if (applyAnimatedStandardProperties(state, pseudoElement))
adjustComputedStyle(state, 0);
document().styleEngine().incStyleForElementCount();
INCREMENT_STYLE_STATS_COUNTER(document().styleEngine(), pseudoElementsStyled,
1);
if (state.style()->hasViewportUnits())
document().setHasViewportUnits();
return true;
}
PassRefPtr<ComputedStyle> StyleResolver::pseudoStyleForElement(
Element* element,
const PseudoStyleRequest& pseudoStyleRequest,
const ComputedStyle* parentStyle) {
DCHECK(parentStyle);
if (!element)
return nullptr;
StyleResolverState state(document(), element, parentStyle);
if (!pseudoStyleForElementInternal(*element, pseudoStyleRequest, parentStyle,
state)) {
if (pseudoStyleRequest.type == PseudoStyleRequest::ForRenderer)
return nullptr;
return state.takeStyle();
}
if (PseudoElement* pseudoElement =
element->pseudoElement(pseudoStyleRequest.pseudoId))
setAnimationUpdateIfNeeded(state, *pseudoElement);
// Now return the style.
return state.takeStyle();
}
PassRefPtr<ComputedStyle> StyleResolver::styleForPage(int pageIndex) {
// m_rootElementStyle will be set to the document style.
StyleResolverState state(document(), document().documentElement());
RefPtr<ComputedStyle> style = ComputedStyle::create();
const ComputedStyle* rootElementStyle = state.rootElementStyle()
? state.rootElementStyle()
: document().computedStyle();
DCHECK(rootElementStyle);
style->inheritFrom(*rootElementStyle);
state.setStyle(std::move(style));
PageRuleCollector collector(rootElementStyle, pageIndex);
collector.matchPageRules(
CSSDefaultStyleSheets::instance().defaultPrintStyle());
if (ScopedStyleResolver* scopedResolver = document().scopedStyleResolver())
scopedResolver->matchPageRules(collector);
bool inheritedOnly = false;
NeedsApplyPass needsApplyPass;
const MatchResult& result = collector.matchedResult();
applyMatchedProperties<AnimationPropertyPriority, UpdateNeedsApplyPass>(
state, result.allRules(), false, inheritedOnly, needsApplyPass);
applyMatchedProperties<HighPropertyPriority, CheckNeedsApplyPass>(
state, result.allRules(), false, inheritedOnly, needsApplyPass);
// If our font got dirtied, go ahead and update it now.
updateFont(state);
applyMatchedProperties<LowPropertyPriority, CheckNeedsApplyPass>(
state, result.allRules(), false, inheritedOnly, needsApplyPass);
loadPendingResources(state);
// Now return the style.
return state.takeStyle();
}
PassRefPtr<ComputedStyle> StyleResolver::initialStyleForElement() {
RefPtr<ComputedStyle> style = ComputedStyle::create();
FontBuilder fontBuilder(document());
fontBuilder.setInitial(style->effectiveZoom());
fontBuilder.createFont(document().styleEngine().fontSelector(), *style);
return style.release();
}
PassRefPtr<ComputedStyle> StyleResolver::styleForText(Text* textNode) {
DCHECK(textNode);
Node* parentNode = LayoutTreeBuilderTraversal::parent(*textNode);
if (!parentNode || !parentNode->computedStyle())
return initialStyleForElement();
return parentNode->mutableComputedStyle();
}
void StyleResolver::updateFont(StyleResolverState& state) {
state.fontBuilder().createFont(document().styleEngine().fontSelector(),
state.mutableStyleRef());
state.setConversionFontSizes(CSSToLengthConversionData::FontSizes(
state.style(), state.rootElementStyle()));
state.setConversionZoom(state.style()->effectiveZoom());
}
void StyleResolver::addMatchedRulesToTracker(
const ElementRuleCollector& collector) {
collector.addMatchedRulesToTracker(m_tracker);
}
StyleRuleList* StyleResolver::styleRulesForElement(Element* element,
unsigned rulesToInclude) {
DCHECK(element);
StyleResolverState state(document(), element);
ElementRuleCollector collector(state.elementContext(), m_selectorFilter,
state.style());
collector.setMode(SelectorChecker::CollectingStyleRules);
collectPseudoRulesForElement(*element, collector, PseudoIdNone,
rulesToInclude);
return collector.matchedStyleRuleList();
}
CSSRuleList* StyleResolver::pseudoCSSRulesForElement(Element* element,
PseudoId pseudoId,
unsigned rulesToInclude) {
DCHECK(element);
StyleResolverState state(document(), element);
ElementRuleCollector collector(state.elementContext(), m_selectorFilter,
state.style());
collector.setMode(SelectorChecker::CollectingCSSRules);
collectPseudoRulesForElement(*element, collector, pseudoId, rulesToInclude);
if (m_tracker)
addMatchedRulesToTracker(collector);
return collector.matchedCSSRuleList();
}
CSSRuleList* StyleResolver::cssRulesForElement(Element* element,
unsigned rulesToInclude) {
return pseudoCSSRulesForElement(element, PseudoIdNone, rulesToInclude);
}
void StyleResolver::collectPseudoRulesForElement(
const Element& element,
ElementRuleCollector& collector,
PseudoId pseudoId,
unsigned rulesToInclude) {
collector.setPseudoStyleRequest(PseudoStyleRequest(pseudoId));
if (rulesToInclude & UAAndUserCSSRules)
matchUARules(collector);
if (rulesToInclude & AuthorCSSRules) {
collector.setSameOriginOnly(!(rulesToInclude & CrossOriginCSSRules));
collector.setIncludeEmptyRules(rulesToInclude & EmptyCSSRules);
matchAuthorRules(element, collector);
}
}
bool StyleResolver::applyAnimatedStandardProperties(
StyleResolverState& state,
const Element* animatingElement) {
Element* element = state.element();
DCHECK(element);
// The animating element may be this element, or its pseudo element. It is
// null when calculating the style for a potential pseudo element that has
// yet to be created.
DCHECK(animatingElement == element || !animatingElement ||
animatingElement->parentOrShadowHostElement() == element);
if (state.style()->animations() ||
(animatingElement && animatingElement->hasAnimations())) {
if (!state.isAnimationInterpolationMapReady())
calculateAnimationUpdate(state, animatingElement);
} else if (!state.style()->transitions()) {
return false;
}
CSSAnimations::calculateCompositorAnimationUpdate(
state.animationUpdate(), animatingElement, *element, *state.style(),
state.parentStyle(), wasViewportResized());
CSSAnimations::calculateTransitionUpdate(state.animationUpdate(),
animatingElement, *state.style());
CSSAnimations::snapshotCompositorKeyframes(
*element, state.animationUpdate(), *state.style(), state.parentStyle());
if (state.animationUpdate().isEmpty())
return false;
if (state.style()->insideLink() != EInsideLink::kNotInsideLink) {
DCHECK(state.applyPropertyToRegularStyle());
state.setApplyPropertyToVisitedLinkStyle(true);
}
const ActiveInterpolationsMap& activeInterpolationsMapForAnimations =
state.animationUpdate().activeInterpolationsForAnimations();
const ActiveInterpolationsMap& activeInterpolationsMapForTransitions =
state.animationUpdate().activeInterpolationsForTransitions();
// TODO(crbug.com/644148): Apply animations on custom properties.
applyAnimatedProperties<HighPropertyPriority>(
state, activeInterpolationsMapForAnimations);
applyAnimatedProperties<HighPropertyPriority>(
state, activeInterpolationsMapForTransitions);
updateFont(state);
applyAnimatedProperties<LowPropertyPriority>(
state, activeInterpolationsMapForAnimations);
applyAnimatedProperties<LowPropertyPriority>(
state, activeInterpolationsMapForTransitions);
// Start loading resources used by animations.
loadPendingResources(state);
DCHECK(!state.fontBuilder().fontDirty());
state.setApplyPropertyToVisitedLinkStyle(false);
return true;
}
StyleRuleKeyframes* StyleResolver::findKeyframesRule(
const Element* element,
const AtomicString& animationName) {
HeapVector<Member<ScopedStyleResolver>, 8> resolvers;
collectScopedResolversForHostedShadowTrees(*element, resolvers);
if (ScopedStyleResolver* scopedResolver =
element->treeScope().scopedStyleResolver())
resolvers.push_back(scopedResolver);
for (auto& resolver : resolvers) {
if (StyleRuleKeyframes* keyframesRule =
resolver->keyframeStylesForAnimation(animationName.impl()))
return keyframesRule;
}
for (auto& resolver : resolvers)
resolver->setHasUnresolvedKeyframesRule();
return nullptr;
}
template <CSSPropertyPriority priority>
void StyleResolver::applyAnimatedProperties(
StyleResolverState& state,
const ActiveInterpolationsMap& activeInterpolationsMap) {
// TODO(alancutter): Don't apply presentation attribute animations here,
// they should instead apply in
// SVGElement::collectStyleForPresentationAttribute().
for (const auto& entry : activeInterpolationsMap) {
CSSPropertyID property = entry.key.isCSSProperty()
? entry.key.cssProperty()
: entry.key.presentationAttribute();
if (!CSSPropertyPriorityData<priority>::propertyHasPriority(property))
continue;
const Interpolation& interpolation = *entry.value.front();
if (interpolation.isInvalidatableInterpolation()) {
CSSInterpolationTypesMap map(state.document().propertyRegistry());
InterpolationEnvironment environment(map, state);
InvalidatableInterpolation::applyStack(entry.value, environment);
} else {
// TODO(alancutter): Remove this old code path once animations have
// completely migrated to InterpolationTypes.
toLegacyStyleInterpolation(interpolation).apply(state);
}
}
}
static inline bool isValidCueStyleProperty(CSSPropertyID id) {
switch (id) {
case CSSPropertyBackground:
case CSSPropertyBackgroundAttachment:
case CSSPropertyBackgroundClip:
case CSSPropertyBackgroundColor:
case CSSPropertyBackgroundImage:
case CSSPropertyBackgroundOrigin:
case CSSPropertyBackgroundPosition:
case CSSPropertyBackgroundPositionX:
case CSSPropertyBackgroundPositionY:
case CSSPropertyBackgroundRepeat:
case CSSPropertyBackgroundRepeatX:
case CSSPropertyBackgroundRepeatY:
case CSSPropertyBackgroundSize:
case CSSPropertyColor:
case CSSPropertyFont:
case CSSPropertyFontFamily:
case CSSPropertyFontSize:
case CSSPropertyFontStretch:
case CSSPropertyFontStyle:
case CSSPropertyFontVariant:
case CSSPropertyFontWeight:
case CSSPropertyLineHeight:
case CSSPropertyOpacity:
case CSSPropertyOutline:
case CSSPropertyOutlineColor:
case CSSPropertyOutlineOffset:
case CSSPropertyOutlineStyle:
case CSSPropertyOutlineWidth:
case CSSPropertyVisibility:
case CSSPropertyWhiteSpace:
// FIXME: 'text-decoration' shorthand to be handled when available.
// See https://chromiumcodereview.appspot.com/19516002 for details.
case CSSPropertyTextDecoration:
case CSSPropertyTextShadow:
case CSSPropertyBorderStyle:
return true;
case CSSPropertyTextDecorationLine:
case CSSPropertyTextDecorationStyle:
case CSSPropertyTextDecorationColor:
case CSSPropertyTextDecorationSkip:
DCHECK(RuntimeEnabledFeatures::css3TextDecorationsEnabled());
return true;
case CSSPropertyFontVariationSettings:
DCHECK(RuntimeEnabledFeatures::cssVariableFontsEnabled());
return true;
default:
break;
}
return false;
}
static inline bool isValidFirstLetterStyleProperty(CSSPropertyID id) {
switch (id) {
// Valid ::first-letter properties listed in spec:
// http://www.w3.org/TR/css3-selectors/#application-in-css
case CSSPropertyBackgroundAttachment:
case CSSPropertyBackgroundBlendMode:
case CSSPropertyBackgroundClip:
case CSSPropertyBackgroundColor:
case CSSPropertyBackgroundImage:
case CSSPropertyBackgroundOrigin:
case CSSPropertyBackgroundPosition:
case CSSPropertyBackgroundPositionX:
case CSSPropertyBackgroundPositionY:
case CSSPropertyBackgroundRepeat:
case CSSPropertyBackgroundRepeatX:
case CSSPropertyBackgroundRepeatY:
case CSSPropertyBackgroundSize:
case CSSPropertyBorderBottomColor:
case CSSPropertyBorderBottomLeftRadius:
case CSSPropertyBorderBottomRightRadius:
case CSSPropertyBorderBottomStyle:
case CSSPropertyBorderBottomWidth:
case CSSPropertyBorderImageOutset:
case CSSPropertyBorderImageRepeat:
case CSSPropertyBorderImageSlice:
case CSSPropertyBorderImageSource:
case CSSPropertyBorderImageWidth:
case CSSPropertyBorderLeftColor:
case CSSPropertyBorderLeftStyle:
case CSSPropertyBorderLeftWidth:
case CSSPropertyBorderRightColor:
case CSSPropertyBorderRightStyle:
case CSSPropertyBorderRightWidth:
case CSSPropertyBorderTopColor:
case CSSPropertyBorderTopLeftRadius:
case CSSPropertyBorderTopRightRadius:
case CSSPropertyBorderTopStyle:
case CSSPropertyBorderTopWidth:
case CSSPropertyColor:
case CSSPropertyFloat:
case CSSPropertyFont:
case CSSPropertyFontFamily:
case CSSPropertyFontKerning:
case CSSPropertyFontSize:
case CSSPropertyFontStretch:
case CSSPropertyFontStyle:
case CSSPropertyFontVariant:
case CSSPropertyFontVariantCaps:
case CSSPropertyFontVariantLigatures:
case CSSPropertyFontVariantNumeric:
case CSSPropertyFontWeight:
case CSSPropertyLetterSpacing:
case CSSPropertyLineHeight:
case CSSPropertyMarginBottom:
case CSSPropertyMarginLeft:
case CSSPropertyMarginRight:
case CSSPropertyMarginTop:
case CSSPropertyPaddingBottom:
case CSSPropertyPaddingLeft:
case CSSPropertyPaddingRight:
case CSSPropertyPaddingTop:
case CSSPropertyTextTransform:
case CSSPropertyVerticalAlign:
case CSSPropertyWebkitBackgroundClip:
case CSSPropertyWebkitBackgroundOrigin:
case CSSPropertyWebkitBorderAfter:
case CSSPropertyWebkitBorderAfterColor:
case CSSPropertyWebkitBorderAfterStyle:
case CSSPropertyWebkitBorderAfterWidth:
case CSSPropertyWebkitBorderBefore:
case CSSPropertyWebkitBorderBeforeColor:
case CSSPropertyWebkitBorderBeforeStyle:
case CSSPropertyWebkitBorderBeforeWidth:
case CSSPropertyWebkitBorderEnd:
case CSSPropertyWebkitBorderEndColor:
case CSSPropertyWebkitBorderEndStyle:
case CSSPropertyWebkitBorderEndWidth:
case CSSPropertyWebkitBorderHorizontalSpacing:
case CSSPropertyWebkitBorderImage:
case CSSPropertyWebkitBorderStart:
case CSSPropertyWebkitBorderStartColor:
case CSSPropertyWebkitBorderStartStyle:
case CSSPropertyWebkitBorderStartWidth:
case CSSPropertyWebkitBorderVerticalSpacing:
case CSSPropertyWebkitFontSmoothing:
case CSSPropertyWebkitMarginAfter:
case CSSPropertyWebkitMarginAfterCollapse:
case CSSPropertyWebkitMarginBefore:
case CSSPropertyWebkitMarginBeforeCollapse:
case CSSPropertyWebkitMarginBottomCollapse:
case CSSPropertyWebkitMarginCollapse:
case CSSPropertyWebkitMarginEnd:
case CSSPropertyWebkitMarginStart:
case CSSPropertyWebkitMarginTopCollapse:
case CSSPropertyWordSpacing:
return true;
case CSSPropertyFontVariationSettings:
DCHECK(RuntimeEnabledFeatures::cssVariableFontsEnabled());
return true;
case CSSPropertyTextDecoration:
DCHECK(!RuntimeEnabledFeatures::css3TextDecorationsEnabled());
return true;
case CSSPropertyTextDecorationColor:
case CSSPropertyTextDecorationLine:
case CSSPropertyTextDecorationStyle:
case CSSPropertyTextDecorationSkip:
DCHECK(RuntimeEnabledFeatures::css3TextDecorationsEnabled());
return true;
// text-shadow added in text decoration spec:
// http://www.w3.org/TR/css-text-decor-3/#text-shadow-property
case CSSPropertyTextShadow:
// box-shadox added in CSS3 backgrounds spec:
// http://www.w3.org/TR/css3-background/#placement
case CSSPropertyBoxShadow:
// Properties that we currently support outside of spec.
case CSSPropertyVisibility:
return true;
default:
return false;
}
}
static bool shouldIgnoreTextTrackAuthorStyle(const Document& document) {
Settings* settings = document.settings();
if (!settings)
return false;
// Ignore author specified settings for text tracks when any of the user
// settings are present.
if (!settings->getTextTrackBackgroundColor().isEmpty() ||
!settings->getTextTrackFontFamily().isEmpty() ||
!settings->getTextTrackFontStyle().isEmpty() ||
!settings->getTextTrackFontVariant().isEmpty() ||
!settings->getTextTrackTextColor().isEmpty() ||
!settings->getTextTrackTextShadow().isEmpty() ||
!settings->getTextTrackTextSize().isEmpty())
return true;
return false;
}
static inline bool isPropertyInWhitelist(
PropertyWhitelistType propertyWhitelistType,
CSSPropertyID property,
const Document& document) {
if (propertyWhitelistType == PropertyWhitelistNone)
return true; // Early bail for the by far most common case.
if (propertyWhitelistType == PropertyWhitelistFirstLetter)
return isValidFirstLetterStyleProperty(property);
if (propertyWhitelistType == PropertyWhitelistCue)
return isValidCueStyleProperty(property) &&
!shouldIgnoreTextTrackAuthorStyle(document);
NOTREACHED();
return true;
}
// This method expands the 'all' shorthand property to longhand properties
// and applies the expanded longhand properties.
template <CSSPropertyPriority priority>
void StyleResolver::applyAllProperty(
StyleResolverState& state,
const CSSValue& allValue,
bool inheritedOnly,
PropertyWhitelistType propertyWhitelistType) {
// The 'all' property doesn't apply to variables:
// https://drafts.csswg.org/css-variables/#defining-variables
if (priority == ResolveVariables)
return;
unsigned startCSSProperty = CSSPropertyPriorityData<priority>::first();
unsigned endCSSProperty = CSSPropertyPriorityData<priority>::last();
for (unsigned i = startCSSProperty; i <= endCSSProperty; ++i) {
CSSPropertyID propertyId = static_cast<CSSPropertyID>(i);
// StyleBuilder does not allow any expanded shorthands.
if (isShorthandProperty(propertyId))
continue;
// all shorthand spec says:
// The all property is a shorthand that resets all CSS properties
// except direction and unicode-bidi.
// c.f. http://dev.w3.org/csswg/css-cascade/#all-shorthand
// We skip applyProperty when a given property is unicode-bidi or
// direction.
if (!CSSProperty::isAffectedByAllProperty(propertyId))
continue;
if (!isPropertyInWhitelist(propertyWhitelistType, propertyId, document()))
continue;
// When hitting matched properties' cache, only inherited properties will be
// applied.
if (inheritedOnly && !CSSPropertyMetadata::isInheritedProperty(propertyId))
continue;
StyleBuilder::applyProperty(propertyId, state, allValue);
}
}
template <CSSPropertyPriority priority,
StyleResolver::ShouldUpdateNeedsApplyPass shouldUpdateNeedsApplyPass>
void StyleResolver::applyPropertiesForApplyAtRule(
StyleResolverState& state,
const CSSValue& value,
bool isImportant,
NeedsApplyPass& needsApplyPass,
PropertyWhitelistType propertyWhitelistType) {
state.style()->setHasVariableReferenceFromNonInheritedProperty();
if (!state.style()->inheritedVariables())
return;
const String& name = toCSSCustomIdentValue(value).value();
const StylePropertySet* propertySet =
state.customPropertySetForApplyAtRule(name);
bool inheritedOnly = false;
if (propertySet) {
applyProperties<priority, shouldUpdateNeedsApplyPass>(
state, propertySet, isImportant, inheritedOnly, needsApplyPass,
propertyWhitelistType);
}
}
template <CSSPropertyPriority priority,
StyleResolver::ShouldUpdateNeedsApplyPass shouldUpdateNeedsApplyPass>
void StyleResolver::applyProperties(
StyleResolverState& state,
const StylePropertySet* properties,
bool isImportant,
bool inheritedOnly,
NeedsApplyPass& needsApplyPass,
PropertyWhitelistType propertyWhitelistType) {
unsigned propertyCount = properties->propertyCount();
for (unsigned i = 0; i < propertyCount; ++i) {
StylePropertySet::PropertyReference current = properties->propertyAt(i);
CSSPropertyID property = current.id();
if (property == CSSPropertyApplyAtRule) {
DCHECK(!inheritedOnly);
applyPropertiesForApplyAtRule<priority, shouldUpdateNeedsApplyPass>(
state, current.value(), isImportant, needsApplyPass,
propertyWhitelistType);
continue;
}
if (property == CSSPropertyAll && isImportant == current.isImportant()) {
if (shouldUpdateNeedsApplyPass) {
needsApplyPass.set(AnimationPropertyPriority, isImportant);
needsApplyPass.set(HighPropertyPriority, isImportant);
needsApplyPass.set(LowPropertyPriority, isImportant);
}
applyAllProperty<priority>(state, current.value(), inheritedOnly,
propertyWhitelistType);
continue;
}
if (shouldUpdateNeedsApplyPass)
needsApplyPass.set(priorityForProperty(property), current.isImportant());
if (isImportant != current.isImportant())
continue;
if (!isPropertyInWhitelist(propertyWhitelistType, property, document()))
continue;
if (inheritedOnly && !current.isInherited()) {
// If the property value is explicitly inherited, we need to apply further
// non-inherited properties as they might override the value inherited
// here. For this reason we don't allow declarations with explicitly
// inherited properties to be cached.
DCHECK(!current.value().isInheritedValue());
continue;
}
if (!CSSPropertyPriorityData<priority>::propertyHasPriority(property))
continue;
StyleBuilder::applyProperty(property, state, current.value());
}
}
template <CSSPropertyPriority priority,
StyleResolver::ShouldUpdateNeedsApplyPass shouldUpdateNeedsApplyPass>
void StyleResolver::applyMatchedProperties(StyleResolverState& state,
const MatchedPropertiesRange& range,
bool isImportant,
bool inheritedOnly,
NeedsApplyPass& needsApplyPass) {
if (range.isEmpty())
return;
if (!shouldUpdateNeedsApplyPass && !needsApplyPass.get(priority, isImportant))
return;
if (state.style()->insideLink() != EInsideLink::kNotInsideLink) {
for (const auto& matchedProperties : range) {
unsigned linkMatchType = matchedProperties.m_types.linkMatchType;
// FIXME: It would be nicer to pass these as arguments but that requires
// changes in many places.
state.setApplyPropertyToRegularStyle(linkMatchType &
CSSSelector::MatchLink);
state.setApplyPropertyToVisitedLinkStyle(linkMatchType &
CSSSelector::MatchVisited);
applyProperties<priority, shouldUpdateNeedsApplyPass>(
state, matchedProperties.properties.get(), isImportant, inheritedOnly,
needsApplyPass, static_cast<PropertyWhitelistType>(
matchedProperties.m_types.whitelistType));
}
state.setApplyPropertyToRegularStyle(true);
state.setApplyPropertyToVisitedLinkStyle(false);
return;
}
for (const auto& matchedProperties : range) {
applyProperties<priority, shouldUpdateNeedsApplyPass>(
state, matchedProperties.properties.get(), isImportant, inheritedOnly,
needsApplyPass, static_cast<PropertyWhitelistType>(
matchedProperties.m_types.whitelistType));
}
}
static unsigned computeMatchedPropertiesHash(
const MatchedProperties* properties,
unsigned size) {
return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
}
void StyleResolver::invalidateMatchedPropertiesCache() {
m_matchedPropertiesCache.clear();
}
void StyleResolver::setResizedForViewportUnits() {
DCHECK(!m_wasViewportResized);
m_wasViewportResized = true;
document().styleEngine().updateActiveStyle();
m_matchedPropertiesCache.clearViewportDependent();
}
void StyleResolver::clearResizedForViewportUnits() {
m_wasViewportResized = false;
}
void StyleResolver::applyMatchedPropertiesAndCustomPropertyAnimations(
StyleResolverState& state,
const MatchResult& matchResult,
const Element* animatingElement) {
CacheSuccess cacheSuccess = applyMatchedCache(state, matchResult);
NeedsApplyPass needsApplyPass;
if (!cacheSuccess.isFullCacheHit()) {
applyCustomProperties(state, matchResult, false, cacheSuccess,
needsApplyPass);
applyMatchedAnimationProperties(state, matchResult, cacheSuccess,
needsApplyPass);
}
if (state.style()->animations() ||
(animatingElement && animatingElement->hasAnimations())) {
calculateAnimationUpdate(state, animatingElement);
if (state.isAnimatingCustomProperties()) {
cacheSuccess.setFailed();
applyCustomProperties(state, matchResult, true, cacheSuccess,
needsApplyPass);
}
}
if (!cacheSuccess.isFullCacheHit()) {
applyMatchedStandardProperties(state, matchResult, cacheSuccess,
needsApplyPass);
}
}
StyleResolver::CacheSuccess StyleResolver::applyMatchedCache(
StyleResolverState& state,
const MatchResult& matchResult) {
const Element* element = state.element();
DCHECK(element);
unsigned cacheHash =
matchResult.isCacheable()
? computeMatchedPropertiesHash(matchResult.matchedProperties().data(),
matchResult.matchedProperties().size())
: 0;
bool isInheritedCacheHit = false;
bool isNonInheritedCacheHit = false;
const CachedMatchedProperties* cachedMatchedProperties =
cacheHash
? m_matchedPropertiesCache.find(cacheHash, state,
matchResult.matchedProperties())
: nullptr;
if (cachedMatchedProperties && MatchedPropertiesCache::isCacheable(state)) {
INCREMENT_STYLE_STATS_COUNTER(document().styleEngine(),
matchedPropertyCacheHit, 1);
// We can build up the style by copying non-inherited properties from an
// earlier style object built using the same exact style declarations. We
// then only need to apply the inherited properties, if any, as their values
// can depend on the element context. This is fast and saves memory by
// reusing the style data structures.
state.style()->copyNonInheritedFromCached(
*cachedMatchedProperties->computedStyle);
if (state.parentStyle()->inheritedDataShared(
*cachedMatchedProperties->parentComputedStyle) &&
!isAtShadowBoundary(element) &&
(!state.distributedToInsertionPoint() ||
state.style()->userModify() == READ_ONLY)) {
INCREMENT_STYLE_STATS_COUNTER(document().styleEngine(),
matchedPropertyCacheInheritedHit, 1);
EInsideLink linkStatus = state.style()->insideLink();
// If the cache item parent style has identical inherited properties to
// the current parent style then the resulting style will be identical
// too. We copy the inherited properties over from the cache and are done.
state.style()->inheritFrom(*cachedMatchedProperties->computedStyle);
// Unfortunately the link status is treated like an inherited property. We
// need to explicitly restore it.
state.style()->setInsideLink(linkStatus);
updateFont(state);
isInheritedCacheHit = true;
}
isNonInheritedCacheHit = true;
}
return CacheSuccess(isInheritedCacheHit, isNonInheritedCacheHit, cacheHash,
cachedMatchedProperties);
}
void StyleResolver::applyCustomProperties(StyleResolverState& state,
const MatchResult& matchResult,
bool applyAnimations,
const CacheSuccess& cacheSuccess,
NeedsApplyPass& needsApplyPass) {
DCHECK(!cacheSuccess.isFullCacheHit());
bool applyInheritedOnly = cacheSuccess.shouldApplyInheritedOnly();
// TODO(leviw): We need the proper bit for tracking whether we need to do
// this work.
applyMatchedProperties<ResolveVariables, UpdateNeedsApplyPass>(
state, matchResult.authorRules(), false, applyInheritedOnly,
needsApplyPass);
applyMatchedProperties<ResolveVariables, CheckNeedsApplyPass>(
state, matchResult.authorRules(), true, applyInheritedOnly,
needsApplyPass);
if (applyAnimations) {
applyAnimatedProperties<ResolveVariables>(
state, state.animationUpdate().activeInterpolationsForAnimations());
}
// TODO(leviw): stop recalculating every time
CSSVariableResolver::resolveVariableDefinitions(state);
if (RuntimeEnabledFeatures::cssApplyAtRulesEnabled()) {
if (cacheCustomPropertiesForApplyAtRules(state,
matchResult.authorRules())) {
applyMatchedProperties<ResolveVariables, UpdateNeedsApplyPass>(
state, matchResult.authorRules(), false, applyInheritedOnly,
needsApplyPass);
applyMatchedProperties<ResolveVariables, CheckNeedsApplyPass>(
state, matchResult.authorRules(), true, applyInheritedOnly,
needsApplyPass);
if (applyAnimations) {
applyAnimatedProperties<ResolveVariables>(
state, state.animationUpdate().activeInterpolationsForAnimations());
}
CSSVariableResolver::resolveVariableDefinitions(state);
}
}
}
void StyleResolver::applyMatchedAnimationProperties(
StyleResolverState& state,
const MatchResult& matchResult,
const CacheSuccess& cacheSuccess,
NeedsApplyPass& needsApplyPass) {
DCHECK(!cacheSuccess.isFullCacheHit());
bool applyInheritedOnly = cacheSuccess.shouldApplyInheritedOnly();
applyMatchedProperties<AnimationPropertyPriority, UpdateNeedsApplyPass>(
state, matchResult.allRules(), false, applyInheritedOnly, needsApplyPass);
applyMatchedProperties<AnimationPropertyPriority, CheckNeedsApplyPass>(
state, matchResult.allRules(), true, applyInheritedOnly, needsApplyPass);
}
void StyleResolver::calculateAnimationUpdate(StyleResolverState& state,
const Element* animatingElement) {
DCHECK(state.style()->animations() ||
(animatingElement && animatingElement->hasAnimations()));
DCHECK(!state.isAnimationInterpolationMapReady());
CSSAnimations::calculateAnimationUpdate(
state.animationUpdate(), animatingElement, *state.element(),
*state.style(), state.parentStyle(), this);
state.setIsAnimationInterpolationMapReady();
if (state.isAnimatingCustomProperties())
return;
for (const auto& propertyHandle :
state.animationUpdate().activeInterpolationsForAnimations().keys()) {
if (CSSAnimations::isCustomPropertyHandle(propertyHandle)) {
state.setIsAnimatingCustomProperties(true);
return;
}
}
}
void StyleResolver::applyMatchedStandardProperties(
StyleResolverState& state,
const MatchResult& matchResult,
const CacheSuccess& cacheSuccess,
NeedsApplyPass& needsApplyPass) {
INCREMENT_STYLE_STATS_COUNTER(document().styleEngine(), matchedPropertyApply,
1);
DCHECK(!cacheSuccess.isFullCacheHit());
bool applyInheritedOnly = cacheSuccess.shouldApplyInheritedOnly();
// Now we have all of the matched rules in the appropriate order. Walk the
// rules and apply high-priority properties first, i.e., those properties that
// other properties depend on. The order is (1) high-priority not important,
// (2) high-priority important, (3) normal not important and (4) normal
// important.
applyMatchedProperties<HighPropertyPriority, CheckNeedsApplyPass>(
state, matchResult.allRules(), false, applyInheritedOnly, needsApplyPass);
for (auto range : ImportantAuthorRanges(matchResult)) {
applyMatchedProperties<HighPropertyPriority, CheckNeedsApplyPass>(
state, range, true, applyInheritedOnly, needsApplyPass);
}
applyMatchedProperties<HighPropertyPriority, CheckNeedsApplyPass>(
state, matchResult.uaRules(), true, applyInheritedOnly, needsApplyPass);
if (UNLIKELY(isSVGForeignObjectElement(state.element()))) {
// LayoutSVGRoot handles zooming for the whole SVG subtree, so foreignObject
// content should not be scaled again.
//
// FIXME: The following hijacks the zoom property for foreignObject so that
// children of foreignObject get the correct font-size in case of zooming.
// 'zoom' has HighPropertyPriority, along with other font-related properties
// used as input to the FontBuilder, so resetting it here may cause the
// FontBuilder to recompute the font used as inheritable font for
// foreignObject content. If we want to support zoom on foreignObject we'll
// need to find another way of handling the SVG zoom model.
state.setEffectiveZoom(ComputedStyle::initialZoom());
}
if (cacheSuccess.cachedMatchedProperties &&
cacheSuccess.cachedMatchedProperties->computedStyle->effectiveZoom() !=
state.style()->effectiveZoom()) {
state.fontBuilder().didChangeEffectiveZoom();
applyInheritedOnly = false;
}
// If our font got dirtied, go ahead and update it now.
updateFont(state);
// Many properties depend on the font. If it changes we just apply all
// properties.
if (cacheSuccess.cachedMatchedProperties &&
cacheSuccess.cachedMatchedProperties->computedStyle
->getFontDescription() != state.style()->getFontDescription())
applyInheritedOnly = false;
// Registered custom properties are computed after high priority properties.
CSSVariableResolver::computeRegisteredVariables(state);
// Now do the normal priority UA properties.
applyMatchedProperties<LowPropertyPriority, CheckNeedsApplyPass>(
state, matchResult.uaRules(), false, applyInheritedOnly, needsApplyPass);
// Cache the UA properties to pass them to LayoutTheme in adjustComputedStyle.
state.cacheUserAgentBorderAndBackground();
// Now do the author and user normal priority properties and all the
// !important properties.
applyMatchedProperties<LowPropertyPriority, CheckNeedsApplyPass>(
state, matchResult.authorRules(), false, applyInheritedOnly,
needsApplyPass);
for (auto range : ImportantAuthorRanges(matchResult)) {
applyMatchedProperties<LowPropertyPriority, CheckNeedsApplyPass>(
state, range, true, applyInheritedOnly, needsApplyPass);
}
applyMatchedProperties<LowPropertyPriority, CheckNeedsApplyPass>(
state, matchResult.uaRules(), true, applyInheritedOnly, needsApplyPass);
if (state.style()->hasAppearance() && !applyInheritedOnly) {
// Check whether the final border and background differs from the cached UA
// ones. When there is a partial match in the MatchedPropertiesCache, these
// flags will already be set correctly and the value stored in
// cacheUserAgentBorderAndBackground is incorrect, so doing this check again
// would give the wrong answer.
state.style()->setHasAuthorBackground(hasAuthorBackground(state));
state.style()->setHasAuthorBorder(hasAuthorBorder(state));
}
loadPendingResources(state);
if (!state.isAnimatingCustomProperties() &&
!cacheSuccess.cachedMatchedProperties && cacheSuccess.cacheHash &&
MatchedPropertiesCache::isCacheable(state)) {
INCREMENT_STYLE_STATS_COUNTER(document().styleEngine(),
matchedPropertyCacheAdded, 1);
m_matchedPropertiesCache.add(*state.style(), *state.parentStyle(),
cacheSuccess.cacheHash,
matchResult.matchedProperties());
}
DCHECK(!state.fontBuilder().fontDirty());
}
bool StyleResolver::hasAuthorBackground(const StyleResolverState& state) {
const CachedUAStyle* cachedUAStyle = state.cachedUAStyle();
if (!cachedUAStyle)
return false;
FillLayer oldFill = cachedUAStyle->backgroundLayers;
FillLayer newFill = state.style()->backgroundLayers();
// Exclude background-repeat from comparison by resetting it.
oldFill.setRepeatX(NoRepeatFill);
oldFill.setRepeatY(NoRepeatFill);
newFill.setRepeatX(NoRepeatFill);
newFill.setRepeatY(NoRepeatFill);
return (oldFill != newFill ||
cachedUAStyle->backgroundColor != state.style()->backgroundColor());
}
bool StyleResolver::hasAuthorBorder(const StyleResolverState& state) {
const CachedUAStyle* cachedUAStyle = state.cachedUAStyle();
return cachedUAStyle && (cachedUAStyle->border != state.style()->border());
}
void StyleResolver::applyCallbackSelectors(StyleResolverState& state) {
RuleSet* watchedSelectorsRuleSet =
document().styleEngine().watchedSelectorsRuleSet();
if (!watchedSelectorsRuleSet)
return;
ElementRuleCollector collector(state.elementContext(), m_selectorFilter,
state.style());
collector.setMode(SelectorChecker::CollectingStyleRules);
collector.setIncludeEmptyRules(true);
MatchRequest matchRequest(watchedSelectorsRuleSet);
collector.collectMatchingRules(matchRequest);
collector.sortAndTransferMatchedRules();
if (m_tracker)
addMatchedRulesToTracker(collector);
StyleRuleList* rules = collector.matchedStyleRuleList();
if (!rules)
return;
for (size_t i = 0; i < rules->size(); i++)
state.style()->addCallbackSelector(
rules->at(i)->selectorList().selectorsText());
}
void StyleResolver::computeFont(ComputedStyle* style,
const StylePropertySet& propertySet) {
CSSPropertyID properties[] = {
CSSPropertyFontSize, CSSPropertyFontFamily, CSSPropertyFontStretch,
CSSPropertyFontStyle, CSSPropertyFontVariantCaps, CSSPropertyFontWeight,
CSSPropertyLineHeight,
};
// TODO(timloh): This is weird, the style is being used as its own parent
StyleResolverState state(document(), nullptr, style);
state.setStyle(style);
for (CSSPropertyID property : properties) {
if (property == CSSPropertyLineHeight)
updateFont(state);
StyleBuilder::applyProperty(property, state,
*propertySet.getPropertyCSSValue(property));
}
}
void StyleResolver::updateMediaType() {
if (FrameView* view = document().view()) {
bool wasPrint = m_printMediaType;
m_printMediaType =
equalIgnoringCase(view->mediaType(), MediaTypeNames::print);
if (wasPrint != m_printMediaType)
m_matchedPropertiesCache.clearViewportDependent();
}
}
DEFINE_TRACE(StyleResolver) {
visitor->trace(m_matchedPropertiesCache);
visitor->trace(m_selectorFilter);
visitor->trace(m_styleSharingLists);
visitor->trace(m_document);
visitor->trace(m_tracker);
}
} // namespace blink
|