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
|
/*
* Copyright (C) 2004, 2005, 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005, 2006, 2008 Rob Buis <buis@kde.org>
* Copyright (C) 2008-2019 Apple Inc. All rights reserved.
* Copyright (C) 2008 Alp Toker <alp@atoker.com>
* Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
* Copyright (C) 2013 Samsung Electronics. All rights reserved.
* Copyright (C) 2014 Adobe Systems Incorporated. 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 "config.h"
#include "SVGElement.h"
#include "CSSPrimitiveValueMappings.h"
#include "CSSPropertyParser.h"
#include "ComputedStyleExtractor.h"
#include "Document.h"
#include "ElementChildIteratorInlines.h"
#include "Event.h"
#include "EventNames.h"
#include "HTMLElement.h"
#include "HTMLNames.h"
#include "HTMLParserIdioms.h"
#include "JSEventListener.h"
#include "NodeName.h"
#include "RenderAncestorIterator.h"
#include "RenderSVGResourceFilter.h"
#include "RenderSVGResourceMasker.h"
#include "ResolvedStyle.h"
#include "SVGDocumentExtensions.h"
#include "SVGElementRareData.h"
#include "SVGElementTypeHelpers.h"
#include "SVGForeignObjectElement.h"
#include "SVGGraphicsElement.h"
#include "SVGImageElement.h"
#include "SVGNames.h"
#include "SVGPropertyAnimatorFactory.h"
#include "SVGRenderStyle.h"
#include "SVGRenderSupport.h"
#include "SVGResourceElementClient.h"
#include "SVGSVGElement.h"
#include "SVGTitleElement.h"
#include "SVGUseElement.h"
#include "ShadowRoot.h"
#include "StyleAdjuster.h"
#include "StyleResolver.h"
#include "XMLNames.h"
#include <wtf/HashMap.h>
#include <wtf/IsoMallocInlines.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/RobinHoodHashMap.h>
#include <wtf/StdLibExtras.h>
namespace WebCore {
WTF_MAKE_ISO_ALLOCATED_IMPL(SVGElement);
static NEVER_INLINE MemoryCompactLookupOnlyRobinHoodHashMap<AtomString, CSSPropertyID> createAttributeNameToCSSPropertyIDMap()
{
using namespace HTMLNames;
using namespace SVGNames;
// This list should include all base CSS and SVG CSS properties which are exposed as SVG XML attributes.
static constexpr std::array attributeNames {
&alignment_baselineAttr,
&baseline_shiftAttr,
&buffered_renderingAttr,
&clipAttr,
&clip_pathAttr,
&clip_ruleAttr,
&SVGNames::colorAttr,
&color_interpolationAttr,
&color_interpolation_filtersAttr,
&cursorAttr,
&cxAttr,
&cyAttr,
&SVGNames::directionAttr,
&displayAttr,
&dominant_baselineAttr,
&fillAttr,
&fill_opacityAttr,
&fill_ruleAttr,
&filterAttr,
&flood_colorAttr,
&flood_opacityAttr,
&font_familyAttr,
&font_sizeAttr,
&font_size_adjustAttr,
&font_stretchAttr,
&font_styleAttr,
&font_variantAttr,
&font_weightAttr,
&glyph_orientation_horizontalAttr,
&glyph_orientation_verticalAttr,
&image_renderingAttr,
&SVGNames::heightAttr,
&kerningAttr,
&letter_spacingAttr,
&lighting_colorAttr,
&marker_endAttr,
&marker_midAttr,
&marker_startAttr,
&maskAttr,
&mask_typeAttr,
&opacityAttr,
&overflowAttr,
&paint_orderAttr,
&pointer_eventsAttr,
&rAttr,
&rxAttr,
&ryAttr,
&shape_renderingAttr,
&stop_colorAttr,
&stop_opacityAttr,
&strokeAttr,
&stroke_dasharrayAttr,
&stroke_dashoffsetAttr,
&stroke_linecapAttr,
&stroke_linejoinAttr,
&stroke_miterlimitAttr,
&stroke_opacityAttr,
&stroke_widthAttr,
&text_anchorAttr,
&text_decorationAttr,
&text_renderingAttr,
&unicode_bidiAttr,
&vector_effectAttr,
&visibilityAttr,
&SVGNames::widthAttr,
&word_spacingAttr,
&writing_modeAttr,
&xAttr,
&yAttr,
};
MemoryCompactLookupOnlyRobinHoodHashMap<AtomString, CSSPropertyID> map;
for (auto& name : attributeNames) {
auto& localName = name->get().localName();
map.add(localName, cssPropertyID(localName));
}
// FIXME: When CSS supports "transform-origin" this special case can be removed,
// and we can add transform_originAttr to the table above instead.
map.add(transform_originAttr->localName(), CSSPropertyTransformOrigin);
return map;
}
SVGElement::SVGElement(const QualifiedName& tagName, Document& document, UniqueRef<SVGPropertyRegistry>&& propertyRegistry, ConstructionType constructionType)
: StyledElement(tagName, document, constructionType)
, m_propertyAnimatorFactory(makeUnique<SVGPropertyAnimatorFactory>())
, m_propertyRegistry(WTFMove(propertyRegistry))
{
static std::once_flag onceFlag;
std::call_once(onceFlag, [] {
PropertyRegistry::registerProperty<HTMLNames::classAttr, &SVGElement::m_className>();
});
}
SVGElement::~SVGElement()
{
if (m_svgRareData) {
RELEASE_ASSERT(m_svgRareData->referencingElements().isEmptyIgnoringNullReferences());
for (SVGElement& instance : copyToVectorOf<Ref<SVGElement>>(instances()))
instance.m_svgRareData->setCorrespondingElement(nullptr);
RELEASE_ASSERT(!m_svgRareData->correspondingElement());
m_svgRareData = nullptr;
}
document().accessSVGExtensions().removeElementToRebuild(*this);
if (hasPendingResources()) {
treeScopeForSVGReferences().removeElementFromPendingSVGResources(*this);
ASSERT(!hasPendingResources());
}
}
void SVGElement::willRecalcStyle(Style::Change change)
{
if (!m_svgRareData || styleResolutionShouldRecompositeLayer())
return;
// If the style changes because of a regular property change (not induced by SMIL animations themselves)
// reset the "computed style without SMIL style properties", so the base value change gets reflected.
if (change > Style::Change::None || needsStyleRecalc())
m_svgRareData->setNeedsOverrideComputedStyleUpdate();
}
SVGElementRareData& SVGElement::ensureSVGRareData()
{
if (!m_svgRareData)
m_svgRareData = makeUnique<SVGElementRareData>();
return *m_svgRareData;
}
bool SVGElement::isInnerSVGSVGElement() const
{
if (!is<SVGSVGElement>(this))
return false;
// Element may not be in the document, pretend we're outermost for viewport(), getCTM(), etc.
if (!parentNode())
return false;
return is<SVGElement>(parentNode());
}
bool SVGElement::isOutermostSVGSVGElement() const
{
if (!is<SVGSVGElement>(this))
return false;
// Element may not be in the document, pretend we're outermost for viewport(), getCTM(), etc.
if (!parentNode())
return true;
// We act like an outermost SVG element, if we're a direct child of a <foreignObject> element.
if (is<SVGForeignObjectElement>(parentNode()))
return true;
// If we're inside the shadow tree of a <use> element, we're always an inner <svg> element.
if (isInShadowTree() && is<SVGUseElement>(shadowHost()))
return false;
// This is true whenever this is the outermost SVG, even if there are HTML elements outside it
return !is<SVGElement>(parentNode());
}
void SVGElement::reportAttributeParsingError(SVGParsingError error, const QualifiedName& name, const AtomString& value)
{
if (error == NoError)
return;
String errorString = "<" + tagName() + "> attribute " + name.toString() + "=\"" + value + "\"";
SVGDocumentExtensions& extensions = document().accessSVGExtensions();
if (error == NegativeValueForbiddenError) {
extensions.reportError("Invalid negative value for " + errorString);
return;
}
if (error == ParsingAttributeFailedError) {
extensions.reportError("Invalid value for " + errorString);
return;
}
ASSERT_NOT_REACHED();
}
void SVGElement::removedFromAncestor(RemovalType removalType, ContainerNode& oldParentOfRemovedTree)
{
if (removalType.disconnectedFromDocument)
updateRelativeLengthsInformation(false, *this);
StyledElement::removedFromAncestor(removalType, oldParentOfRemovedTree);
if (hasPendingResources())
treeScopeForSVGReferences().removeElementFromPendingSVGResources(*this);
if (removalType.disconnectedFromDocument) {
auto& extensions = document().accessSVGExtensions();
if (m_svgRareData) {
for (auto& element : m_svgRareData->takeReferencingElements()) {
extensions.addElementToRebuild(element);
Ref { element }->clearTarget();
}
RELEASE_ASSERT(m_svgRareData->referencingElements().isEmptyIgnoringNullReferences());
}
extensions.removeElementToRebuild(*this);
}
invalidateInstances();
if (removalType.treeScopeChanged && oldParentOfRemovedTree.isUserAgentShadowRoot())
setCorrespondingElement(nullptr);
}
SVGSVGElement* SVGElement::ownerSVGElement() const
{
auto* node = parentNode();
while (node) {
if (auto* svg = dynamicDowncast<SVGSVGElement>(*node))
return svg;
node = node->parentOrShadowHostNode();
}
return nullptr;
}
SVGElement* SVGElement::viewportElement() const
{
// This function needs shadow tree support - as RenderSVGContainer uses this function
// to determine the "overflow" property. <use> on <symbol> wouldn't work otherwhise.
auto* node = parentNode();
while (node) {
if (is<SVGSVGElement>(*node) || is<SVGImageElement>(*node) || node->hasTagName(SVGNames::symbolTag))
return downcast<SVGElement>(node);
node = node->parentOrShadowHostNode();
}
return nullptr;
}
const WeakHashSet<SVGElement, WeakPtrImplWithEventTargetData>& SVGElement::instances() const
{
if (!m_svgRareData) {
static NeverDestroyed<WeakHashSet<SVGElement, WeakPtrImplWithEventTargetData>> emptyInstances;
return emptyInstances;
}
return m_svgRareData->instances();
}
std::optional<FloatRect> SVGElement::getBoundingBox() const
{
if (is<SVGGraphicsElement>(*this)) {
if (auto renderer = this->renderer())
return renderer->objectBoundingBox();
}
return std::nullopt;
}
Vector<Ref<SVGElement>> SVGElement::referencingElements() const
{
if (!m_svgRareData)
return { };
return copyToVectorOf<Ref<SVGElement>>(m_svgRareData->referencingElements());
}
void SVGElement::addReferencingElement(SVGElement& element)
{
ensureSVGRareData().addReferencingElement(element);
auto& rareDataOfReferencingElement = element.ensureSVGRareData();
RELEASE_ASSERT(!rareDataOfReferencingElement.referenceTarget());
rareDataOfReferencingElement.setReferenceTarget(*this);
}
void SVGElement::removeReferencingElement(SVGElement& element)
{
ensureSVGRareData().removeReferencingElement(element);
element.ensureSVGRareData().setReferenceTarget(nullptr);
}
void SVGElement::removeElementReference()
{
if (!m_svgRareData)
return;
if (RefPtr destination = m_svgRareData->referenceTarget())
destination->removeReferencingElement(*this);
}
Vector<WeakPtr<SVGResourceElementClient>> SVGElement::referencingCSSClients() const
{
if (!m_svgRareData)
return { };
return copyToVector(m_svgRareData->referencingCSSClients());
}
void SVGElement::addReferencingCSSClient(SVGResourceElementClient& client)
{
ensureSVGRareData().addReferencingCSSClient(client);
}
void SVGElement::removeReferencingCSSClient(SVGResourceElementClient& client)
{
if (!m_svgRareData)
return;
ensureSVGRareData().removeReferencingCSSClient(client);
}
SVGElement* SVGElement::correspondingElement() const
{
return m_svgRareData ? m_svgRareData->correspondingElement() : nullptr;
}
RefPtr<SVGUseElement> SVGElement::correspondingUseElement() const
{
auto* root = containingShadowRoot();
if (!root)
return nullptr;
if (root->mode() != ShadowRootMode::UserAgent)
return nullptr;
auto* host = root->host();
if (!is<SVGUseElement>(host))
return nullptr;
return &downcast<SVGUseElement>(*host);
}
void SVGElement::setCorrespondingElement(SVGElement* correspondingElement)
{
if (m_svgRareData) {
if (RefPtr oldCorrespondingElement = m_svgRareData->correspondingElement())
oldCorrespondingElement->m_svgRareData->removeInstance(*this);
}
if (m_svgRareData || correspondingElement)
ensureSVGRareData().setCorrespondingElement(correspondingElement);
if (correspondingElement)
correspondingElement->ensureSVGRareData().addInstance(*this);
}
bool SVGElement::haveLoadedRequiredResources()
{
for (auto& child : childrenOfType<SVGElement>(*this)) {
if (!child.haveLoadedRequiredResources())
return false;
}
return true;
}
bool SVGElement::addEventListener(const AtomString& eventType, Ref<EventListener>&& listener, const AddEventListenerOptions& options)
{
// Add event listener to regular DOM element
if (!Node::addEventListener(eventType, listener.copyRef(), options))
return false;
if (containingShadowRoot())
return true;
// Add event listener to all shadow tree DOM element instances
ASSERT(!instanceUpdatesBlocked());
for (auto& instance : copyToVectorOf<Ref<SVGElement>>(instances())) {
ASSERT(instance->correspondingElement() == this);
ASSERT(instance->isInUserAgentShadowTree());
bool result = instance->Node::addEventListener(eventType, listener.copyRef(), options);
ASSERT_UNUSED(result, result);
}
return true;
}
bool SVGElement::removeEventListener(const AtomString& eventType, EventListener& listener, const EventListenerOptions& options)
{
if (containingShadowRoot())
return Node::removeEventListener(eventType, listener, options);
// EventTarget::removeEventListener creates a Ref around the given EventListener
// object when creating a temporary RegisteredEventListener object used to look up the
// event listener in a cache. If we want to be able to call removeEventListener() multiple
// times on different nodes, we have to delay its immediate destruction, which would happen
// after the first call below.
Ref<EventListener> protector(listener);
// Remove event listener from regular DOM element
if (!Node::removeEventListener(eventType, listener, options))
return false;
// Remove event listener from all shadow tree DOM element instances
ASSERT(!instanceUpdatesBlocked());
for (auto& instance : copyToVectorOf<Ref<SVGElement>>(instances())) {
ASSERT(instance->correspondingElement() == this);
ASSERT(instance->isInUserAgentShadowTree());
if (instance->Node::removeEventListener(eventType, listener, options))
continue;
// This case can only be hit for event listeners created from markup
ASSERT(JSEventListener::wasCreatedFromMarkup(listener));
// If the event listener 'listener' has been created from markup and has been fired before
// then JSLazyEventListener::parseCode() has been called and m_jsFunction of that listener
// has been created (read: it's not 0 anymore). During shadow tree creation, the event
// listener DOM attribute has been cloned, and another event listener has been setup in
// the shadow tree. If that event listener has not been used yet, m_jsFunction is still 0,
// and tryRemoveEventListener() above will fail. Work around that very rare problem.
ASSERT(instance->eventTargetData());
instance->eventTargetData()->eventListenerMap.removeFirstEventListenerCreatedFromMarkup(eventType);
}
return true;
}
static bool hasLoadListener(Element* element)
{
if (element->hasEventListeners(eventNames().loadEvent))
return true;
for (element = element->parentOrShadowHostElement(); element; element = element->parentOrShadowHostElement()) {
if (element->hasCapturingEventListeners(eventNames().loadEvent))
return true;
}
return false;
}
void SVGElement::sendLoadEventIfPossible()
{
if (!isConnected() || !document().frame())
return;
if (!haveLoadedRequiredResources() || !hasLoadListener(this))
return;
dispatchEvent(Event::create(eventNames().loadEvent, Event::CanBubble::No, Event::IsCancelable::No));
}
void SVGElement::loadEventTimerFired()
{
sendLoadEventIfPossible();
}
Timer* SVGElement::loadEventTimer()
{
ASSERT_NOT_REACHED();
return nullptr;
}
void SVGElement::finishParsingChildren()
{
StyledElement::finishParsingChildren();
if (isOutermostSVGSVGElement())
return;
// Notify all the elements which have references to this element to rebuild their shadow and render
// trees, e.g. a <use> element references a target element before this target element is defined.
invalidateInstances();
}
#if ENABLE(LAYER_BASED_SVG_ENGINE)
static inline bool isSVGLayerAwareElement(const SVGElement& element)
{
using namespace ElementNames;
switch (element.elementName()) {
case SVG::a:
case SVG::altGlyph:
case SVG::circle:
case SVG::defs:
case SVG::ellipse:
case SVG::foreignObject:
case SVG::g:
case SVG::image:
case SVG::line:
case SVG::path:
case SVG::polygon:
case SVG::polyline:
case SVG::rect:
case SVG::svg:
case SVG::switch_:
case SVG::symbol:
case SVG::textPath:
case SVG::text:
case SVG::tref:
case SVG::tspan:
case SVG::use:
return true;
default:
break;
}
return false;
}
#endif
bool SVGElement::childShouldCreateRenderer(const Node& child) const
{
if (!child.isSVGElement())
return false;
auto& svgChild = downcast<SVGElement>(child);
#if ENABLE(LAYER_BASED_SVG_ENGINE)
// If the layer based SVG engine is enabled, all renderers that do not support the
// RenderLayer aware layout / painting / hit-testing mode ('LBSE-mode') have to be skipped.
// FIXME: [LBSE] Upstream support for all elements, and remove 'isSVGLayerAwareElement' check afterwards.
if (document().settings().layerBasedSVGEngineEnabled() && !isSVGLayerAwareElement(svgChild))
return false;
#endif
switch (svgChild.elementName()) {
case ElementNames::SVG::altGlyph:
case ElementNames::SVG::textPath:
case ElementNames::SVG::tref:
case ElementNames::SVG::tspan:
return false;
default:
break;
}
return svgChild.isValid();
}
void SVGElement::attributeChanged(const QualifiedName& name, const AtomString& oldValue, const AtomString& newValue, AttributeModificationReason attributeModificationReason)
{
StyledElement::attributeChanged(name, oldValue, newValue, attributeModificationReason);
switch (name.nodeName()) {
case AttributeNames::idAttr:
document().accessSVGExtensions().rebuildAllElementReferencesForTarget(*this);
break;
case AttributeNames::classAttr:
m_className->setBaseValInternal(newValue);
break;
case AttributeNames::tabindexAttr:
if (newValue.isEmpty())
setTabIndexExplicitly(std::nullopt);
else if (auto optionalTabIndex = parseHTMLInteger(newValue))
setTabIndexExplicitly(optionalTabIndex.value());
break;
default:
if (auto& eventName = HTMLElement::eventNameForEventHandlerAttribute(name); !eventName.isNull())
setAttributeEventListener(eventName, name, newValue);
break;
}
// Changes to the style attribute are processed lazily (see Element::getAttribute() and related methods),
// so we don't want changes to the style attribute to result in extra work here except invalidateInstances().
if (name == HTMLNames::styleAttr)
invalidateInstances();
else
svgAttributeChanged(name);
}
void SVGElement::synchronizeAttribute(const QualifiedName& name)
{
// If the value of the property has changed, serialize the new value to the attribute.
if (auto value = propertyRegistry().synchronize(name))
setSynchronizedLazyAttribute(name, AtomString { *value });
}
void SVGElement::synchronizeAllAttributes()
{
// SVGPropertyRegistry::synchronizeAllAttributes() returns the new values of
// the properties which have changed but not committed yet.
auto map = propertyRegistry().synchronizeAllAttributes();
for (const auto& entry : map)
setSynchronizedLazyAttribute(entry.key, AtomString { entry.value });
}
void SVGElement::commitPropertyChange(SVGProperty* property)
{
// We want to dirty the top-level property when a descendant changes. For example
// a change in an SVGLength item in SVGLengthList should set the dirty flag on
// SVGLengthList and not the SVGLength.
property->setDirty();
setAnimatedSVGAttributesAreDirty();
svgAttributeChanged(propertyRegistry().propertyAttributeName(*property));
}
void SVGElement::commitPropertyChange(SVGAnimatedProperty& animatedProperty)
{
QualifiedName attributeName = propertyRegistry().animatedPropertyAttributeName(animatedProperty);
ASSERT(attributeName != nullQName());
// A change in a style property, e.g SVGRectElement::x should be serialized to
// the attribute immediately. Otherwise it is okay to be lazy in this regard.
if (!propertyRegistry().isAnimatedStylePropertyAttribute(attributeName))
propertyRegistry().setAnimatedPropertyDirty(attributeName, animatedProperty);
else
setSynchronizedLazyAttribute(attributeName, AtomString { animatedProperty.baseValAsString() });
setAnimatedSVGAttributesAreDirty();
svgAttributeChanged(attributeName);
}
bool SVGElement::isAnimatedPropertyAttribute(const QualifiedName& attributeName) const
{
return propertyRegistry().isAnimatedPropertyAttribute(attributeName);
}
bool SVGElement::isAnimatedAttribute(const QualifiedName& attributeName) const
{
return SVGPropertyAnimatorFactory::isKnownAttribute(attributeName) || isAnimatedPropertyAttribute(attributeName);
}
bool SVGElement::isAnimatedStyleAttribute(const QualifiedName& attributeName) const
{
return SVGPropertyAnimatorFactory::isKnownAttribute(attributeName) || propertyRegistry().isAnimatedStylePropertyAttribute(attributeName);
}
RefPtr<SVGAttributeAnimator> SVGElement::createAnimator(const QualifiedName& attributeName, AnimationMode animationMode, CalcMode calcMode, bool isAccumulated, bool isAdditive)
{
// Property animator, e.g. "fill" or "fill-opacity".
if (auto animator = propertyAnimatorFactory().createAnimator(attributeName, animationMode, calcMode, isAccumulated, isAdditive))
return animator;
// Animated property animator.
auto animator = propertyRegistry().createAnimator(attributeName, animationMode, calcMode, isAccumulated, isAdditive);
if (!animator)
return animator;
for (auto& instance : copyToVectorOf<Ref<SVGElement>>(instances()))
instance->propertyRegistry().appendAnimatedInstance(attributeName, *animator);
return animator;
}
void SVGElement::animatorWillBeDeleted(const QualifiedName& attributeName)
{
propertyAnimatorFactory().animatorWillBeDeleted(attributeName);
}
std::optional<Style::ResolvedStyle> SVGElement::resolveCustomStyle(const Style::ResolutionContext& resolutionContext, const RenderStyle*)
{
// If the element is in a <use> tree we get the style from the definition tree.
if (RefPtr styleElement = this->correspondingElement()) {
auto styleElementResolutionContext = resolutionContext;
// Can't use the state since we are going to another part of the tree.
styleElementResolutionContext.selectorMatchingState = nullptr;
styleElementResolutionContext.isSVGUseTreeRoot = true;
auto resolvedStyle = styleElement->resolveStyle(styleElementResolutionContext);
Style::Adjuster::adjustSVGElementStyle(*resolvedStyle.style, *this);
return resolvedStyle;
}
return resolveStyle(resolutionContext);
}
MutableStyleProperties* SVGElement::animatedSMILStyleProperties() const
{
if (m_svgRareData)
return m_svgRareData->animatedSMILStyleProperties();
return 0;
}
MutableStyleProperties& SVGElement::ensureAnimatedSMILStyleProperties()
{
return ensureSVGRareData().ensureAnimatedSMILStyleProperties();
}
void SVGElement::setUseOverrideComputedStyle(bool value)
{
if (m_svgRareData)
m_svgRareData->setUseOverrideComputedStyle(value);
}
inline const RenderStyle* SVGElementRareData::overrideComputedStyle(Element& element, const RenderStyle* parentStyle)
{
if (!m_useOverrideComputedStyle)
return nullptr;
if (!m_overrideComputedStyle || m_needsOverrideComputedStyleUpdate) {
// The style computed here contains no CSS Animations/Transitions or SMIL induced rules - this is needed to compute the "base value" for the SMIL animation sandwhich model.
m_overrideComputedStyle = element.styleResolver().styleForElement(element, { parentStyle }, RuleMatchingBehavior::MatchAllRulesExcludingSMIL).style;
m_needsOverrideComputedStyleUpdate = false;
}
ASSERT(m_overrideComputedStyle);
return m_overrideComputedStyle.get();
}
const RenderStyle* SVGElement::computedStyle(PseudoId pseudoElementSpecifier)
{
if (!m_svgRareData || !m_svgRareData->useOverrideComputedStyle())
return Element::computedStyle(pseudoElementSpecifier);
const RenderStyle* parentStyle = nullptr;
if (RefPtr parent = parentOrShadowHostElement()) {
if (auto renderer = parent->renderer())
parentStyle = &renderer->style();
}
return m_svgRareData->overrideComputedStyle(*this, parentStyle);
}
ColorInterpolation SVGElement::colorInterpolation() const
{
if (auto renderer = this->renderer())
return renderer->style().svgStyle().colorInterpolationFilters();
// Try to determine the property value from the computed style.
if (auto value = ComputedStyleExtractor(const_cast<SVGElement*>(this)).propertyValue(CSSPropertyColorInterpolationFilters, ComputedStyleExtractor::UpdateLayout::No))
return fromCSSValue<ColorInterpolation>(*value);
return ColorInterpolation::Auto;
}
QualifiedName SVGElement::animatableAttributeForName(const AtomString& localName)
{
static NeverDestroyed animatableAttributes = [] {
static constexpr std::array names {
&HTMLNames::classAttr,
&SVGNames::amplitudeAttr,
&SVGNames::azimuthAttr,
&SVGNames::baseFrequencyAttr,
&SVGNames::biasAttr,
&SVGNames::clipPathUnitsAttr,
&SVGNames::cxAttr,
&SVGNames::cyAttr,
&SVGNames::diffuseConstantAttr,
&SVGNames::divisorAttr,
&SVGNames::dxAttr,
&SVGNames::dyAttr,
&SVGNames::edgeModeAttr,
&SVGNames::elevationAttr,
&SVGNames::exponentAttr,
&SVGNames::filterUnitsAttr,
&SVGNames::fxAttr,
&SVGNames::fyAttr,
&SVGNames::gradientTransformAttr,
&SVGNames::gradientUnitsAttr,
&SVGNames::heightAttr,
&SVGNames::in2Attr,
&SVGNames::inAttr,
&SVGNames::interceptAttr,
&SVGNames::k1Attr,
&SVGNames::k2Attr,
&SVGNames::k3Attr,
&SVGNames::k4Attr,
&SVGNames::kernelMatrixAttr,
&SVGNames::kernelUnitLengthAttr,
&SVGNames::lengthAdjustAttr,
&SVGNames::limitingConeAngleAttr,
&SVGNames::markerHeightAttr,
&SVGNames::markerUnitsAttr,
&SVGNames::markerWidthAttr,
&SVGNames::maskContentUnitsAttr,
&SVGNames::maskUnitsAttr,
&SVGNames::methodAttr,
&SVGNames::modeAttr,
&SVGNames::numOctavesAttr,
&SVGNames::offsetAttr,
&SVGNames::operatorAttr,
&SVGNames::orderAttr,
&SVGNames::orientAttr,
&SVGNames::pathLengthAttr,
&SVGNames::patternContentUnitsAttr,
&SVGNames::patternTransformAttr,
&SVGNames::patternUnitsAttr,
&SVGNames::pointsAtXAttr,
&SVGNames::pointsAtYAttr,
&SVGNames::pointsAtZAttr,
&SVGNames::preserveAlphaAttr,
&SVGNames::preserveAspectRatioAttr,
&SVGNames::primitiveUnitsAttr,
&SVGNames::radiusAttr,
&SVGNames::rAttr,
&SVGNames::refXAttr,
&SVGNames::refYAttr,
&SVGNames::resultAttr,
&SVGNames::rotateAttr,
&SVGNames::rxAttr,
&SVGNames::ryAttr,
&SVGNames::scaleAttr,
&SVGNames::seedAttr,
&SVGNames::slopeAttr,
&SVGNames::spacingAttr,
&SVGNames::specularConstantAttr,
&SVGNames::specularExponentAttr,
&SVGNames::spreadMethodAttr,
&SVGNames::startOffsetAttr,
&SVGNames::stdDeviationAttr,
&SVGNames::stitchTilesAttr,
&SVGNames::surfaceScaleAttr,
&SVGNames::tableValuesAttr,
&SVGNames::targetAttr,
&SVGNames::targetXAttr,
&SVGNames::targetYAttr,
&SVGNames::transformAttr,
&SVGNames::typeAttr,
&SVGNames::valuesAttr,
&SVGNames::viewBoxAttr,
&SVGNames::widthAttr,
&SVGNames::x1Attr,
&SVGNames::x2Attr,
&SVGNames::xAttr,
&SVGNames::xChannelSelectorAttr,
&SVGNames::y1Attr,
&SVGNames::y2Attr,
&SVGNames::yAttr,
&SVGNames::yChannelSelectorAttr,
&SVGNames::zAttr,
&SVGNames::hrefAttr,
};
MemoryCompactLookupOnlyRobinHoodHashMap<AtomString, QualifiedName> map;
for (auto& name : names) {
auto addResult = map.add(name->get().localName(), *name);
ASSERT_UNUSED(addResult, addResult.isNewEntry);
}
return map;
}();
return animatableAttributes.get().get(localName);
}
#ifndef NDEBUG
bool SVGElement::isAnimatableAttribute(const QualifiedName& name) const
{
if (animatableAttributeForName(name.localName()) == name)
return !filterOutAnimatableAttribute(name);
return false;
}
bool SVGElement::filterOutAnimatableAttribute(const QualifiedName&) const
{
return false;
}
#endif
String SVGElement::title() const
{
// According to spec, for stand-alone SVG documents we should not return a title when
// hovering over the rootmost SVG element (the first <title> element is the title of
// the document, not a tooltip) so we instantly return.
if (isOutermostSVGSVGElement() && document().topDocument().isSVGDocument())
return String();
auto firstTitle = childrenOfType<SVGTitleElement>(*this).first();
return firstTitle ? const_cast<SVGTitleElement*>(firstTitle)->innerText() : String();
}
bool SVGElement::rendererIsNeeded(const RenderStyle& style)
{
// http://www.w3.org/TR/SVG/extend.html#PrivateData
// Prevent anything other than SVG renderers from appearing in our render tree
// Spec: SVG allows inclusion of elements from foreign namespaces anywhere
// with the SVG content. In general, the SVG user agent will include the unknown
// elements in the DOM but will otherwise ignore unknown elements.
if (!parentOrShadowHostElement() || is<SVGElement>(*parentOrShadowHostElement()))
return StyledElement::rendererIsNeeded(style);
return false;
}
CSSPropertyID SVGElement::cssPropertyIdForSVGAttributeName(const QualifiedName& attrName)
{
if (!attrName.namespaceURI().isNull())
return CSSPropertyInvalid;
static NeverDestroyed properties = createAttributeNameToCSSPropertyIDMap();
return properties.get().get(attrName.localName());
}
bool SVGElement::hasPresentationalHintsForAttribute(const QualifiedName& name) const
{
if (cssPropertyIdForSVGAttributeName(name) > 0)
return true;
return StyledElement::hasPresentationalHintsForAttribute(name);
}
void SVGElement::collectPresentationalHintsForAttribute(const QualifiedName& name, const AtomString& value, MutableStyleProperties& style)
{
CSSPropertyID propertyID = cssPropertyIdForSVGAttributeName(name);
if (propertyID > 0)
addPropertyToPresentationalHintStyle(style, propertyID, value);
}
void SVGElement::updateSVGRendererForElementChange()
{
document().updateSVGRenderer(*this);
}
void SVGElement::svgAttributeChanged(const QualifiedName& attrName)
{
CSSPropertyID propId = cssPropertyIdForSVGAttributeName(attrName);
if (propId > 0) {
invalidateInstances();
return;
}
if (attrName == HTMLNames::classAttr) {
classAttributeChanged(className());
invalidateInstances();
return;
}
if (attrName == HTMLNames::idAttr) {
auto renderer = this->renderer();
// Notify resources about id changes, this is important as we cache resources by id in SVGDocumentExtensions
if (is<RenderSVGResourceContainer>(renderer))
downcast<RenderSVGResourceContainer>(*renderer).idChanged();
if (isConnected())
buildPendingResourcesIfNeeded();
invalidateInstances();
return;
}
}
Node::InsertedIntoAncestorResult SVGElement::insertedIntoAncestor(InsertionType insertionType, ContainerNode& parentOfInsertedTree)
{
StyledElement::insertedIntoAncestor(insertionType, parentOfInsertedTree);
updateRelativeLengthsInformation();
if (needsPendingResourceHandling() && insertionType.connectedToDocument && !isInShadowTree()) {
if (treeScopeForSVGReferences().isIdOfPendingSVGResource(getIdAttribute()))
return InsertedIntoAncestorResult::NeedsPostInsertionCallback;
}
hideNonce();
return InsertedIntoAncestorResult::Done;
}
void SVGElement::didFinishInsertingNode()
{
buildPendingResourcesIfNeeded();
}
void SVGElement::buildPendingResourcesIfNeeded()
{
if (!needsPendingResourceHandling() || !isConnected() || isInShadowTree())
return;
auto& treeScope = treeScopeForSVGReferences();
auto resourceId = getIdAttribute();
if (!treeScope.isIdOfPendingSVGResource(resourceId))
return;
treeScope.markPendingSVGResourcesForRemoval(resourceId);
// Rebuild pending resources for each client of a pending resource that is being removed.
while (auto clientElement = treeScope.takeElementFromPendingSVGResourcesForRemovalMap(resourceId)) {
ASSERT(clientElement->hasPendingResources());
if (clientElement->hasPendingResources()) {
clientElement->buildPendingResource();
if (auto renderer = clientElement->renderer()) {
for (auto& ancestor : ancestorsOfType<RenderSVGResourceContainer>(*renderer))
ancestor.markAllClientsForRepaint();
}
treeScope.clearHasPendingSVGResourcesIfPossible(*clientElement);
}
}
}
void SVGElement::childrenChanged(const ChildChange& change)
{
StyledElement::childrenChanged(change);
if (change.source == ChildChange::Source::Parser)
return;
invalidateInstances();
}
bool SVGElement::instanceUpdatesBlocked() const
{
return m_svgRareData && m_svgRareData->instanceUpdatesBlocked();
}
void SVGElement::setInstanceUpdatesBlocked(bool value)
{
// Catch any callers that calls setInstanceUpdatesBlocked(true) twice in a row.
// That probably indicates nested use of InstanceUpdateBlocker and a bug.
ASSERT(!value || !instanceUpdatesBlocked());
if (m_svgRareData)
m_svgRareData->setInstanceUpdatesBlocked(value);
}
AffineTransform SVGElement::localCoordinateSpaceTransform(SVGLocatable::CTMScope) const
{
// To be overridden by SVGGraphicsElement (or as special case SVGTextElement and SVGPatternElement)
return AffineTransform();
}
void SVGElement::updateRelativeLengthsInformation(bool hasRelativeLengths, SVGElement& element)
{
// If we're not yet in a document, this function will be called again from insertedIntoAncestor(). Do nothing now.
if (!isConnected())
return;
// An element wants to notify us that its own relative lengths state changed.
// Register it in the relative length map, and register us in the parent relative length map.
// Register the parent in the grandparents map, etc. Repeat procedure until the root of the SVG tree.
if (hasRelativeLengths)
m_elementsWithRelativeLengths.add(element);
else {
bool neverRegistered = !m_elementsWithRelativeLengths.contains(element);
if (neverRegistered)
return;
m_elementsWithRelativeLengths.remove(element);
}
if (is<SVGGraphicsElement>(element)) {
if (RefPtr parent = parentNode(); is<SVGElement>(parent))
downcast<SVGElement>(*parent).updateRelativeLengthsInformation(hasRelativeLengths, *this);
}
}
bool SVGElement::accessKeyAction(bool sendMouseEvents)
{
return dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
}
void SVGElement::invalidateInstances()
{
if (instanceUpdatesBlocked())
return;
for (auto& instance : copyToVectorOf<Ref<SVGElement>>(instances())) {
if (auto useElement = instance->correspondingUseElement())
useElement->invalidateShadowTree();
instance->setCorrespondingElement(nullptr);
}
}
SVGConditionalProcessingAttributes& SVGElement::conditionalProcessingAttributes()
{
return ensureSVGRareData().conditionalProcessingAttributes(*this);
}
SVGConditionalProcessingAttributes* SVGElement::conditionalProcessingAttributesIfExists() const
{
if (!m_svgRareData)
return nullptr;
return m_svgRareData->conditionalProcessingAttributesIfExists();
}
bool SVGElement::hasAssociatedSVGLayoutBox() const
{
if (!renderer())
return false;
// Legacy SVG engine specific condition.
if (renderer()->isLegacySVGRoot())
return false;
#if ENABLE(LAYER_BASED_SVG_ENGINE)
// LBSE specific condition.
if (document().settings().layerBasedSVGEngineEnabled())
return false;
#endif
return true;
}
}
|