2 * Copyright (C) 2004 Allan Sandfeld Jensen (kde@carewolf.com)
3 * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public License
16 * along with this library; see the file COPYING.LIB. If not, write to
17 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
23 #include "RenderCounter.h"
25 #include "CounterNode.h"
28 #include "HTMLNames.h"
29 #include "HTMLOListElement.h"
30 #include "RenderListItem.h"
31 #include "RenderListMarker.h"
32 #include "RenderStyle.h"
33 #include <wtf/StdLibExtras.h>
41 using namespace HTMLNames;
43 typedef HashMap<RefPtr<AtomicStringImpl>, RefPtr<CounterNode> > CounterMap;
44 typedef HashMap<const RenderObject*, CounterMap*> CounterMaps;
46 static CounterNode* makeCounterNode(RenderObject*, const AtomicString& identifier, bool alwaysCreateCounter);
48 static CounterMaps& counterMaps()
50 DEFINE_STATIC_LOCAL(CounterMaps, staticCounterMaps, ());
51 return staticCounterMaps;
54 // This function processes the renderer tree in the order of the DOM tree
55 // including pseudo elements as defined in CSS 2.1.
56 // Anonymous renderers are skipped except for those representing pseudo elements.
57 static RenderObject* previousInPreOrder(const RenderObject* object)
61 switch (object->style()->styleType()) {
63 ASSERT(!object->isAnonymous());
64 parent = toElement(object->node());
65 sibling = parent->previousElementSibling();
66 parent = parent->parentElement();
69 return object->generatingNode()->renderer(); // It is always the generating node's renderer
71 parent = toElement(object->generatingNode());
72 sibling = parent->lastElementChild();
79 if (RenderObject* renderer = sibling->renderer()) {
80 if (RenderObject* after = renderer->afterPseudoElementRenderer())
83 sibling = sibling->lastElementChild();
85 if (RenderObject* before = renderer->beforePseudoElementRenderer())
90 sibling = sibling->previousElementSibling();
94 RenderObject* renderer = parent->renderer(); // Should never be null
95 if (RenderObject* before = renderer->beforePseudoElementRenderer())
100 // This function processes the renderer tree in the order of the DOM tree
101 // including pseudo elements as defined in CSS 2.1.
102 // Anonymous renderers are skipped except for those representing pseudo elements.
103 static RenderObject* previousSiblingOrParent(const RenderObject* object)
107 switch (object->style()->styleType()) {
109 ASSERT(!object->isAnonymous());
110 parent = toElement(object->node());
111 sibling = parent->previousElementSibling();
112 parent = parent->parentElement();
115 return object->generatingNode()->renderer(); // It is always the generating node's renderer
117 parent = toElement(object->generatingNode());
118 sibling = parent->lastElementChild();
121 ASSERT_NOT_REACHED();
125 if (RenderObject* renderer = sibling->renderer()) // This skips invisible nodes
127 sibling = sibling->previousElementSibling();
130 RenderObject* renderer = parent->renderer();
131 if (RenderObject* before = renderer->virtualChildren()->beforePseudoElementRenderer(renderer))
138 static Element* parentElement(RenderObject* object)
140 switch (object->style()->styleType()) {
142 ASSERT(!object->isAnonymous());
143 return toElement(object->node())->parentElement();
146 return toElement(object->generatingNode());
148 ASSERT_NOT_REACHED();
153 static inline bool areRenderersElementsSiblings(RenderObject* first, RenderObject* second)
155 return parentElement(first) == parentElement(second);
158 // This function processes the renderer tree in the order of the DOM tree
159 // including pseudo elements as defined in CSS 2.1.
160 // Anonymous renderers are skipped except for those representing pseudo elements.
161 static RenderObject* nextInPreOrder(const RenderObject* object, const Element* stayWithin, bool skipDescendants = false)
165 RenderObject* result;
166 self = toElement(object->generatingNode());
169 switch (object->style()->styleType()) {
171 ASSERT(!object->isAnonymous());
172 result = object->beforePseudoElementRenderer();
181 ASSERT_NOT_REACHED();
184 child = self->firstElementChild();
187 result = child->renderer();
190 child = child->nextElementSibling();
192 result = self->renderer()->afterPseudoElementRenderer();
196 if (self == stayWithin)
198 child = self->nextElementSibling();
199 self = self->parentElement();
201 ASSERT(!child); // We can only reach this if we are searching beyond the root element
202 return 0; // which cannot have siblings
207 static bool planCounter(RenderObject* object, const AtomicString& identifier, bool& isReset, int& value)
211 // Real text nodes don't have their own style so they can't have counters.
212 // We can't even look at their styles or we'll see extra resets and increments!
213 if (object->isText() && !object->isBR())
215 Node* generatingNode = object->generatingNode();
216 // We must have a generating node or else we cannot have a counter.
219 RenderStyle* style = object->style();
222 switch (style->styleType()) {
224 // Sometimes nodes have more then one renderer. Only the first one gets the counter
225 // LayoutTests/http/tests/css/counter-crash.html
226 if (generatingNode->renderer() != object)
233 return false; // Counters are forbidden from all other pseudo elements.
236 if (const CounterDirectiveMap* directivesMap = style->counterDirectives()) {
237 CounterDirectives directives = directivesMap->get(identifier.impl());
238 if (directives.m_reset) {
239 value = directives.m_resetValue;
240 if (directives.m_increment)
241 value += directives.m_incrementValue;
245 if (directives.m_increment) {
246 value = directives.m_incrementValue;
252 if (identifier == "list-item") {
253 if (object->isListItem()) {
254 if (toRenderListItem(object)->hasExplicitValue()) {
255 value = toRenderListItem(object)->explicitValue();
263 if (Node* e = object->node()) {
264 if (e->hasTagName(olTag)) {
265 value = static_cast<HTMLOListElement*>(e)->start();
269 if (e->hasTagName(ulTag) || e->hasTagName(menuTag) || e->hasTagName(dirTag)) {
280 // - Finds the insertion point for the counter described by counterOwner, isReset and
281 // identifier in the CounterNode tree for identifier and sets parent and
282 // previousSibling accordingly.
283 // - The function returns true if the counter whose insertion point is searched is NOT
284 // the root of the tree.
285 // - The root of the tree is a counter reference that is not in the scope of any other
286 // counter with the same identifier.
287 // - All the counter references with the same identifier as this one that are in
288 // children or subsequent siblings of the renderer that owns the root of the tree
289 // form the rest of of the nodes of the tree.
290 // - The root of the tree is always a reset type reference.
291 // - A subtree rooted at any reset node in the tree is equivalent to all counter
292 // references that are in the scope of the counter or nested counter defined by that
294 // - Non-reset CounterNodes cannot have descendants.
296 static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString& identifier, bool isReset, CounterNode*& parent, CounterNode*& previousSibling)
298 // We cannot stop searching for counters with the same identifier before we also
299 // check this renderer, because it may affect the positioning in the tree of our counter.
300 RenderObject* searchEndRenderer = previousSiblingOrParent(counterOwner);
301 // We check renderers in preOrder from the renderer that our counter is attached to
302 // towards the begining of the document for counters with the same identifier as the one
303 // we are trying to find a place for. This is the next renderer to be checked.
304 RenderObject* currentRenderer = previousInPreOrder(counterOwner);
306 while (currentRenderer) {
307 CounterNode* currentCounter = makeCounterNode(currentRenderer, identifier, false);
308 if (searchEndRenderer == currentRenderer) {
309 // We may be at the end of our search.
310 if (currentCounter) {
311 // We have a suitable counter on the EndSearchRenderer.
312 if (previousSibling) { // But we already found another counter that we come after.
313 if (currentCounter->actsAsReset()) {
314 // We found a reset counter that is on a renderer that is a sibling of ours or a parent.
315 if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
316 // We are also a reset counter and the previous reset was on a sibling renderer
317 // hence we are the next sibling of that counter if that reset is not a root or
318 // we are a root node if that reset is a root.
319 parent = currentCounter->parent();
320 previousSibling = parent ? currentCounter : 0;
323 // We are not a reset node or the previous reset must be on an ancestor of our owner renderer
324 // hence we must be a child of that reset counter.
325 parent = currentCounter;
326 // In some cases renders can be reparented (ex. nodes inside a table but not in a column or row).
327 // In these cases the identified previousSibling will be invalid as its parent is different from
328 // our identified parent.
329 if (previousSibling->parent() != currentCounter)
333 // CurrentCounter, the counter at the EndSearchRenderer, is not reset.
334 if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
335 // If the node we are placing is not reset or we have found a counter that is attached
336 // to an ancestor of the placed counter's owner renderer we know we are a sibling of that node.
337 ASSERT(currentCounter->parent() == previousSibling->parent());
338 parent = currentCounter->parent();
342 // We are at the potential end of the search, but we had no previous sibling candidate
343 // In this case we follow pretty much the same logic as above but no ASSERTs about
344 // previousSibling, and when we are a sibling of the end counter we must set previousSibling
345 // to currentCounter.
346 if (currentCounter->actsAsReset()) {
347 if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
348 parent = currentCounter->parent();
349 previousSibling = currentCounter;
352 parent = currentCounter;
355 if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
356 parent = currentCounter->parent();
357 previousSibling = currentCounter;
360 previousSibling = currentCounter;
363 // We come here if the previous sibling or parent of our owner renderer had no
364 // good counter, or we are a reset node and the counter on the previous sibling
365 // of our owner renderer was not a reset counter.
366 // Set a new goal for the end of the search.
367 searchEndRenderer = previousSiblingOrParent(currentRenderer);
369 // We are searching descendants of a previous sibling of the renderer that the
370 // counter being placed is attached to.
371 if (currentCounter) {
372 // We found a suitable counter.
373 if (previousSibling) {
374 // Since we had a suitable previous counter before, we should only consider this one as our
375 // previousSibling if it is a reset counter and hence the current previousSibling is its child.
376 if (currentCounter->actsAsReset()) {
377 previousSibling = currentCounter;
378 // We are no longer interested in previous siblings of the currentRenderer or their children
379 // as counters they may have attached cannot be the previous sibling of the counter we are placing.
380 currentRenderer = parentElement(currentRenderer)->renderer();
384 previousSibling = currentCounter;
385 currentRenderer = previousSiblingOrParent(currentRenderer);
389 // This function is designed so that the same test is not done twice in an iteration, except for this one
390 // which may be done twice in some cases. Rearranging the decision points though, to accommodate this
391 // performance improvement would create more code duplication than is worthwhile in my oppinion and may further
392 // impede the readability of this already complex algorithm.
394 currentRenderer = previousSiblingOrParent(currentRenderer);
396 currentRenderer = previousInPreOrder(currentRenderer);
401 static CounterNode* makeCounterNode(RenderObject* object, const AtomicString& identifier, bool alwaysCreateCounter)
405 if (object->m_hasCounterNodeMap) {
406 if (CounterMap* nodeMap = counterMaps().get(object)) {
407 if (CounterNode* node = nodeMap->get(identifier.impl()).get())
412 bool isReset = false;
414 if (!planCounter(object, identifier, isReset, value) && !alwaysCreateCounter)
417 CounterNode* newParent = 0;
418 CounterNode* newPreviousSibling = 0;
419 RefPtr<CounterNode> newNode = CounterNode::create(object, isReset, value);
420 if (findPlaceForCounter(object, identifier, isReset, newParent, newPreviousSibling))
421 newParent->insertAfter(newNode.get(), newPreviousSibling, identifier);
423 if (object->m_hasCounterNodeMap)
424 nodeMap = counterMaps().get(object);
426 nodeMap = new CounterMap;
427 counterMaps().set(object, nodeMap);
428 object->m_hasCounterNodeMap = true;
430 nodeMap->set(identifier.impl(), newNode);
431 if (newNode->parent())
432 return newNode.get();
433 // Checking if some nodes that were previously counter tree root nodes
434 // should become children of this node now.
435 CounterMaps& maps = counterMaps();
436 Element* stayWithin = parentElement(object);
437 bool skipDescendants;
438 for (RenderObject* currentRenderer = nextInPreOrder(object, stayWithin); currentRenderer; currentRenderer = nextInPreOrder(currentRenderer, stayWithin, skipDescendants)) {
439 skipDescendants = false;
440 if (!currentRenderer->m_hasCounterNodeMap)
442 CounterNode* currentCounter = maps.get(currentRenderer)->get(identifier.impl()).get();
445 skipDescendants = true;
446 if (currentCounter->parent())
448 if (stayWithin == parentElement(currentRenderer) && currentCounter->hasResetType())
450 newNode->insertAfter(currentCounter, newNode->lastChild(), identifier);
452 return newNode.get();
455 RenderCounter::RenderCounter(Document* node, const CounterContent& counter)
456 : RenderText(node, StringImpl::empty())
459 , m_nextForSameCounter(0)
463 RenderCounter::~RenderCounter()
466 m_counterNode->removeRenderer(this);
467 ASSERT(!m_counterNode);
471 const char* RenderCounter::renderName() const
473 return "RenderCounter";
476 bool RenderCounter::isCounter() const
481 PassRefPtr<StringImpl> RenderCounter::originalText() const
483 if (!m_counterNode) {
484 RenderObject* beforeAfterContainer = parent();
486 if (!beforeAfterContainer)
488 if (!beforeAfterContainer->isAnonymous())
489 return 0; // RenderCounters are restricted to before and after pseudo elements
490 PseudoId containerStyle = beforeAfterContainer->style()->styleType();
491 if ((containerStyle == BEFORE) || (containerStyle == AFTER))
493 beforeAfterContainer = beforeAfterContainer->parent();
495 makeCounterNode(beforeAfterContainer, m_counter.identifier(), true)->addRenderer(const_cast<RenderCounter*>(this));
496 ASSERT(m_counterNode);
498 CounterNode* child = m_counterNode;
499 int value = child->actsAsReset() ? child->value() : child->countInParent();
501 String text = listMarkerText(m_counter.listStyle(), value);
503 if (!m_counter.separator().isNull()) {
504 if (!child->actsAsReset())
505 child = child->parent();
506 while (CounterNode* parent = child->parent()) {
507 text = listMarkerText(m_counter.listStyle(), child->countInParent())
508 + m_counter.separator() + text;
516 void RenderCounter::computePreferredLogicalWidths(float lead)
518 setTextInternal(originalText());
519 RenderText::computePreferredLogicalWidths(lead);
522 void RenderCounter::invalidate()
524 m_counterNode->removeRenderer(this);
525 ASSERT(!m_counterNode);
526 if (documentBeingDestroyed())
528 setNeedsLayoutAndPrefWidthsRecalc();
531 static void destroyCounterNodeWithoutMapRemoval(const AtomicString& identifier, CounterNode* node)
533 CounterNode* previous;
534 for (RefPtr<CounterNode> child = node->lastDescendant(); child && child != node; child = previous) {
535 previous = child->previousInPreOrder();
536 child->parent()->removeChild(child.get());
537 ASSERT(counterMaps().get(child->owner())->get(identifier.impl()) == child);
538 counterMaps().get(child->owner())->remove(identifier.impl());
540 if (CounterNode* parent = node->parent())
541 parent->removeChild(node);
544 void RenderCounter::destroyCounterNodes(RenderObject* owner)
546 CounterMaps& maps = counterMaps();
547 CounterMaps::iterator mapsIterator = maps.find(owner);
548 if (mapsIterator == maps.end())
550 CounterMap* map = mapsIterator->second;
551 CounterMap::const_iterator end = map->end();
552 for (CounterMap::const_iterator it = map->begin(); it != end; ++it) {
553 AtomicString identifier(it->first.get());
554 destroyCounterNodeWithoutMapRemoval(identifier, it->second.get());
556 maps.remove(mapsIterator);
558 owner->m_hasCounterNodeMap = false;
561 void RenderCounter::destroyCounterNode(RenderObject* owner, const AtomicString& identifier)
563 CounterMap* map = counterMaps().get(owner);
566 CounterMap::iterator mapIterator = map->find(identifier.impl());
567 if (mapIterator == map->end())
569 destroyCounterNodeWithoutMapRemoval(identifier, mapIterator->second.get());
570 map->remove(mapIterator);
571 // We do not delete "map" here even if empty because we expect to reuse
572 // it soon. In order for a renderer to lose all its counters permanently,
573 // a style change for the renderer involving removal of all counter
574 // directives must occur, in which case, RenderCounter::destroyCounterNodes()
576 // The destruction of the Renderer (possibly caused by the removal of its
577 // associated DOM node) is the other case that leads to the permanent
578 // destruction of all counters attached to a Renderer. In this case
579 // RenderCounter::destroyCounterNodes() must be and is now called, too.
580 // RenderCounter::destroyCounterNodes() handles destruction of the counter
581 // map associated with a renderer, so there is no risk in leaking the map.
584 void RenderCounter::rendererRemovedFromTree(RenderObject* removedRenderer)
586 RenderObject* currentRenderer = removedRenderer->lastLeafChild();
587 if (!currentRenderer)
588 currentRenderer = removedRenderer;
590 destroyCounterNodes(currentRenderer);
591 if (currentRenderer == removedRenderer)
593 currentRenderer = currentRenderer->previousInPreOrder();
597 static void updateCounters(RenderObject* renderer)
599 ASSERT(renderer->style());
600 const CounterDirectiveMap* directiveMap = renderer->style()->counterDirectives();
603 CounterDirectiveMap::const_iterator end = directiveMap->end();
604 if (!renderer->m_hasCounterNodeMap) {
605 for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it)
606 makeCounterNode(renderer, AtomicString(it->first.get()), false);
609 CounterMap* counterMap = counterMaps().get(renderer);
611 for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it) {
612 RefPtr<CounterNode> node = counterMap->get(it->first.get());
614 makeCounterNode(renderer, AtomicString(it->first.get()), false);
617 CounterNode* newParent = 0;
618 CounterNode* newPreviousSibling;
620 findPlaceForCounter(renderer, AtomicString(it->first.get()), node->hasResetType(), newParent, newPreviousSibling);
621 if (node != counterMap->get(it->first.get()))
623 CounterNode* parent = node->parent();
624 if (newParent == parent && newPreviousSibling == node->previousSibling())
627 parent->removeChild(node.get());
629 newParent->insertAfter(node.get(), newPreviousSibling, it->first.get());
633 void RenderCounter::rendererSubtreeAttached(RenderObject* renderer)
635 Node* node = renderer->node();
637 node = node->parentNode();
639 node = renderer->generatingNode();
640 if (node && !node->attached())
641 return; // No need to update if the parent is not attached yet
642 for (RenderObject* descendant = renderer; descendant; descendant = descendant->nextInPreOrder(renderer))
643 updateCounters(descendant);
646 void RenderCounter::rendererStyleChanged(RenderObject* renderer, const RenderStyle* oldStyle, const RenderStyle* newStyle)
648 Node* node = renderer->generatingNode();
649 if (!node || !node->attached())
650 return; // cannot have generated content or if it can have, it will be handled during attaching
651 const CounterDirectiveMap* newCounterDirectives;
652 const CounterDirectiveMap* oldCounterDirectives;
653 if (oldStyle && (oldCounterDirectives = oldStyle->counterDirectives())) {
654 if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
655 CounterDirectiveMap::const_iterator newMapEnd = newCounterDirectives->end();
656 CounterDirectiveMap::const_iterator oldMapEnd = oldCounterDirectives->end();
657 for (CounterDirectiveMap::const_iterator it = newCounterDirectives->begin(); it != newMapEnd; ++it) {
658 CounterDirectiveMap::const_iterator oldMapIt = oldCounterDirectives->find(it->first);
659 if (oldMapIt != oldMapEnd) {
660 if (oldMapIt->second == it->second)
662 RenderCounter::destroyCounterNode(renderer, it->first.get());
664 // We must create this node here, because the changed node may be a node with no display such as
665 // as those created by the increment or reset directives and the re-layout that will happen will
666 // not catch the change if the node had no children.
667 makeCounterNode(renderer, it->first.get(), false);
669 // Destroying old counters that do not exist in the new counterDirective map.
670 for (CounterDirectiveMap::const_iterator it = oldCounterDirectives->begin(); it !=oldMapEnd; ++it) {
671 if (!newCounterDirectives->contains(it->first))
672 RenderCounter::destroyCounterNode(renderer, it->first.get());
675 if (renderer->m_hasCounterNodeMap)
676 RenderCounter::destroyCounterNodes(renderer);
678 } else if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
679 CounterDirectiveMap::const_iterator newMapEnd = newCounterDirectives->end();
680 for (CounterDirectiveMap::const_iterator it = newCounterDirectives->begin(); it != newMapEnd; ++it) {
681 // We must create this node here, because the added node may be a node with no display such as
682 // as those created by the increment or reset directives and the re-layout that will happen will
683 // not catch the change if the node had no children.
684 makeCounterNode(renderer, it->first.get(), false);
689 } // namespace WebCore
693 void showCounterRendererTree(const WebCore::RenderObject* renderer, const char* counterName)
697 const WebCore::RenderObject* root = renderer;
698 while (root->parent())
699 root = root->parent();
701 AtomicString identifier(counterName);
702 for (const WebCore::RenderObject* current = root; current; current = current->nextInPreOrder()) {
703 fprintf(stderr, "%c", (current == renderer) ? '*' : ' ');
704 for (const WebCore::RenderObject* parent = current; parent && parent != root; parent = parent->parent())
705 fprintf(stderr, " ");
706 fprintf(stderr, "%p N:%p P:%p PS:%p NS:%p C:%p\n",
707 current, current->node(), current->parent(), current->previousSibling(),
708 current->nextSibling(), current->m_hasCounterNodeMap?
709 counterName ? WebCore::counterMaps().get(current)->get(identifier.impl()).get() : (WebCore::CounterNode*)1 : (WebCore::CounterNode*)0);