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>
37 using namespace HTMLNames;
39 typedef HashMap<RefPtr<AtomicStringImpl>, RefPtr<CounterNode> > CounterMap;
40 typedef HashMap<const RenderObject*, CounterMap*> CounterMaps;
42 static CounterNode* makeCounterNode(RenderObject*, const AtomicString& identifier, bool alwaysCreateCounter);
44 static CounterMaps& counterMaps()
46 DEFINE_STATIC_LOCAL(CounterMaps, staticCounterMaps, ());
47 return staticCounterMaps;
50 // This function processes the renderer tree in the order of the DOM tree
51 // including pseudo elements as defined in CSS 2.1.
52 // Anonymous renderers are skipped except for those representing pseudo elements.
53 static RenderObject* previousInPreOrder(const RenderObject* object)
57 switch (object->style()->styleType()) {
59 ASSERT(!object->isAnonymous());
60 parent = toElement(object->node());
61 sibling = parent->previousElementSibling();
62 parent = parent->parentElement();
65 return object->generatingNode()->renderer(); // It is always the generating node's renderer
67 parent = toElement(object->generatingNode());
68 sibling = parent->lastElementChild();
75 if (RenderObject* renderer = sibling->renderer()) {
76 if (RenderObject* after = renderer->afterPseudoElementRenderer())
79 sibling = sibling->lastElementChild();
81 if (RenderObject* before = renderer->beforePseudoElementRenderer())
86 sibling = sibling->previousElementSibling();
90 RenderObject* renderer = parent->renderer(); // Should never be null
91 if (RenderObject* before = renderer->beforePseudoElementRenderer())
96 // This function processes the renderer tree in the order of the DOM tree
97 // including pseudo elements as defined in CSS 2.1.
98 // Anonymous renderers are skipped except for those representing pseudo elements.
99 static RenderObject* previousSiblingOrParent(const RenderObject* object)
103 switch (object->style()->styleType()) {
105 ASSERT(!object->isAnonymous());
106 parent = toElement(object->node());
107 sibling = parent->previousElementSibling();
108 parent = parent->parentElement();
111 return object->generatingNode()->renderer(); // It is always the generating node's renderer
113 parent = toElement(object->generatingNode());
114 sibling = parent->lastElementChild();
117 ASSERT_NOT_REACHED();
121 if (RenderObject* renderer = sibling->renderer()) // This skips invisible nodes
123 sibling = sibling->previousElementSibling();
126 RenderObject* renderer = parent->renderer();
127 if (RenderObject* before = renderer->virtualChildren()->beforePseudoElementRenderer(renderer))
134 static Element* parentElement(RenderObject* object)
136 switch (object->style()->styleType()) {
138 ASSERT(!object->isAnonymous());
139 return toElement(object->node())->parentElement();
142 return toElement(object->generatingNode());
144 ASSERT_NOT_REACHED();
149 static inline bool areRenderersElementsSiblings(RenderObject* first, RenderObject* second)
151 return parentElement(first) == parentElement(second);
154 // This function processes the renderer tree in the order of the DOM tree
155 // including pseudo elements as defined in CSS 2.1.
156 // Anonymous renderers are skipped except for those representing pseudo elements.
157 static RenderObject* nextInPreOrder(const RenderObject* object, const Element* stayWithin, bool skipDescendants = false)
161 RenderObject* result;
162 self = toElement(object->generatingNode());
165 switch (object->style()->styleType()) {
167 ASSERT(!object->isAnonymous());
168 result = object->beforePseudoElementRenderer();
177 ASSERT_NOT_REACHED();
180 child = self->firstElementChild();
183 result = child->renderer();
186 child = child->nextElementSibling();
188 result = self->renderer()->afterPseudoElementRenderer();
192 if (self == stayWithin)
194 child = self->nextElementSibling();
195 self = self->parentElement();
197 ASSERT(!child); // We can only reach this if we are searching beyond the root element
198 return 0; // which cannot have siblings
203 static bool planCounter(RenderObject* object, const AtomicString& identifier, bool& isReset, int& value)
207 // Real text nodes don't have their own style so they can't have counters.
208 // We can't even look at their styles or we'll see extra resets and increments!
209 if (object->isText() && !object->isBR())
211 Node* generatingNode = object->generatingNode();
212 // We must have a generating node or else we cannot have a counter.
215 RenderStyle* style = object->style();
218 switch (style->styleType()) {
220 // Sometimes nodes have more then one renderer. Only the first one gets the counter
221 // LayoutTests/http/tests/css/counter-crash.html
222 if (generatingNode->renderer() != object)
229 return false; // Counters are forbidden from all other pseudo elements.
232 if (const CounterDirectiveMap* directivesMap = style->counterDirectives()) {
233 CounterDirectives directives = directivesMap->get(identifier.impl());
234 if (directives.m_reset) {
235 value = directives.m_resetValue;
236 if (directives.m_increment)
237 value += directives.m_incrementValue;
241 if (directives.m_increment) {
242 value = directives.m_incrementValue;
248 if (identifier == "list-item") {
249 if (object->isListItem()) {
250 if (toRenderListItem(object)->hasExplicitValue()) {
251 value = toRenderListItem(object)->explicitValue();
259 if (Node* e = object->node()) {
260 if (e->hasTagName(olTag)) {
261 value = static_cast<HTMLOListElement*>(e)->start();
265 if (e->hasTagName(ulTag) || e->hasTagName(menuTag) || e->hasTagName(dirTag)) {
276 // - Finds the insertion point for the counter described by counterOwner, isReset and
277 // identifier in the CounterNode tree for identifier and sets parent and
278 // previousSibling accordingly.
279 // - The function returns true if the counter whose insertion point is searched is NOT
280 // the root of the tree.
281 // - The root of the tree is a counter reference that is not in the scope of any other
282 // counter with the same identifier.
283 // - All the counter references with the same identifier as this one that are in
284 // children or subsequent siblings of the renderer that owns the root of the tree
285 // form the rest of of the nodes of the tree.
286 // - The root of the tree is always a reset type reference.
287 // - A subtree rooted at any reset node in the tree is equivalent to all counter
288 // references that are in the scope of the counter or nested counter defined by that
290 // - Non-reset CounterNodes cannot have descendants.
292 static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString& identifier, bool isReset, CounterNode*& parent, CounterNode*& previousSibling)
294 // We cannot stop searching for counters with the same identifier before we also
295 // check this renderer, because it may affect the positioning in the tree of our counter.
296 RenderObject* searchEndRenderer = previousSiblingOrParent(counterOwner);
297 // We check renderers in preOrder from the renderer that our counter is attached to
298 // towards the begining of the document for counters with the same identifier as the one
299 // we are trying to find a place for. This is the next renderer to be checked.
300 RenderObject* currentRenderer = previousInPreOrder(counterOwner);
302 while (currentRenderer) {
303 CounterNode* currentCounter = makeCounterNode(currentRenderer, identifier, false);
304 if (searchEndRenderer == currentRenderer) {
305 // We may be at the end of our search.
306 if (currentCounter) {
307 // We have a suitable counter on the EndSearchRenderer.
308 if (previousSibling) { // But we already found another counter that we come after.
309 if (currentCounter->actsAsReset()) {
310 // We found a reset counter that is on a renderer that is a sibling of ours or a parent.
311 if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
312 // We are also a reset counter and the previous reset was on a sibling renderer
313 // hence we are the next sibling of that counter if that reset is not a root or
314 // we are a root node if that reset is a root.
315 parent = currentCounter->parent();
316 previousSibling = parent ? currentCounter : 0;
319 // We are not a reset node or the previous reset must be on an ancestor of our renderer
320 // hence we must be a child of that reset counter.
321 parent = currentCounter;
322 ASSERT(previousSibling->parent() == currentCounter);
325 // CurrentCounter, the counter at the EndSearchRenderer, is not reset.
326 if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
327 // If the node we are placing is not reset or we have found a counter that is attached
328 // to an ancestor of the placed counter's renderer we know we are a sibling of that node.
329 ASSERT(currentCounter->parent() == previousSibling->parent());
330 parent = currentCounter->parent();
334 // We are at the potential end of the search, but we had no previous sibling candidate
335 // In this case we follow pretty much the same logic as above but no ASSERTs about
336 // previousSibling, and when we are a sibling of the end counter we must set previousSibling
337 // to currentCounter.
338 if (currentCounter->actsAsReset()) {
339 if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
340 parent = currentCounter->parent();
341 previousSibling = currentCounter;
344 parent = currentCounter;
347 if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
348 parent = currentCounter->parent();
349 previousSibling = currentCounter;
352 previousSibling = currentCounter;
355 // We come here if the previous sibling or parent of our renderer had no
356 // good counter, or we are a reset node and the counter on the previous sibling
357 // of our renderer was not a reset counter.
358 // Set a new goal for the end of the search.
359 searchEndRenderer = previousSiblingOrParent(currentRenderer);
361 // We are searching descendants of a previous sibling of the renderer that the
362 // counter being placed is attached to.
363 if (currentCounter) {
364 // We found a suitable counter.
365 if (previousSibling) {
366 // Since we had a suitable previous counter before, we should only consider this one as our
367 // previousSibling if it is a reset counter and hence the current previousSibling is its child.
368 if (currentCounter->actsAsReset()) {
369 previousSibling = currentCounter;
370 // We are no longer interested in previous siblings of the currentRenderer or their children
371 // as counters they may have attached cannot be the previous sibling of the counter we are placing.
372 currentRenderer = parentElement(currentRenderer)->renderer();
376 previousSibling = currentCounter;
377 currentRenderer = previousSiblingOrParent(currentRenderer);
381 // This function is designed so that the same test is not done twice in an iteration, except for this one
382 // which may be done twice in some cases. Rearranging the decision points though, to accommodate this
383 // performance improvement would create more code duplication than is worthwhile in my oppinion and may further
384 // impede the readability of this already complex algorithm.
386 currentRenderer = previousSiblingOrParent(currentRenderer);
388 currentRenderer = currentRenderer->previousInPreOrder();
393 static CounterNode* makeCounterNode(RenderObject* object, const AtomicString& identifier, bool alwaysCreateCounter)
397 if (object->m_hasCounterNodeMap) {
398 if (CounterMap* nodeMap = counterMaps().get(object)) {
399 if (CounterNode* node = nodeMap->get(identifier.impl()).get())
404 bool isReset = false;
406 if (!planCounter(object, identifier, isReset, value) && !alwaysCreateCounter)
409 CounterNode* newParent = 0;
410 CounterNode* newPreviousSibling = 0;
411 RefPtr<CounterNode> newNode = CounterNode::create(object, isReset, value);
412 if (findPlaceForCounter(object, identifier, isReset, newParent, newPreviousSibling))
413 newParent->insertAfter(newNode.get(), newPreviousSibling, identifier);
415 if (object->m_hasCounterNodeMap)
416 nodeMap = counterMaps().get(object);
418 nodeMap = new CounterMap;
419 counterMaps().set(object, nodeMap);
420 object->m_hasCounterNodeMap = true;
422 nodeMap->set(identifier.impl(), newNode);
423 if (newNode->parent())
424 return newNode.get();
425 // Checking if some nodes that were previously counter tree root nodes
426 // should become children of this node now.
427 CounterMaps& maps = counterMaps();
428 Element* stayWithin = parentElement(object);
429 bool skipDescendants;
430 for (RenderObject* currentRenderer = nextInPreOrder(object, stayWithin); currentRenderer; currentRenderer = nextInPreOrder(currentRenderer, stayWithin, skipDescendants)) {
431 skipDescendants = false;
432 if (!currentRenderer->m_hasCounterNodeMap)
434 CounterNode* currentCounter = maps.get(currentRenderer)->get(identifier.impl()).get();
437 skipDescendants = true;
438 if (currentCounter->parent()) {
439 ASSERT(newNode->firstChild());
442 if (stayWithin == parentElement(currentRenderer) && currentCounter->hasResetType())
444 newNode->insertAfter(currentCounter, newNode->lastChild(), identifier);
446 return newNode.get();
449 RenderCounter::RenderCounter(Document* node, const CounterContent& counter)
450 : RenderText(node, StringImpl::empty())
456 RenderCounter::~RenderCounter()
460 const char* RenderCounter::renderName() const
462 return "RenderCounter";
465 bool RenderCounter::isCounter() const
470 PassRefPtr<StringImpl> RenderCounter::originalText() const
476 m_counterNode = makeCounterNode(parent(), m_counter.identifier(), true);
478 CounterNode* child = m_counterNode;
479 int value = child->actsAsReset() ? child->value() : child->countInParent();
481 String text = listMarkerText(m_counter.listStyle(), value);
483 if (!m_counter.separator().isNull()) {
484 if (!child->actsAsReset())
485 child = child->parent();
486 while (CounterNode* parent = child->parent()) {
487 text = listMarkerText(m_counter.listStyle(), child->countInParent())
488 + m_counter.separator() + text;
496 void RenderCounter::computePreferredLogicalWidths(int lead)
498 setTextInternal(originalText());
499 RenderText::computePreferredLogicalWidths(lead);
502 void RenderCounter::invalidate(const AtomicString& identifier)
504 if (m_counter.identifier() != identifier)
507 setNeedsLayoutAndPrefWidthsRecalc();
510 static void destroyCounterNodeWithoutMapRemoval(const AtomicString& identifier, CounterNode* node)
512 CounterNode* previous;
513 for (RefPtr<CounterNode> child = node->lastDescendant(); child && child != node; child = previous) {
514 previous = child->previousInPreOrder();
515 child->parent()->removeChild(child.get(), identifier);
516 ASSERT(counterMaps().get(child->renderer())->get(identifier.impl()) == child);
517 counterMaps().get(child->renderer())->remove(identifier.impl());
518 if (!child->renderer()->documentBeingDestroyed()) {
519 RenderObjectChildList* children = child->renderer()->virtualChildren();
521 children->invalidateCounters(child->renderer(), identifier);
524 RenderObject* renderer = node->renderer();
525 if (!renderer->documentBeingDestroyed()) {
526 if (RenderObjectChildList* children = renderer->virtualChildren())
527 children->invalidateCounters(renderer, identifier);
529 if (CounterNode* parent = node->parent())
530 parent->removeChild(node, identifier);
533 void RenderCounter::destroyCounterNodes(RenderObject* renderer)
535 CounterMaps& maps = counterMaps();
536 CounterMaps::iterator mapsIterator = maps.find(renderer);
537 if (mapsIterator == maps.end())
539 CounterMap* map = mapsIterator->second;
540 CounterMap::const_iterator end = map->end();
541 for (CounterMap::const_iterator it = map->begin(); it != end; ++it) {
542 AtomicString identifier(it->first.get());
543 destroyCounterNodeWithoutMapRemoval(identifier, it->second.get());
545 maps.remove(mapsIterator);
547 renderer->m_hasCounterNodeMap = false;
550 void RenderCounter::destroyCounterNode(RenderObject* renderer, const AtomicString& identifier)
552 CounterMap* map = counterMaps().get(renderer);
555 CounterMap::iterator mapIterator = map->find(identifier.impl());
556 if (mapIterator == map->end())
558 destroyCounterNodeWithoutMapRemoval(identifier, mapIterator->second.get());
559 map->remove(mapIterator);
560 // We do not delete "map" here even if empty because we expect to reuse
561 // it soon. In order for a renderer to lose all its counters permanently,
562 // a style change for the renderer involving removal of all counter
563 // directives must occur, in which case, RenderCounter::destroyCounterNodes()
565 // The destruction of the Renderer (possibly caused by the removal of its
566 // associated DOM node) is the other case that leads to the permanent
567 // destruction of all counters attached to a Renderer. In this case
568 // RenderCounter::destroyCounterNodes() must be and is now called, too.
569 // RenderCounter::destroyCounterNodes() handles destruction of the counter
570 // map associated with a renderer, so there is no risk in leaking the map.
573 static void updateCounters(RenderObject* renderer)
575 ASSERT(renderer->style());
576 const CounterDirectiveMap* directiveMap = renderer->style()->counterDirectives();
579 CounterDirectiveMap::const_iterator end = directiveMap->end();
580 if (!renderer->m_hasCounterNodeMap) {
581 for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it)
582 makeCounterNode(renderer, AtomicString(it->first.get()), false);
585 CounterMap* counterMap = counterMaps().get(renderer);
587 for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it) {
588 RefPtr<CounterNode> node = counterMap->get(it->first.get());
590 makeCounterNode(renderer, AtomicString(it->first.get()), false);
593 CounterNode* newParent = 0;
594 CounterNode* newPreviousSibling;
596 findPlaceForCounter(renderer, AtomicString(it->first.get()), node->hasResetType(), newParent, newPreviousSibling);
597 if (node != counterMap->get(it->first.get()))
599 CounterNode* parent = node->parent();
600 if (newParent == parent && newPreviousSibling == node->previousSibling())
603 parent->removeChild(node.get(), it->first.get());
605 newParent->insertAfter(node.get(), newPreviousSibling, it->first.get());
609 void RenderCounter::rendererSubtreeAttached(RenderObject* renderer)
611 Node* node = renderer->node();
613 node = node->parentNode();
615 node = renderer->generatingNode();
616 if (node && !node->attached())
617 return; // No need to update if the parent is not attached yet
618 for (RenderObject* descendant = renderer; descendant; descendant = descendant->nextInPreOrder(renderer))
619 updateCounters(descendant);
622 void RenderCounter::rendererStyleChanged(RenderObject* renderer, const RenderStyle* oldStyle, const RenderStyle* newStyle)
624 Node* node = renderer->generatingNode();
625 if (!node || !node->attached())
626 return; // cannot have generated content or if it can have, it will be handled during attaching
627 const CounterDirectiveMap* newCounterDirectives;
628 const CounterDirectiveMap* oldCounterDirectives;
629 if (oldStyle && (oldCounterDirectives = oldStyle->counterDirectives())) {
630 if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
631 CounterDirectiveMap::const_iterator newMapEnd = newCounterDirectives->end();
632 CounterDirectiveMap::const_iterator oldMapEnd = oldCounterDirectives->end();
633 for (CounterDirectiveMap::const_iterator it = newCounterDirectives->begin(); it != newMapEnd; ++it) {
634 CounterDirectiveMap::const_iterator oldMapIt = oldCounterDirectives->find(it->first);
635 if (oldMapIt != oldMapEnd) {
636 if (oldMapIt->second == it->second)
638 RenderCounter::destroyCounterNode(renderer, it->first.get());
640 // We must create this node here, because the changed node may be a node with no display such as
641 // as those created by the increment or reset directives and the re-layout that will happen will
642 // not catch the change if the node had no children.
643 makeCounterNode(renderer, it->first.get(), false);
645 // Destroying old counters that do not exist in the new counterDirective map.
646 for (CounterDirectiveMap::const_iterator it = oldCounterDirectives->begin(); it !=oldMapEnd; ++it) {
647 if (!newCounterDirectives->contains(it->first))
648 RenderCounter::destroyCounterNode(renderer, it->first.get());
651 if (renderer->m_hasCounterNodeMap)
652 RenderCounter::destroyCounterNodes(renderer);
654 } else if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
655 CounterDirectiveMap::const_iterator newMapEnd = newCounterDirectives->end();
656 for (CounterDirectiveMap::const_iterator it = newCounterDirectives->begin(); it != newMapEnd; ++it) {
657 // We must create this node here, because the added node may be a node with no display such as
658 // as those created by the increment or reset directives and the re-layout that will happen will
659 // not catch the change if the node had no children.
660 makeCounterNode(renderer, it->first.get(), false);
665 } // namespace WebCore
669 void showCounterRendererTree(const WebCore::RenderObject* renderer, const char* counterName)
673 const WebCore::RenderObject* root = renderer;
674 while (root->parent())
675 root = root->parent();
677 AtomicString identifier(counterName);
678 for (const WebCore::RenderObject* current = root; current; current = current->nextInPreOrder()) {
679 fprintf(stderr, "%c", (current == renderer) ? '*' : ' ');
680 for (const WebCore::RenderObject* parent = current; parent && parent != root; parent = parent->parent())
681 fprintf(stderr, " ");
682 fprintf(stderr, "%p N:%p P:%p PS:%p NS:%p C:%p\n",
683 current, current->node(), current->parent(), current->previousSibling(),
684 current->nextSibling(), current->m_hasCounterNodeMap?
685 counterName ? WebCore::counterMaps().get(current)->get(identifier.impl()).get() : (WebCore::CounterNode*)1 : (WebCore::CounterNode*)0);