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
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All
* rights reserved.
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
* (http://www.torchmobile.com/)
* Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) Research In Motion Limited 2010-2011. 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/dom/StyleEngine.h"
#include "core/HTMLNames.h"
#include "core/css/CSSDefaultStyleSheets.h"
#include "core/css/CSSFontSelector.h"
#include "core/css/CSSStyleSheet.h"
#include "core/css/FontFaceCache.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/invalidation/InvalidationSet.h"
#include "core/css/resolver/ScopedStyleResolver.h"
#include "core/css/resolver/SharedStyleFinder.h"
#include "core/css/resolver/StyleRuleUsageTracker.h"
#include "core/css/resolver/ViewportStyleResolver.h"
#include "core/dom/DocumentStyleSheetCollector.h"
#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/ProcessingInstruction.h"
#include "core/dom/ShadowTreeStyleSheetCollection.h"
#include "core/dom/StyleChangeReason.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLIFrameElement.h"
#include "core/html/HTMLLinkElement.h"
#include "core/html/HTMLSlotElement.h"
#include "core/html/imports/HTMLImportsController.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/layout/api/LayoutViewItem.h"
#include "core/page/Page.h"
#include "core/svg/SVGStyleElement.h"
#include "platform/fonts/FontCache.h"
#include "platform/instrumentation/tracing/TraceEvent.h"
namespace blink {
using namespace HTMLNames;
StyleEngine::StyleEngine(Document& document)
: m_document(&document),
m_isMaster(!document.importsController() ||
document.importsController()->master() == &document),
m_documentStyleSheetCollection(
this,
DocumentStyleSheetCollection::create(document)) {
if (document.frame()) {
// We don't need to create CSSFontSelector for imported document or
// HTMLTemplateElement's document, because those documents have no frame.
m_fontSelector = CSSFontSelector::create(&document);
m_fontSelector->registerForInvalidationCallbacks(this);
}
if (document.isInMainFrame())
m_viewportResolver = ViewportStyleResolver::create(document);
}
StyleEngine::~StyleEngine() {}
inline Document* StyleEngine::master() {
if (isMaster())
return m_document;
HTMLImportsController* import = document().importsController();
// Document::import() can return null while executing its destructor.
if (!import)
return nullptr;
return import->master();
}
TreeScopeStyleSheetCollection* StyleEngine::ensureStyleSheetCollectionFor(
TreeScope& treeScope) {
if (treeScope == m_document)
return &documentStyleSheetCollection();
StyleSheetCollectionMap::AddResult result =
m_styleSheetCollectionMap.add(&treeScope, nullptr);
if (result.isNewEntry)
result.storedValue->value =
new ShadowTreeStyleSheetCollection(toShadowRoot(treeScope));
return result.storedValue->value.get();
}
TreeScopeStyleSheetCollection* StyleEngine::styleSheetCollectionFor(
TreeScope& treeScope) {
if (treeScope == m_document)
return &documentStyleSheetCollection();
StyleSheetCollectionMap::iterator it =
m_styleSheetCollectionMap.find(&treeScope);
if (it == m_styleSheetCollectionMap.end())
return nullptr;
return it->value.get();
}
const HeapVector<TraceWrapperMember<StyleSheet>>&
StyleEngine::styleSheetsForStyleSheetList(TreeScope& treeScope) {
// TODO(rune@opera.com): we could split styleSheets and active stylesheet
// update to have a lighter update while accessing the styleSheets list.
DCHECK(master());
if (master()->isActive()) {
if (isMaster())
updateActiveStyle();
else
master()->styleEngine().updateActiveStyle();
}
if (treeScope == m_document)
return documentStyleSheetCollection().styleSheetsForStyleSheetList();
return ensureStyleSheetCollectionFor(treeScope)
->styleSheetsForStyleSheetList();
}
void StyleEngine::injectAuthorSheet(StyleSheetContents* authorSheet) {
m_injectedAuthorStyleSheets.push_back(TraceWrapperMember<CSSStyleSheet>(
this, CSSStyleSheet::create(authorSheet, *m_document)));
markDocumentDirty();
}
CSSStyleSheet& StyleEngine::ensureInspectorStyleSheet() {
if (m_inspectorStyleSheet)
return *m_inspectorStyleSheet;
StyleSheetContents* contents =
StyleSheetContents::create(CSSParserContext::create(*m_document));
m_inspectorStyleSheet = CSSStyleSheet::create(contents, *m_document);
markDocumentDirty();
// TODO(rune@opera.com): Making the active stylesheets up-to-date here is
// required by some inspector tests, at least. I theory this should not be
// necessary. Need to investigate to figure out if/why.
updateActiveStyle();
return *m_inspectorStyleSheet;
}
void StyleEngine::addPendingSheet(StyleEngineContext& context) {
m_pendingScriptBlockingStylesheets++;
context.addingPendingSheet(document());
if (context.addedPendingSheetBeforeBody())
m_pendingRenderBlockingStylesheets++;
}
// This method is called whenever a top-level stylesheet has finished loading.
void StyleEngine::removePendingSheet(Node& styleSheetCandidateNode,
const StyleEngineContext& context) {
if (styleSheetCandidateNode.isConnected())
setNeedsActiveStyleUpdate(styleSheetCandidateNode.treeScope());
if (context.addedPendingSheetBeforeBody()) {
DCHECK_GT(m_pendingRenderBlockingStylesheets, 0);
m_pendingRenderBlockingStylesheets--;
}
// Make sure we knew this sheet was pending, and that our count isn't out of
// sync.
DCHECK_GT(m_pendingScriptBlockingStylesheets, 0);
m_pendingScriptBlockingStylesheets--;
if (m_pendingScriptBlockingStylesheets)
return;
document().didRemoveAllPendingStylesheet();
}
void StyleEngine::setNeedsActiveStyleUpdate(TreeScope& treeScope) {
if (document().isActive() || !isMaster())
markTreeScopeDirty(treeScope);
}
void StyleEngine::addStyleSheetCandidateNode(Node& node) {
if (!node.isConnected() || document().isDetached())
return;
DCHECK(!isXSLStyleSheet(node));
TreeScope& treeScope = node.treeScope();
TreeScopeStyleSheetCollection* collection =
ensureStyleSheetCollectionFor(treeScope);
DCHECK(collection);
collection->addStyleSheetCandidateNode(node);
setNeedsActiveStyleUpdate(treeScope);
if (treeScope != m_document)
m_activeTreeScopes.add(&treeScope);
}
void StyleEngine::removeStyleSheetCandidateNode(Node& node,
ContainerNode& insertionPoint) {
DCHECK(!isXSLStyleSheet(node));
DCHECK(insertionPoint.isConnected());
ShadowRoot* shadowRoot = node.containingShadowRoot();
if (!shadowRoot)
shadowRoot = insertionPoint.containingShadowRoot();
TreeScope& treeScope =
shadowRoot ? *toTreeScope(shadowRoot) : toTreeScope(document());
TreeScopeStyleSheetCollection* collection =
styleSheetCollectionFor(treeScope);
// After detaching document, collection could be null. In the case,
// we should not update anything. Instead, just return.
if (!collection)
return;
collection->removeStyleSheetCandidateNode(node);
setNeedsActiveStyleUpdate(treeScope);
}
void StyleEngine::modifiedStyleSheetCandidateNode(Node& node) {
if (node.isConnected())
setNeedsActiveStyleUpdate(node.treeScope());
}
void StyleEngine::mediaQueriesChangedInScope(TreeScope& treeScope) {
if (ScopedStyleResolver* resolver = treeScope.scopedStyleResolver())
resolver->setNeedsAppendAllSheets();
setNeedsActiveStyleUpdate(treeScope);
}
void StyleEngine::watchedSelectorsChanged() {
m_globalRuleSet.initWatchedSelectorsRuleSet(document());
// TODO(rune@opera.com): Should be able to use RuleSetInvalidation here.
document().setNeedsStyleRecalc(SubtreeStyleChange,
StyleChangeReasonForTracing::create(
StyleChangeReason::DeclarativeContent));
}
bool StyleEngine::shouldUpdateDocumentStyleSheetCollection() const {
return m_allTreeScopesDirty || m_documentScopeDirty;
}
bool StyleEngine::shouldUpdateShadowTreeStyleSheetCollection() const {
return m_allTreeScopesDirty || !m_dirtyTreeScopes.isEmpty();
}
void StyleEngine::mediaQueryAffectingValueChanged(
UnorderedTreeScopeSet& treeScopes) {
for (TreeScope* treeScope : treeScopes) {
DCHECK(treeScope != m_document);
ShadowTreeStyleSheetCollection* collection =
toShadowTreeStyleSheetCollection(styleSheetCollectionFor(*treeScope));
DCHECK(collection);
if (collection->mediaQueryAffectingValueChanged())
setNeedsActiveStyleUpdate(*treeScope);
}
}
void StyleEngine::mediaQueryAffectingValueChanged() {
if (documentStyleSheetCollection().mediaQueryAffectingValueChanged())
setNeedsActiveStyleUpdate(document());
mediaQueryAffectingValueChanged(m_activeTreeScopes);
if (m_resolver)
m_resolver->updateMediaType();
}
void StyleEngine::updateStyleSheetsInImport(
StyleEngine& masterEngine,
DocumentStyleSheetCollector& parentCollector) {
DCHECK(!isMaster());
HeapVector<Member<StyleSheet>> sheetsForList;
ImportedDocumentStyleSheetCollector subcollector(parentCollector,
sheetsForList);
documentStyleSheetCollection().collectStyleSheets(masterEngine, subcollector);
documentStyleSheetCollection().swapSheetsForSheetList(sheetsForList);
}
void StyleEngine::updateActiveStyleSheetsInShadow(
TreeScope* treeScope,
UnorderedTreeScopeSet& treeScopesRemoved) {
DCHECK_NE(treeScope, m_document);
ShadowTreeStyleSheetCollection* collection =
toShadowTreeStyleSheetCollection(styleSheetCollectionFor(*treeScope));
DCHECK(collection);
collection->updateActiveStyleSheets(*this);
if (!collection->hasStyleSheetCandidateNodes()) {
treeScopesRemoved.add(treeScope);
// When removing TreeScope from ActiveTreeScopes,
// its resolver should be destroyed by invoking resetAuthorStyle.
DCHECK(!treeScope->scopedStyleResolver());
}
}
void StyleEngine::updateActiveStyleSheets() {
if (!needsActiveStyleSheetUpdate())
return;
DCHECK(isMaster());
DCHECK(!document().inStyleRecalc());
DCHECK(document().isActive());
TRACE_EVENT0("blink,blink_style", "StyleEngine::updateActiveStyleSheets");
if (shouldUpdateDocumentStyleSheetCollection())
documentStyleSheetCollection().updateActiveStyleSheets(*this);
if (shouldUpdateShadowTreeStyleSheetCollection()) {
UnorderedTreeScopeSet treeScopesRemoved;
if (m_allTreeScopesDirty) {
for (TreeScope* treeScope : m_activeTreeScopes)
updateActiveStyleSheetsInShadow(treeScope, treeScopesRemoved);
} else {
for (TreeScope* treeScope : m_dirtyTreeScopes)
updateActiveStyleSheetsInShadow(treeScope, treeScopesRemoved);
}
for (TreeScope* treeScope : treeScopesRemoved)
m_activeTreeScopes.remove(treeScope);
}
InspectorInstrumentation::activeStyleSheetsUpdated(m_document);
m_dirtyTreeScopes.clear();
m_documentScopeDirty = false;
m_allTreeScopesDirty = false;
}
void StyleEngine::updateViewport() {
if (m_viewportResolver)
m_viewportResolver->updateViewport(documentStyleSheetCollection());
}
bool StyleEngine::needsActiveStyleUpdate() const {
return (m_viewportResolver && m_viewportResolver->needsUpdate()) ||
needsActiveStyleSheetUpdate() || m_globalRuleSet.isDirty();
}
void StyleEngine::updateActiveStyle() {
DCHECK(document().isActive());
updateViewport();
updateActiveStyleSheets();
updateGlobalRuleSet();
}
const ActiveStyleSheetVector StyleEngine::activeStyleSheetsForInspector() {
if (document().isActive())
updateActiveStyle();
if (m_activeTreeScopes.isEmpty())
return documentStyleSheetCollection().activeAuthorStyleSheets();
ActiveStyleSheetVector activeStyleSheets;
activeStyleSheets.appendVector(
documentStyleSheetCollection().activeAuthorStyleSheets());
for (TreeScope* treeScope : m_activeTreeScopes) {
if (TreeScopeStyleSheetCollection* collection =
m_styleSheetCollectionMap.get(treeScope))
activeStyleSheets.appendVector(collection->activeAuthorStyleSheets());
}
// FIXME: Inspector needs a vector which has all active stylesheets.
// However, creating such a large vector might cause performance regression.
// Need to implement some smarter solution.
return activeStyleSheets;
}
void StyleEngine::shadowRootRemovedFromDocument(ShadowRoot* shadowRoot) {
m_styleSheetCollectionMap.remove(shadowRoot);
m_activeTreeScopes.remove(shadowRoot);
m_dirtyTreeScopes.remove(shadowRoot);
resetAuthorStyle(*shadowRoot);
}
void StyleEngine::addTreeBoundaryCrossingScope(const TreeScope& treeScope) {
m_treeBoundaryCrossingScopes.add(&treeScope.rootNode());
}
void StyleEngine::resetAuthorStyle(TreeScope& treeScope) {
m_treeBoundaryCrossingScopes.remove(&treeScope.rootNode());
ScopedStyleResolver* scopedResolver = treeScope.scopedStyleResolver();
if (!scopedResolver)
return;
m_globalRuleSet.markDirty();
if (treeScope.rootNode().isDocumentNode()) {
scopedResolver->resetAuthorStyle();
return;
}
treeScope.clearScopedStyleResolver();
}
void StyleEngine::setRuleUsageTracker(StyleRuleUsageTracker* tracker) {
m_tracker = tracker;
if (m_resolver)
m_resolver->setRuleUsageTracker(m_tracker);
}
RuleSet* StyleEngine::ruleSetForSheet(CSSStyleSheet& sheet) {
if (!sheet.matchesMediaQueries(ensureMediaQueryEvaluator()))
return nullptr;
AddRuleFlags addRuleFlags = RuleHasNoSpecialState;
if (m_document->getSecurityOrigin()->canRequest(sheet.baseURL()))
addRuleFlags = RuleHasDocumentSecurityOrigin;
return &sheet.contents()->ensureRuleSet(*m_mediaQueryEvaluator, addRuleFlags);
}
void StyleEngine::createResolver() {
m_resolver = StyleResolver::create(*m_document);
m_resolver->setRuleUsageTracker(m_tracker);
}
void StyleEngine::clearResolvers() {
DCHECK(!document().inStyleRecalc());
DCHECK(isMaster() || !m_resolver);
document().clearScopedStyleResolver();
for (TreeScope* treeScope : m_activeTreeScopes)
treeScope->clearScopedStyleResolver();
if (m_resolver) {
TRACE_EVENT1("blink", "StyleEngine::clearResolver", "frame",
document().frame());
m_resolver->dispose();
m_resolver.clear();
}
}
void StyleEngine::didDetach() {
clearResolvers();
m_globalRuleSet.dispose();
m_treeBoundaryCrossingScopes.clear();
m_dirtyTreeScopes.clear();
m_activeTreeScopes.clear();
m_viewportResolver = nullptr;
m_mediaQueryEvaluator = nullptr;
if (m_fontSelector)
m_fontSelector->fontFaceCache()->clearAll();
m_fontSelector = nullptr;
}
void StyleEngine::clearFontCache() {
if (m_fontSelector)
m_fontSelector->fontFaceCache()->clearCSSConnected();
if (m_resolver)
m_resolver->invalidateMatchedPropertiesCache();
}
void StyleEngine::updateGenericFontFamilySettings() {
// FIXME: we should not update generic font family settings when
// document is inactive.
DCHECK(document().isActive());
if (!m_fontSelector)
return;
m_fontSelector->updateGenericFontFamilySettings(*m_document);
if (m_resolver)
m_resolver->invalidateMatchedPropertiesCache();
FontCache::fontCache()->invalidateShapeCache();
}
void StyleEngine::removeFontFaceRules(
const HeapVector<Member<const StyleRuleFontFace>>& fontFaceRules) {
if (!m_fontSelector)
return;
FontFaceCache* cache = m_fontSelector->fontFaceCache();
for (const auto& rule : fontFaceRules)
cache->remove(rule);
if (m_resolver)
m_resolver->invalidateMatchedPropertiesCache();
}
void StyleEngine::markTreeScopeDirty(TreeScope& scope) {
if (scope == m_document) {
markDocumentDirty();
return;
}
DCHECK(m_styleSheetCollectionMap.contains(&scope));
m_dirtyTreeScopes.add(&scope);
document().scheduleLayoutTreeUpdateIfNeeded();
}
void StyleEngine::markDocumentDirty() {
m_documentScopeDirty = true;
if (RuntimeEnabledFeatures::cssViewportEnabled())
viewportRulesChanged();
if (document().importLoader())
document().importsController()->master()->styleEngine().markDocumentDirty();
else
document().scheduleLayoutTreeUpdateIfNeeded();
}
CSSStyleSheet* StyleEngine::createSheet(Element& element,
const String& text,
TextPosition startPosition,
StyleEngineContext& context) {
DCHECK(element.document() == document());
CSSStyleSheet* styleSheet = nullptr;
addPendingSheet(context);
AtomicString textContent(text);
auto result = m_textToSheetCache.add(textContent, nullptr);
StyleSheetContents* contents = result.storedValue->value;
if (result.isNewEntry || !contents ||
!contents->isCacheableForStyleElement()) {
result.storedValue->value = nullptr;
styleSheet = parseSheet(element, text, startPosition);
if (styleSheet->contents()->isCacheableForStyleElement()) {
result.storedValue->value = styleSheet->contents();
m_sheetToTextCache.add(styleSheet->contents(), textContent);
}
} else {
DCHECK(contents);
DCHECK(contents->isCacheableForStyleElement());
DCHECK(contents->hasSingleOwnerDocument());
contents->setIsUsedFromTextCache();
styleSheet = CSSStyleSheet::createInline(contents, element, startPosition);
}
DCHECK(styleSheet);
if (!element.isInShadowTree()) {
styleSheet->setTitle(element.title());
setPreferredStylesheetSetNameIfNotSet(element.title());
}
return styleSheet;
}
CSSStyleSheet* StyleEngine::parseSheet(Element& element,
const String& text,
TextPosition startPosition) {
CSSStyleSheet* styleSheet = nullptr;
styleSheet = CSSStyleSheet::createInline(element, KURL(), startPosition,
document().characterSet());
styleSheet->contents()->parseStringAtPosition(text, startPosition);
return styleSheet;
}
void StyleEngine::collectScopedStyleFeaturesTo(RuleFeatureSet& features) const {
HeapHashSet<Member<const StyleSheetContents>> visitedSharedStyleSheetContents;
if (document().scopedStyleResolver())
document().scopedStyleResolver()->collectFeaturesTo(
features, visitedSharedStyleSheetContents);
for (TreeScope* treeScope : m_activeTreeScopes) {
// When creating StyleResolver, dirty treescopes might not be processed.
// So some active treescopes might not have a scoped style resolver.
// In this case, we should skip collectFeatures for the treescopes without
// scoped style resolvers. When invoking updateActiveStyleSheets,
// the treescope's features will be processed.
if (ScopedStyleResolver* resolver = treeScope->scopedStyleResolver())
resolver->collectFeaturesTo(features, visitedSharedStyleSheetContents);
}
}
void StyleEngine::fontsNeedUpdate(CSSFontSelector*) {
if (!document().isActive())
return;
if (m_resolver)
m_resolver->invalidateMatchedPropertiesCache();
document().setNeedsStyleRecalc(
SubtreeStyleChange,
StyleChangeReasonForTracing::create(StyleChangeReason::Fonts));
InspectorInstrumentation::fontsUpdated(m_document);
}
void StyleEngine::setFontSelector(CSSFontSelector* fontSelector) {
if (m_fontSelector)
m_fontSelector->unregisterForInvalidationCallbacks(this);
m_fontSelector = fontSelector;
if (m_fontSelector)
m_fontSelector->registerForInvalidationCallbacks(this);
}
void StyleEngine::platformColorsChanged() {
if (m_resolver)
m_resolver->invalidateMatchedPropertiesCache();
document().setNeedsStyleRecalc(SubtreeStyleChange,
StyleChangeReasonForTracing::create(
StyleChangeReason::PlatformColorChange));
}
bool StyleEngine::shouldSkipInvalidationFor(const Element& element) const {
if (!resolver())
return true;
if (!element.inActiveDocument())
return true;
if (!element.parentNode())
return true;
return element.parentNode()->getStyleChangeType() >= SubtreeStyleChange;
}
void StyleEngine::classChangedForElement(const SpaceSplitString& changedClasses,
Element& element) {
if (shouldSkipInvalidationFor(element))
return;
InvalidationLists invalidationLists;
unsigned changedSize = changedClasses.size();
const RuleFeatureSet& features = ruleFeatureSet();
for (unsigned i = 0; i < changedSize; ++i) {
features.collectInvalidationSetsForClass(invalidationLists, element,
changedClasses[i]);
}
m_styleInvalidator.scheduleInvalidationSetsForNode(invalidationLists,
element);
}
void StyleEngine::classChangedForElement(const SpaceSplitString& oldClasses,
const SpaceSplitString& newClasses,
Element& element) {
if (shouldSkipInvalidationFor(element))
return;
if (!oldClasses.size()) {
classChangedForElement(newClasses, element);
return;
}
// Class vectors tend to be very short. This is faster than using a hash
// table.
BitVector remainingClassBits;
remainingClassBits.ensureSize(oldClasses.size());
InvalidationLists invalidationLists;
const RuleFeatureSet& features = ruleFeatureSet();
for (unsigned i = 0; i < newClasses.size(); ++i) {
bool found = false;
for (unsigned j = 0; j < oldClasses.size(); ++j) {
if (newClasses[i] == oldClasses[j]) {
// Mark each class that is still in the newClasses so we can skip doing
// an n^2 search below when looking for removals. We can't break from
// this loop early since a class can appear more than once.
remainingClassBits.quickSet(j);
found = true;
}
}
// Class was added.
if (!found) {
features.collectInvalidationSetsForClass(invalidationLists, element,
newClasses[i]);
}
}
for (unsigned i = 0; i < oldClasses.size(); ++i) {
if (remainingClassBits.quickGet(i))
continue;
// Class was removed.
features.collectInvalidationSetsForClass(invalidationLists, element,
oldClasses[i]);
}
m_styleInvalidator.scheduleInvalidationSetsForNode(invalidationLists,
element);
}
void StyleEngine::attributeChangedForElement(const QualifiedName& attributeName,
Element& element) {
if (shouldSkipInvalidationFor(element))
return;
InvalidationLists invalidationLists;
ruleFeatureSet().collectInvalidationSetsForAttribute(invalidationLists,
element, attributeName);
m_styleInvalidator.scheduleInvalidationSetsForNode(invalidationLists,
element);
}
void StyleEngine::idChangedForElement(const AtomicString& oldId,
const AtomicString& newId,
Element& element) {
if (shouldSkipInvalidationFor(element))
return;
InvalidationLists invalidationLists;
const RuleFeatureSet& features = ruleFeatureSet();
if (!oldId.isEmpty())
features.collectInvalidationSetsForId(invalidationLists, element, oldId);
if (!newId.isEmpty())
features.collectInvalidationSetsForId(invalidationLists, element, newId);
m_styleInvalidator.scheduleInvalidationSetsForNode(invalidationLists,
element);
}
void StyleEngine::pseudoStateChangedForElement(
CSSSelector::PseudoType pseudoType,
Element& element) {
if (shouldSkipInvalidationFor(element))
return;
InvalidationLists invalidationLists;
ruleFeatureSet().collectInvalidationSetsForPseudoClass(invalidationLists,
element, pseudoType);
m_styleInvalidator.scheduleInvalidationSetsForNode(invalidationLists,
element);
}
void StyleEngine::scheduleSiblingInvalidationsForElement(
Element& element,
ContainerNode& schedulingParent,
unsigned minDirectAdjacent) {
DCHECK(minDirectAdjacent);
InvalidationLists invalidationLists;
const RuleFeatureSet& features = ruleFeatureSet();
if (element.hasID()) {
features.collectSiblingInvalidationSetForId(invalidationLists, element,
element.idForStyleResolution(),
minDirectAdjacent);
}
if (element.hasClass()) {
const SpaceSplitString& classNames = element.classNames();
for (size_t i = 0; i < classNames.size(); i++)
features.collectSiblingInvalidationSetForClass(
invalidationLists, element, classNames[i], minDirectAdjacent);
}
for (const Attribute& attribute : element.attributes())
features.collectSiblingInvalidationSetForAttribute(
invalidationLists, element, attribute.name(), minDirectAdjacent);
features.collectUniversalSiblingInvalidationSet(invalidationLists,
minDirectAdjacent);
m_styleInvalidator.scheduleSiblingInvalidationsAsDescendants(
invalidationLists, schedulingParent);
}
void StyleEngine::scheduleInvalidationsForInsertedSibling(
Element* beforeElement,
Element& insertedElement) {
unsigned affectedSiblings =
insertedElement.parentNode()->childrenAffectedByIndirectAdjacentRules()
? UINT_MAX
: maxDirectAdjacentSelectors();
ContainerNode* schedulingParent = insertedElement.parentElementOrShadowRoot();
if (!schedulingParent)
return;
scheduleSiblingInvalidationsForElement(insertedElement, *schedulingParent, 1);
for (unsigned i = 1; beforeElement && i <= affectedSiblings;
i++, beforeElement = ElementTraversal::previousSibling(*beforeElement))
scheduleSiblingInvalidationsForElement(*beforeElement, *schedulingParent,
i);
}
void StyleEngine::scheduleInvalidationsForRemovedSibling(
Element* beforeElement,
Element& removedElement,
Element& afterElement) {
unsigned affectedSiblings =
afterElement.parentNode()->childrenAffectedByIndirectAdjacentRules()
? UINT_MAX
: maxDirectAdjacentSelectors();
ContainerNode* schedulingParent = afterElement.parentElementOrShadowRoot();
if (!schedulingParent)
return;
scheduleSiblingInvalidationsForElement(removedElement, *schedulingParent, 1);
for (unsigned i = 1; beforeElement && i <= affectedSiblings;
i++, beforeElement = ElementTraversal::previousSibling(*beforeElement))
scheduleSiblingInvalidationsForElement(*beforeElement, *schedulingParent,
i);
}
void StyleEngine::scheduleNthPseudoInvalidations(ContainerNode& nthParent) {
InvalidationLists invalidationLists;
ruleFeatureSet().collectNthInvalidationSet(invalidationLists);
m_styleInvalidator.scheduleInvalidationSetsForNode(invalidationLists,
nthParent);
}
void StyleEngine::scheduleRuleSetInvalidationsForElement(
Element& element,
const HeapHashSet<Member<RuleSet>>& ruleSets) {
AtomicString id;
const SpaceSplitString* classNames = nullptr;
if (element.hasID())
id = element.idForStyleResolution();
if (element.hasClass())
classNames = &element.classNames();
InvalidationLists invalidationLists;
for (const auto& ruleSet : ruleSets) {
if (!id.isNull())
ruleSet->features().collectInvalidationSetsForId(invalidationLists,
element, id);
if (classNames) {
unsigned classNameCount = classNames->size();
for (size_t i = 0; i < classNameCount; i++)
ruleSet->features().collectInvalidationSetsForClass(
invalidationLists, element, (*classNames)[i]);
}
for (const Attribute& attribute : element.attributes())
ruleSet->features().collectInvalidationSetsForAttribute(
invalidationLists, element, attribute.name());
if (ruleSet->tagRules(element.localNameForSelectorMatching()))
element.setNeedsStyleRecalc(LocalStyleChange,
StyleChangeReasonForTracing::create(
StyleChangeReason::StyleSheetChange));
}
m_styleInvalidator.scheduleInvalidationSetsForNode(invalidationLists,
element);
}
void StyleEngine::invalidateSlottedElements(HTMLSlotElement& slot) {
for (auto& node : slot.getDistributedNodes()) {
if (node->isElementNode())
node->setNeedsStyleRecalc(LocalStyleChange,
StyleChangeReasonForTracing::create(
StyleChangeReason::StyleSheetChange));
}
}
void StyleEngine::scheduleInvalidationsForRuleSets(
TreeScope& treeScope,
const HeapHashSet<Member<RuleSet>>& ruleSets) {
#if DCHECK_IS_ON()
// Full scope recalcs should be handled while collecting the ruleSets before
// calling this method.
for (auto ruleSet : ruleSets)
DCHECK(!ruleSet->features().needsFullRecalcForRuleSetInvalidation());
#endif // DCHECK_IS_ON()
TRACE_EVENT0("blink,blink_style",
"StyleEngine::scheduleInvalidationsForRuleSets");
bool invalidateSlotted = false;
if (treeScope.rootNode().isShadowRoot()) {
Element& host = toShadowRoot(treeScope.rootNode()).host();
scheduleRuleSetInvalidationsForElement(host, ruleSets);
if (host.getStyleChangeType() >= SubtreeStyleChange)
return;
for (auto ruleSet : ruleSets) {
if (ruleSet->hasSlottedRules()) {
invalidateSlotted = true;
break;
}
}
}
Node* stayWithin = &treeScope.rootNode();
Element* element = ElementTraversal::firstChild(*stayWithin);
while (element) {
scheduleRuleSetInvalidationsForElement(*element, ruleSets);
if (invalidateSlotted && isHTMLSlotElement(element))
invalidateSlottedElements(toHTMLSlotElement(*element));
if (element->getStyleChangeType() < SubtreeStyleChange)
element = ElementTraversal::next(*element, stayWithin);
else
element = ElementTraversal::nextSkippingChildren(*element, stayWithin);
}
}
void StyleEngine::setStatsEnabled(bool enabled) {
if (!enabled) {
m_styleResolverStats = nullptr;
return;
}
if (!m_styleResolverStats)
m_styleResolverStats = StyleResolverStats::create();
else
m_styleResolverStats->reset();
}
void StyleEngine::setPreferredStylesheetSetNameIfNotSet(const String& name) {
if (!m_preferredStylesheetSetName.isEmpty())
return;
m_preferredStylesheetSetName = name;
// TODO(rune@opera.com): Setting the selected set here is wrong if the set
// has been previously set by through Document.selectedStylesheetSet. Our
// current implementation ignores the effect of Document.selectedStylesheetSet
// and either only collects persistent style, or additionally preferred
// style when present.
m_selectedStylesheetSetName = name;
markDocumentDirty();
}
void StyleEngine::setSelectedStylesheetSetName(const String& name) {
m_selectedStylesheetSetName = name;
// TODO(rune@opera.com): Setting Document.selectedStylesheetSet currently
// has no other effect than the ability to read back the set value using
// the same api. If it did have an effect, we should have marked the
// document scope dirty and triggered an update of the active stylesheets
// from here.
}
void StyleEngine::setHttpDefaultStyle(const String& content) {
setPreferredStylesheetSetNameIfNotSet(content);
}
void StyleEngine::ensureUAStyleForFullscreen() {
if (m_globalRuleSet.hasFullscreenUAStyle())
return;
CSSDefaultStyleSheets::instance().ensureDefaultStyleSheetForFullscreen();
m_globalRuleSet.markDirty();
updateActiveStyle();
}
void StyleEngine::ensureUAStyleForElement(const Element& element) {
if (CSSDefaultStyleSheets::instance().ensureDefaultStyleSheetsForElement(
element)) {
m_globalRuleSet.markDirty();
updateActiveStyle();
}
}
bool StyleEngine::hasRulesForId(const AtomicString& id) const {
return m_globalRuleSet.ruleFeatureSet().hasSelectorForId(id);
}
void StyleEngine::initialViewportChanged() {
if (m_viewportResolver)
m_viewportResolver->initialViewportChanged();
}
void StyleEngine::viewportRulesChanged() {
if (m_viewportResolver)
m_viewportResolver->setNeedsCollectRules();
}
void StyleEngine::htmlImportAddedOrRemoved() {
if (document().importLoader()) {
document()
.importsController()
->master()
->styleEngine()
.htmlImportAddedOrRemoved();
return;
}
// When we remove an import link and re-insert it into the document, the
// import Document and CSSStyleSheet pointers are persisted. That means the
// comparison of active stylesheets is not able to figure out that the order
// of the stylesheets have changed after insertion.
//
// This is also the case when we import the same document twice where the
// last inserted document is inserted before the first one in dom order where
// the last would take precedence.
//
// Fall back to re-add all sheets to the scoped resolver and recalculate style
// for the whole document when we remove or insert an import document.
if (ScopedStyleResolver* resolver = document().scopedStyleResolver()) {
markDocumentDirty();
resolver->setNeedsAppendAllSheets();
document().setNeedsStyleRecalc(
SubtreeStyleChange, StyleChangeReasonForTracing::create(
StyleChangeReason::ActiveStylesheetsUpdate));
}
}
PassRefPtr<ComputedStyle> StyleEngine::findSharedStyle(
const ElementResolveContext& elementResolveContext) {
DCHECK(m_resolver);
return SharedStyleFinder(
elementResolveContext, m_globalRuleSet.ruleFeatureSet(),
m_globalRuleSet.siblingRuleSet(),
m_globalRuleSet.uncommonAttributeRuleSet(), *m_resolver)
.findSharedStyle();
}
namespace {
enum RuleSetFlags {
FontFaceRules = 1 << 0,
KeyframesRules = 1 << 1,
FullRecalcRules = 1 << 2
};
unsigned getRuleSetFlags(const HeapHashSet<Member<RuleSet>> ruleSets) {
unsigned flags = 0;
for (auto& ruleSet : ruleSets) {
ruleSet->compactRulesIfNeeded();
if (!ruleSet->keyframesRules().isEmpty())
flags |= KeyframesRules;
if (!ruleSet->fontFaceRules().isEmpty())
flags |= FontFaceRules;
if (ruleSet->needsFullRecalcForRuleSetInvalidation())
flags |= FullRecalcRules;
}
return flags;
}
} // namespace
void StyleEngine::applyRuleSetChanges(
TreeScope& treeScope,
const ActiveStyleSheetVector& oldStyleSheets,
const ActiveStyleSheetVector& newStyleSheets) {
HeapHashSet<Member<RuleSet>> changedRuleSets;
ScopedStyleResolver* scopedResolver = treeScope.scopedStyleResolver();
bool appendAllSheets =
scopedResolver && scopedResolver->needsAppendAllSheets();
ActiveSheetsChange change =
compareActiveStyleSheets(oldStyleSheets, newStyleSheets, changedRuleSets);
if (change == NoActiveSheetsChanged && !appendAllSheets)
return;
// With rules added or removed, we need to re-aggregate rule meta data.
m_globalRuleSet.markDirty();
unsigned changedRuleFlags = getRuleSetFlags(changedRuleSets);
bool fontsChanged = treeScope.rootNode().isDocumentNode() &&
(changedRuleFlags & FontFaceRules);
unsigned appendStartIndex = 0;
// We don't need to clear the font cache if new sheets are appended.
if (fontsChanged && change == ActiveSheetsChanged)
clearFontCache();
// - If all sheets were removed, we remove the ScopedStyleResolver.
// - If new sheets were appended to existing ones, start appending after the
// common prefix.
// - For other diffs, reset author style and re-add all sheets for the
// TreeScope.
if (treeScope.scopedStyleResolver()) {
if (newStyleSheets.isEmpty())
resetAuthorStyle(treeScope);
else if (change == ActiveSheetsAppended && !appendAllSheets)
appendStartIndex = oldStyleSheets.size();
else
treeScope.scopedStyleResolver()->resetAuthorStyle();
}
if (!newStyleSheets.isEmpty()) {
treeScope.ensureScopedStyleResolver().appendActiveStyleSheets(
appendStartIndex, newStyleSheets);
}
if (treeScope.document().hasPendingForcedStyleRecalc())
return;
if (!treeScope.document().body() ||
treeScope.document().hasNodesWithPlaceholderStyle()) {
treeScope.document().setNeedsStyleRecalc(
SubtreeStyleChange, StyleChangeReasonForTracing::create(
StyleChangeReason::CleanupPlaceholderStyles));
return;
}
if (changedRuleFlags & KeyframesRules)
ScopedStyleResolver::keyframesRulesAdded(treeScope);
if (fontsChanged || (changedRuleFlags & FullRecalcRules)) {
ScopedStyleResolver::invalidationRootForTreeScope(treeScope)
.setNeedsStyleRecalc(SubtreeStyleChange,
StyleChangeReasonForTracing::create(
StyleChangeReason::ActiveStylesheetsUpdate));
return;
}
scheduleInvalidationsForRuleSets(treeScope, changedRuleSets);
}
const MediaQueryEvaluator& StyleEngine::ensureMediaQueryEvaluator() {
if (!m_mediaQueryEvaluator) {
if (document().frame())
m_mediaQueryEvaluator = new MediaQueryEvaluator(document().frame());
else
m_mediaQueryEvaluator = new MediaQueryEvaluator("all");
}
return *m_mediaQueryEvaluator;
}
bool StyleEngine::mediaQueryAffectedByViewportChange() {
const MediaQueryEvaluator& evaluator = ensureMediaQueryEvaluator();
const auto& results =
m_globalRuleSet.ruleFeatureSet().viewportDependentMediaQueryResults();
for (unsigned i = 0; i < results.size(); ++i) {
if (evaluator.eval(results[i]->expression()) != results[i]->result())
return true;
}
return false;
}
bool StyleEngine::mediaQueryAffectedByDeviceChange() {
const MediaQueryEvaluator& evaluator = ensureMediaQueryEvaluator();
const auto& results =
m_globalRuleSet.ruleFeatureSet().deviceDependentMediaQueryResults();
for (unsigned i = 0; i < results.size(); ++i) {
if (evaluator.eval(results[i]->expression()) != results[i]->result())
return true;
}
return false;
}
DEFINE_TRACE(StyleEngine) {
visitor->trace(m_document);
visitor->trace(m_injectedAuthorStyleSheets);
visitor->trace(m_inspectorStyleSheet);
visitor->trace(m_documentStyleSheetCollection);
visitor->trace(m_styleSheetCollectionMap);
visitor->trace(m_dirtyTreeScopes);
visitor->trace(m_activeTreeScopes);
visitor->trace(m_treeBoundaryCrossingScopes);
visitor->trace(m_globalRuleSet);
visitor->trace(m_resolver);
visitor->trace(m_viewportResolver);
visitor->trace(m_mediaQueryEvaluator);
visitor->trace(m_styleInvalidator);
visitor->trace(m_fontSelector);
visitor->trace(m_textToSheetCache);
visitor->trace(m_sheetToTextCache);
visitor->trace(m_tracker);
CSSFontSelectorClient::trace(visitor);
}
DEFINE_TRACE_WRAPPERS(StyleEngine) {
for (auto sheet : m_injectedAuthorStyleSheets) {
visitor->traceWrappers(sheet);
}
visitor->traceWrappers(m_documentStyleSheetCollection);
}
} // namespace blink
|