#include "config.h"
#include "RenderCounter.h"
#include "CounterNode.h"
#include "Document.h"
#include "Element.h"
#include "ElementTraversal.h"
#include "HTMLNames.h"
#include "HTMLOListElement.h"
#include "PseudoElement.h"
#include "RenderListItem.h"
#include "RenderListMarker.h"
#include "RenderStyle.h"
#include "RenderView.h"
#include <wtf/IsoMallocInlines.h>
#include <wtf/StdLibExtras.h>
#if ENABLE(TREE_DEBUGGING)
#include <stdio.h>
#endif
namespace WebCore {
using namespace HTMLNames;
WTF_MAKE_ISO_ALLOCATED_IMPL(RenderCounter);
using CounterMap = HashMap<AtomicString, Ref<CounterNode>>;
using CounterMaps = HashMap<const RenderElement*, std::unique_ptr<CounterMap>>;
static CounterNode* makeCounterNode(RenderElement&, const AtomicString& identifier, bool alwaysCreateCounter);
static CounterMaps& counterMaps()
{
static NeverDestroyed<CounterMaps> staticCounterMaps;
return staticCounterMaps;
}
static RenderElement* previousInPreOrder(const RenderElement& renderer)
{
ASSERT(renderer.element());
Element* previous = ElementTraversal::previousIncludingPseudo(*renderer.element());
while (previous && !previous->renderer())
previous = ElementTraversal::previousIncludingPseudo(*previous);
return previous ? previous->renderer() : 0;
}
static inline Element* parentOrPseudoHostElement(const RenderElement& renderer)
{
if (renderer.isPseudoElement())
return renderer.generatingElement();
return renderer.element() ? renderer.element()->parentElement() : nullptr;
}
static RenderElement* previousSiblingOrParent(const RenderElement& renderer)
{
ASSERT(renderer.element());
Element* previous = ElementTraversal::pseudoAwarePreviousSibling(*renderer.element());
while (previous && !previous->renderer())
previous = ElementTraversal::pseudoAwarePreviousSibling(*previous);
if (previous)
return previous->renderer();
previous = parentOrPseudoHostElement(renderer);
return previous ? previous->renderer() : nullptr;
}
static inline bool areRenderersElementsSiblings(const RenderElement& first, const RenderElement& second)
{
return parentOrPseudoHostElement(first) == parentOrPseudoHostElement(second);
}
static RenderElement* nextInPreOrder(const RenderElement& renderer, const Element* stayWithin, bool skipDescendants = false)
{
ASSERT(renderer.element());
Element& self = *renderer.element();
Element* next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(self, stayWithin) : ElementTraversal::nextIncludingPseudo(self, stayWithin);
while (next && !next->renderer())
next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(*next, stayWithin) : ElementTraversal::nextIncludingPseudo(*next, stayWithin);
return next ? next->renderer() : nullptr;
}
static CounterDirectives listItemCounterDirectives(RenderElement& renderer)
{
if (is<RenderListItem>(renderer)) {
auto& item = downcast<RenderListItem>(renderer);
if (auto explicitValue = item.explicitValue())
return { *explicitValue, std::nullopt };
return { std::nullopt, item.isInReversedOrderedList() ? -1 : 1 };
}
if (auto element = renderer.element()) {
if (is<HTMLOListElement>(*element)) {
auto& list = downcast<HTMLOListElement>(*element);
return { list.start(), list.isReversed() ? 1 : -1 };
}
if (isHTMLListElement(*element))
return { 0, std::nullopt };
}
return { };
}
struct CounterPlan {
bool isReset;
int value;
};
static std::optional<CounterPlan> planCounter(RenderElement& renderer, const AtomicString& identifier)
{
Element* generatingElement = renderer.generatingElement();
if (!generatingElement)
return std::nullopt;
auto& style = renderer.style();
switch (style.styleType()) {
case PseudoId::None:
if (generatingElement->renderer() != &renderer)
return std::nullopt;
break;
case PseudoId::Before:
case PseudoId::After:
break;
default:
return std::nullopt; }
CounterDirectives directives;
if (auto map = style.counterDirectives())
directives = map->get(identifier);
if (identifier == "list-item") {
auto itemDirectives = listItemCounterDirectives(renderer);
if (!directives.resetValue)
directives.resetValue = itemDirectives.resetValue;
if (!directives.incrementValue)
directives.incrementValue = itemDirectives.incrementValue;
}
if (directives.resetValue)
return CounterPlan { true, saturatedAddition(*directives.resetValue, directives.incrementValue.value_or(0)) };
if (directives.incrementValue)
return CounterPlan { false, *directives.incrementValue };
return std::nullopt;
}
struct CounterInsertionPoint {
RefPtr<CounterNode> parent;
RefPtr<CounterNode> previousSibling;
};
static CounterInsertionPoint findPlaceForCounter(RenderElement& counterOwner, const AtomicString& identifier, bool isReset)
{
RenderElement* searchEndRenderer = previousSiblingOrParent(counterOwner);
RenderElement* currentRenderer = previousInPreOrder(counterOwner);
RefPtr<CounterNode> previousSibling;
while (currentRenderer) {
auto currentCounter = makeCounterNode(*currentRenderer, identifier, false);
if (searchEndRenderer == currentRenderer) {
if (currentCounter) {
if (previousSibling) {
if (currentCounter->actsAsReset()) {
if (isReset && areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
auto* parent = currentCounter->parent();
return { parent, parent ? currentCounter : nullptr };
}
if (previousSibling->parent() != currentCounter)
previousSibling = nullptr;
return { currentCounter, WTFMove(previousSibling) };
}
if (!isReset || !areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
if (currentCounter->parent() != previousSibling->parent())
return { };
return { currentCounter->parent(), WTFMove(previousSibling) };
}
} else {
if (currentCounter->actsAsReset()) {
if (isReset && areRenderersElementsSiblings(*currentRenderer, counterOwner))
return { currentCounter->parent(), currentCounter };
return { currentCounter, WTFMove(previousSibling) };
}
if (!isReset || !areRenderersElementsSiblings(*currentRenderer, counterOwner))
return { currentCounter->parent(), currentCounter };
previousSibling = currentCounter;
}
}
searchEndRenderer = previousSiblingOrParent(*currentRenderer);
} else {
if (currentCounter) {
if (previousSibling) {
if (currentCounter->actsAsReset()) {
previousSibling = currentCounter;
currentRenderer = parentOrPseudoHostElement(*currentRenderer)->renderer();
continue;
}
} else
previousSibling = currentCounter;
currentRenderer = previousSiblingOrParent(*currentRenderer);
continue;
}
}
if (previousSibling)
currentRenderer = previousSiblingOrParent(*currentRenderer);
else
currentRenderer = previousInPreOrder(*currentRenderer);
}
return { };
}
static CounterNode* makeCounterNode(RenderElement& renderer, const AtomicString& identifier, bool alwaysCreateCounter)
{
if (renderer.hasCounterNodeMap()) {
ASSERT(counterMaps().contains(&renderer));
if (auto* node = counterMaps().find(&renderer)->value->get(identifier))
return node;
}
auto plan = planCounter(renderer, identifier);
if (!plan && !alwaysCreateCounter)
return nullptr;
auto& maps = counterMaps();
auto newNode = CounterNode::create(renderer, plan && plan->isReset, plan ? plan->value : 0);
auto place = findPlaceForCounter(renderer, identifier, plan && plan->isReset);
if (place.parent)
place.parent->insertAfter(newNode, place.previousSibling.get(), identifier);
maps.add(&renderer, std::make_unique<CounterMap>()).iterator->value->add(identifier, newNode.copyRef());
renderer.setHasCounterNodeMap(true);
if (newNode->parent())
return newNode.ptr();
auto* currentRenderer = &renderer;
auto* stayWithin = parentOrPseudoHostElement(renderer);
bool skipDescendants = false;
while ((currentRenderer = nextInPreOrder(*currentRenderer, stayWithin, skipDescendants))) {
skipDescendants = false;
if (!currentRenderer->hasCounterNodeMap())
continue;
auto* currentCounter = maps.find(currentRenderer)->value->get(identifier);
if (!currentCounter)
continue;
skipDescendants = true;
if (currentCounter->parent())
continue;
if (stayWithin == parentOrPseudoHostElement(*currentRenderer) && currentCounter->hasResetType())
break;
newNode->insertAfter(*currentCounter, newNode->lastChild(), identifier);
}
return newNode.ptr();
}
RenderCounter::RenderCounter(Document& document, const CounterContent& counter)
: RenderText(document, emptyString())
, m_counter(counter)
{
view().addRenderCounter();
}
RenderCounter::~RenderCounter()
{
}
void RenderCounter::willBeDestroyed()
{
view().removeRenderCounter();
if (m_counterNode) {
m_counterNode->removeRenderer(*this);
ASSERT(!m_counterNode);
}
RenderText::willBeDestroyed();
}
const char* RenderCounter::renderName() const
{
return "RenderCounter";
}
bool RenderCounter::isCounter() const
{
return true;
}
String RenderCounter::originalText() const
{
if (!m_counterNode) {
RenderElement* beforeAfterContainer = parent();
while (true) {
if (!beforeAfterContainer)
return String();
if (!beforeAfterContainer->isAnonymous() && !beforeAfterContainer->isPseudoElement())
return String(); PseudoId containerStyle = beforeAfterContainer->style().styleType();
if ((containerStyle == PseudoId::Before) || (containerStyle == PseudoId::After))
break;
beforeAfterContainer = beforeAfterContainer->parent();
}
makeCounterNode(*beforeAfterContainer, m_counter.identifier(), true)->addRenderer(const_cast<RenderCounter&>(*this));
ASSERT(m_counterNode);
}
CounterNode* child = m_counterNode;
int value = child->actsAsReset() ? child->value() : child->countInParent();
String text = listMarkerText(m_counter.listStyle(), value);
if (!m_counter.separator().isNull()) {
if (!child->actsAsReset())
child = child->parent();
while (CounterNode* parent = child->parent()) {
text = listMarkerText(m_counter.listStyle(), child->countInParent())
+ m_counter.separator() + text;
child = parent;
}
}
return text;
}
void RenderCounter::updateCounter()
{
computePreferredLogicalWidths(0);
}
void RenderCounter::computePreferredLogicalWidths(float lead)
{
#ifndef NDEBUG
SetLayoutNeededForbiddenScope layoutForbiddenScope(this, false);
#endif
setRenderedText(originalText());
RenderText::computePreferredLogicalWidths(lead);
}
static void destroyCounterNodeWithoutMapRemoval(const AtomicString& identifier, CounterNode& node)
{
RefPtr<CounterNode> previous;
for (RefPtr<CounterNode> child = node.lastDescendant(); child && child != &node; child = WTFMove(previous)) {
previous = child->previousInPreOrder();
child->parent()->removeChild(*child);
ASSERT(counterMaps().find(&child->owner())->value->get(identifier) == child);
counterMaps().find(&child->owner())->value->remove(identifier);
}
if (auto* parent = node.parent())
parent->removeChild(node);
}
void RenderCounter::destroyCounterNodes(RenderElement& owner)
{
ASSERT(owner.hasCounterNodeMap());
auto& maps = counterMaps();
ASSERT(maps.contains(&owner));
auto counterMap = maps.take(&owner);
for (auto& counterMapEntry : *counterMap)
destroyCounterNodeWithoutMapRemoval(counterMapEntry.key, counterMapEntry.value);
owner.setHasCounterNodeMap(false);
}
void RenderCounter::destroyCounterNode(RenderElement& owner, const AtomicString& identifier)
{
auto map = counterMaps().find(&owner);
if (map == counterMaps().end())
return;
auto node = map->value->take(identifier);
if (!node)
return;
destroyCounterNodeWithoutMapRemoval(identifier, *node);
}
void RenderCounter::rendererRemovedFromTree(RenderElement& renderer)
{
if (!renderer.view().hasRenderCounters())
return;
RenderObject* currentRenderer = renderer.lastLeafChild();
if (!currentRenderer)
currentRenderer = &renderer;
while (true) {
if (is<RenderElement>(*currentRenderer)) {
auto& counterNodeRenderer = downcast<RenderElement>(*currentRenderer);
if (counterNodeRenderer.hasCounterNodeMap())
destroyCounterNodes(counterNodeRenderer);
}
if (currentRenderer == &renderer)
break;
currentRenderer = currentRenderer->previousInPreOrder();
}
}
static void updateCounters(RenderElement& renderer)
{
auto* directiveMap = renderer.style().counterDirectives();
if (!directiveMap)
return;
if (!renderer.hasCounterNodeMap()) {
for (auto& key : directiveMap->keys())
makeCounterNode(renderer, key, false);
return;
}
ASSERT(counterMaps().contains(&renderer));
auto* counterMap = counterMaps().find(&renderer)->value.get();
for (auto& key : directiveMap->keys()) {
RefPtr<CounterNode> node = counterMap->get(key);
if (!node) {
makeCounterNode(renderer, key, false);
continue;
}
auto place = findPlaceForCounter(renderer, key, node->hasResetType());
if (node != counterMap->get(key))
continue;
CounterNode* parent = node->parent();
if (place.parent == parent && place.previousSibling == node->previousSibling())
continue;
if (parent)
parent->removeChild(*node);
if (place.parent)
place.parent->insertAfter(*node, place.previousSibling.get(), key);
}
}
void RenderCounter::rendererSubtreeAttached(RenderElement& renderer)
{
if (!renderer.view().hasRenderCounters())
return;
Element* element = renderer.element();
if (element && !element->isPseudoElement())
element = element->parentElement();
else
element = renderer.generatingElement();
if (element && !element->renderer())
return; for (RenderObject* descendant = &renderer; descendant; descendant = descendant->nextInPreOrder(&renderer)) {
if (is<RenderElement>(*descendant))
updateCounters(downcast<RenderElement>(*descendant));
}
}
void RenderCounter::rendererStyleChanged(RenderElement& renderer, const RenderStyle* oldStyle, const RenderStyle* newStyle)
{
Element* element = renderer.generatingElement();
if (!element || !element->renderer())
return;
const CounterDirectiveMap* newCounterDirectives;
const CounterDirectiveMap* oldCounterDirectives;
if (oldStyle && (oldCounterDirectives = oldStyle->counterDirectives())) {
if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
for (auto& keyValue : *newCounterDirectives) {
auto existingEntry = oldCounterDirectives->find(keyValue.key);
if (existingEntry != oldCounterDirectives->end()) {
if (existingEntry->value == keyValue.value)
continue;
RenderCounter::destroyCounterNode(renderer, keyValue.key);
}
makeCounterNode(renderer, keyValue.key, false);
}
for (auto& key : oldCounterDirectives->keys()) {
if (!newCounterDirectives->contains(key))
RenderCounter::destroyCounterNode(renderer, key);
}
} else {
if (renderer.hasCounterNodeMap())
RenderCounter::destroyCounterNodes(renderer);
}
} else {
if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
for (auto& key : newCounterDirectives->keys()) {
makeCounterNode(renderer, key, false);
}
}
}
}
}
#if ENABLE(TREE_DEBUGGING)
void showCounterRendererTree(const WebCore::RenderObject* renderer, const char* counterName)
{
if (!renderer)
return;
auto* root = renderer;
while (root->parent())
root = root->parent();
AtomicString identifier(counterName);
for (auto* current = root; current; current = current->nextInPreOrder()) {
if (!is<WebCore::RenderElement>(*current))
continue;
fprintf(stderr, "%c", (current == renderer) ? '*' : ' ');
for (auto* ancestor = current; ancestor && ancestor != root; ancestor = ancestor->parent())
fprintf(stderr, " ");
fprintf(stderr, "%p N:%p P:%p PS:%p NS:%p C:%p\n",
current, current->node(), current->parent(), current->previousSibling(),
current->nextSibling(), downcast<WebCore::RenderElement>(*current).hasCounterNodeMap() ?
counterName ? WebCore::counterMaps().find(downcast<WebCore::RenderElement>(current))->value->get(identifier) : (WebCore::CounterNode*)1 : (WebCore::CounterNode*)0);
}
fflush(stderr);
}
#endif // NDEBUG