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 "RenderView.h"
34
#include <wtf/StdLibExtras.h>
42
using namespace HTMLNames;
44
typedef HashMap<AtomicString, RefPtr<CounterNode> > CounterMap;
45
typedef HashMap<const RenderObject*, OwnPtr<CounterMap> > CounterMaps;
47
static CounterNode* makeCounterNode(RenderObject*, const AtomicString& identifier, bool alwaysCreateCounter);
49
static CounterMaps& counterMaps()
51
DEFINE_STATIC_LOCAL(CounterMaps, staticCounterMaps, ());
52
return staticCounterMaps;
55
static RenderObject* rendererOfAfterPseudoElement(RenderObject* renderer)
57
RenderObject* lastContinuation = renderer;
58
while (RenderObject* continuation = lastContinuation->virtualContinuation())
59
lastContinuation = continuation;
60
return lastContinuation->afterPseudoElementRenderer();
63
// This function processes the renderer tree in the order of the DOM tree
64
// including pseudo elements as defined in CSS 2.1.
65
// Anonymous renderers are skipped except for those representing pseudo elements.
66
static RenderObject* previousInPreOrder(const RenderObject* object)
70
switch (object->style()->styleType()) {
72
ASSERT(!object->isAnonymous());
73
parent = toElement(object->node());
74
sibling = parent->previousElementSibling();
75
parent = parent->parentElement();
78
return object->generatingNode()->renderer(); // It is always the generating node's renderer
80
parent = toElement(object->generatingNode());
81
sibling = parent->lastElementChild();
88
if (RenderObject* renderer = sibling->renderer()) {
89
if (RenderObject* after = rendererOfAfterPseudoElement(renderer))
92
sibling = sibling->lastElementChild();
94
if (RenderObject* before = renderer->beforePseudoElementRenderer())
99
sibling = sibling->previousElementSibling();
103
RenderObject* renderer = parent->renderer(); // Should never be null
104
if (RenderObject* before = renderer->beforePseudoElementRenderer())
109
// This function processes the renderer tree in the order of the DOM tree
110
// including pseudo elements as defined in CSS 2.1.
111
// Anonymous renderers are skipped except for those representing pseudo elements.
112
static RenderObject* previousSiblingOrParent(const RenderObject* object)
116
switch (object->style()->styleType()) {
118
ASSERT(!object->isAnonymous());
119
parent = toElement(object->node());
120
sibling = parent->previousElementSibling();
121
parent = parent->parentElement();
124
return object->generatingNode()->renderer(); // It is always the generating node's renderer
126
parent = toElement(object->generatingNode());
127
sibling = parent->lastElementChild();
130
ASSERT_NOT_REACHED();
134
if (RenderObject* renderer = sibling->renderer()) // This skips invisible nodes
136
sibling = sibling->previousElementSibling();
139
RenderObject* renderer = parent->renderer();
140
if (RenderObject* before = renderer->virtualChildren()->beforePseudoElementRenderer(renderer))
147
static Element* parentElement(RenderObject* object)
149
switch (object->style()->styleType()) {
151
ASSERT(!object->isAnonymous());
152
return toElement(object->node())->parentElement();
155
return toElement(object->generatingNode());
157
ASSERT_NOT_REACHED();
162
static inline bool areRenderersElementsSiblings(RenderObject* first, RenderObject* second)
164
return parentElement(first) == parentElement(second);
167
// This function processes the renderer tree in the order of the DOM tree
168
// including pseudo elements as defined in CSS 2.1.
169
// Anonymous renderers are skipped except for those representing pseudo elements.
170
static RenderObject* nextInPreOrder(const RenderObject* object, const Element* stayWithin, bool skipDescendants = false)
174
RenderObject* result;
175
self = toElement(object->generatingNode());
178
switch (object->style()->styleType()) {
180
ASSERT(!object->isAnonymous());
181
result = object->beforePseudoElementRenderer();
190
ASSERT_NOT_REACHED();
193
child = self->firstElementChild();
196
result = child->renderer();
199
child = child->nextElementSibling();
201
result = rendererOfAfterPseudoElement(self->renderer());
205
if (self == stayWithin)
207
child = self->nextElementSibling();
208
self = self->parentElement();
210
ASSERT(!child); // We can only reach this if we are searching beyond the root element
211
return 0; // which cannot have siblings
216
static bool planCounter(RenderObject* object, const AtomicString& identifier, bool& isReset, int& value)
220
// Real text nodes don't have their own style so they can't have counters.
221
// We can't even look at their styles or we'll see extra resets and increments!
222
if (object->isText() && !object->isBR())
224
Node* generatingNode = object->generatingNode();
225
// We must have a generating node or else we cannot have a counter.
228
RenderStyle* style = object->style();
231
switch (style->styleType()) {
233
// Sometimes nodes have more then one renderer. Only the first one gets the counter
234
// LayoutTests/http/tests/css/counter-crash.html
235
if (generatingNode->renderer() != object)
242
return false; // Counters are forbidden from all other pseudo elements.
245
const CounterDirectives directives = style->getCounterDirectives(identifier);
246
if (directives.isDefined()) {
247
value = directives.combinedValue();
248
isReset = directives.isReset();
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, RefPtr<CounterNode>& parent, RefPtr<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
RefPtr<CounterNode> previousSiblingProtector = 0;
308
while (currentRenderer) {
309
CounterNode* currentCounter = makeCounterNode(currentRenderer, identifier, false);
310
if (searchEndRenderer == currentRenderer) {
311
// We may be at the end of our search.
312
if (currentCounter) {
313
// We have a suitable counter on the EndSearchRenderer.
314
if (previousSiblingProtector) { // But we already found another counter that we come after.
315
if (currentCounter->actsAsReset()) {
316
// We found a reset counter that is on a renderer that is a sibling of ours or a parent.
317
if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
318
// We are also a reset counter and the previous reset was on a sibling renderer
319
// hence we are the next sibling of that counter if that reset is not a root or
320
// we are a root node if that reset is a root.
321
parent = currentCounter->parent();
322
previousSibling = parent ? currentCounter : 0;
325
// We are not a reset node or the previous reset must be on an ancestor of our owner renderer
326
// hence we must be a child of that reset counter.
327
parent = currentCounter;
328
// In some cases renders can be reparented (ex. nodes inside a table but not in a column or row).
329
// In these cases the identified previousSibling will be invalid as its parent is different from
330
// our identified parent.
331
if (previousSiblingProtector->parent() != currentCounter)
332
previousSiblingProtector = 0;
334
previousSibling = previousSiblingProtector.get();
337
// CurrentCounter, the counter at the EndSearchRenderer, is not reset.
338
if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
339
// If the node we are placing is not reset or we have found a counter that is attached
340
// to an ancestor of the placed counter's owner renderer we know we are a sibling of that node.
341
if (currentCounter->parent() != previousSiblingProtector->parent())
344
parent = currentCounter->parent();
345
previousSibling = previousSiblingProtector.get();
349
// We are at the potential end of the search, but we had no previous sibling candidate
350
// In this case we follow pretty much the same logic as above but no ASSERTs about
351
// previousSibling, and when we are a sibling of the end counter we must set previousSibling
352
// to currentCounter.
353
if (currentCounter->actsAsReset()) {
354
if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
355
parent = currentCounter->parent();
356
previousSibling = currentCounter;
359
parent = currentCounter;
360
previousSibling = previousSiblingProtector.get();
363
if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
364
parent = currentCounter->parent();
365
previousSibling = currentCounter;
368
previousSiblingProtector = currentCounter;
371
// We come here if the previous sibling or parent of our owner renderer had no
372
// good counter, or we are a reset node and the counter on the previous sibling
373
// of our owner renderer was not a reset counter.
374
// Set a new goal for the end of the search.
375
searchEndRenderer = previousSiblingOrParent(currentRenderer);
377
// We are searching descendants of a previous sibling of the renderer that the
378
// counter being placed is attached to.
379
if (currentCounter) {
380
// We found a suitable counter.
381
if (previousSiblingProtector) {
382
// Since we had a suitable previous counter before, we should only consider this one as our
383
// previousSibling if it is a reset counter and hence the current previousSibling is its child.
384
if (currentCounter->actsAsReset()) {
385
previousSiblingProtector = currentCounter;
386
// We are no longer interested in previous siblings of the currentRenderer or their children
387
// as counters they may have attached cannot be the previous sibling of the counter we are placing.
388
currentRenderer = parentElement(currentRenderer)->renderer();
392
previousSiblingProtector = currentCounter;
393
currentRenderer = previousSiblingOrParent(currentRenderer);
397
// This function is designed so that the same test is not done twice in an iteration, except for this one
398
// which may be done twice in some cases. Rearranging the decision points though, to accommodate this
399
// performance improvement would create more code duplication than is worthwhile in my oppinion and may further
400
// impede the readability of this already complex algorithm.
401
if (previousSiblingProtector)
402
currentRenderer = previousSiblingOrParent(currentRenderer);
404
currentRenderer = previousInPreOrder(currentRenderer);
409
static CounterNode* makeCounterNode(RenderObject* object, const AtomicString& identifier, bool alwaysCreateCounter)
413
if (object->hasCounterNodeMap()) {
414
if (CounterMap* nodeMap = counterMaps().get(object)) {
415
if (CounterNode* node = nodeMap->get(identifier).get())
420
bool isReset = false;
422
if (!planCounter(object, identifier, isReset, value) && !alwaysCreateCounter)
425
RefPtr<CounterNode> newParent = 0;
426
RefPtr<CounterNode> newPreviousSibling = 0;
427
RefPtr<CounterNode> newNode = CounterNode::create(object, isReset, value);
428
if (findPlaceForCounter(object, identifier, isReset, newParent, newPreviousSibling))
429
newParent->insertAfter(newNode.get(), newPreviousSibling.get(), identifier);
431
if (object->hasCounterNodeMap())
432
nodeMap = counterMaps().get(object);
434
nodeMap = new CounterMap;
435
counterMaps().set(object, adoptPtr(nodeMap));
436
object->setHasCounterNodeMap(true);
438
nodeMap->set(identifier, newNode);
439
if (newNode->parent())
440
return newNode.get();
441
// Checking if some nodes that were previously counter tree root nodes
442
// should become children of this node now.
443
CounterMaps& maps = counterMaps();
444
Element* stayWithin = parentElement(object);
445
bool skipDescendants;
446
for (RenderObject* currentRenderer = nextInPreOrder(object, stayWithin); currentRenderer; currentRenderer = nextInPreOrder(currentRenderer, stayWithin, skipDescendants)) {
447
skipDescendants = false;
448
if (!currentRenderer->hasCounterNodeMap())
450
CounterNode* currentCounter = maps.get(currentRenderer)->get(identifier).get();
453
skipDescendants = true;
454
if (currentCounter->parent())
456
if (stayWithin == parentElement(currentRenderer) && currentCounter->hasResetType())
458
newNode->insertAfter(currentCounter, newNode->lastChild(), identifier);
460
return newNode.get();
463
RenderCounter::RenderCounter(Document* node, const CounterContent& counter)
464
: RenderText(node, StringImpl::empty())
467
, m_nextForSameCounter(0)
469
view()->addRenderCounter();
472
RenderCounter::~RenderCounter()
475
m_counterNode->removeRenderer(this);
476
ASSERT(!m_counterNode);
480
void RenderCounter::willBeDestroyed()
483
view()->removeRenderCounter();
484
RenderText::willBeDestroyed();
487
const char* RenderCounter::renderName() const
489
return "RenderCounter";
492
bool RenderCounter::isCounter() const
497
PassRefPtr<StringImpl> RenderCounter::originalText() const
499
if (!m_counterNode) {
500
RenderObject* beforeAfterContainer = parent();
502
if (!beforeAfterContainer)
504
if (!beforeAfterContainer->isAnonymous())
505
return 0; // RenderCounters are restricted to before and after pseudo elements
506
PseudoId containerStyle = beforeAfterContainer->style()->styleType();
507
if ((containerStyle == BEFORE) || (containerStyle == AFTER))
509
beforeAfterContainer = beforeAfterContainer->parent();
511
makeCounterNode(beforeAfterContainer, m_counter.identifier(), true)->addRenderer(const_cast<RenderCounter*>(this));
512
ASSERT(m_counterNode);
514
CounterNode* child = m_counterNode;
515
int value = child->actsAsReset() ? child->value() : child->countInParent();
517
String text = listMarkerText(m_counter.listStyle(), value);
519
if (!m_counter.separator().isNull()) {
520
if (!child->actsAsReset())
521
child = child->parent();
522
while (CounterNode* parent = child->parent()) {
523
text = listMarkerText(m_counter.listStyle(), child->countInParent())
524
+ m_counter.separator() + text;
532
void RenderCounter::updateText()
534
computePreferredLogicalWidths(0);
537
void RenderCounter::computePreferredLogicalWidths(float lead)
539
setTextInternal(originalText());
540
RenderText::computePreferredLogicalWidths(lead);
543
void RenderCounter::invalidate()
545
m_counterNode->removeRenderer(this);
546
ASSERT(!m_counterNode);
547
if (documentBeingDestroyed())
549
setNeedsLayoutAndPrefWidthsRecalc();
552
static void destroyCounterNodeWithoutMapRemoval(const AtomicString& identifier, CounterNode* node)
554
CounterNode* previous;
555
for (RefPtr<CounterNode> child = node->lastDescendant(); child && child != node; child = previous) {
556
previous = child->previousInPreOrder();
557
child->parent()->removeChild(child.get());
558
ASSERT(counterMaps().get(child->owner())->get(identifier) == child);
559
counterMaps().get(child->owner())->remove(identifier);
561
if (CounterNode* parent = node->parent())
562
parent->removeChild(node);
565
void RenderCounter::destroyCounterNodes(RenderObject* owner)
567
CounterMaps& maps = counterMaps();
568
CounterMaps::iterator mapsIterator = maps.find(owner);
569
if (mapsIterator == maps.end())
571
CounterMap* map = mapsIterator->value.get();
572
CounterMap::const_iterator end = map->end();
573
for (CounterMap::const_iterator it = map->begin(); it != end; ++it) {
574
destroyCounterNodeWithoutMapRemoval(it->key, it->value.get());
576
maps.remove(mapsIterator);
577
owner->setHasCounterNodeMap(false);
580
void RenderCounter::destroyCounterNode(RenderObject* owner, const AtomicString& identifier)
582
CounterMap* map = counterMaps().get(owner);
585
CounterMap::iterator mapIterator = map->find(identifier);
586
if (mapIterator == map->end())
588
destroyCounterNodeWithoutMapRemoval(identifier, mapIterator->value.get());
589
map->remove(mapIterator);
590
// We do not delete "map" here even if empty because we expect to reuse
591
// it soon. In order for a renderer to lose all its counters permanently,
592
// a style change for the renderer involving removal of all counter
593
// directives must occur, in which case, RenderCounter::destroyCounterNodes()
595
// The destruction of the Renderer (possibly caused by the removal of its
596
// associated DOM node) is the other case that leads to the permanent
597
// destruction of all counters attached to a Renderer. In this case
598
// RenderCounter::destroyCounterNodes() must be and is now called, too.
599
// RenderCounter::destroyCounterNodes() handles destruction of the counter
600
// map associated with a renderer, so there is no risk in leaking the map.
603
void RenderCounter::rendererRemovedFromTree(RenderObject* renderer)
605
ASSERT(renderer->view());
606
if (!renderer->view()->hasRenderCounters())
608
RenderObject* currentRenderer = renderer->lastLeafChild();
609
if (!currentRenderer)
610
currentRenderer = renderer;
612
destroyCounterNodes(currentRenderer);
613
if (currentRenderer == renderer)
615
currentRenderer = currentRenderer->previousInPreOrder();
619
static void updateCounters(RenderObject* renderer)
621
ASSERT(renderer->style());
622
const CounterDirectiveMap* directiveMap = renderer->style()->counterDirectives();
625
CounterDirectiveMap::const_iterator end = directiveMap->end();
626
if (!renderer->hasCounterNodeMap()) {
627
for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it)
628
makeCounterNode(renderer, it->key, false);
631
CounterMap* counterMap = counterMaps().get(renderer);
633
for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it) {
634
RefPtr<CounterNode> node = counterMap->get(it->key);
636
makeCounterNode(renderer, it->key, false);
639
RefPtr<CounterNode> newParent = 0;
640
RefPtr<CounterNode> newPreviousSibling = 0;
642
findPlaceForCounter(renderer, it->key, node->hasResetType(), newParent, newPreviousSibling);
643
if (node != counterMap->get(it->key))
645
CounterNode* parent = node->parent();
646
if (newParent == parent && newPreviousSibling == node->previousSibling())
649
parent->removeChild(node.get());
651
newParent->insertAfter(node.get(), newPreviousSibling.get(), it->key);
655
void RenderCounter::rendererSubtreeAttached(RenderObject* renderer)
657
ASSERT(renderer->view());
658
if (!renderer->view()->hasRenderCounters())
660
Node* node = renderer->node();
662
node = node->parentNode();
664
node = renderer->generatingNode();
665
if (node && !node->attached())
666
return; // No need to update if the parent is not attached yet
667
for (RenderObject* descendant = renderer; descendant; descendant = descendant->nextInPreOrder(renderer))
668
updateCounters(descendant);
671
void RenderCounter::rendererStyleChanged(RenderObject* renderer, const RenderStyle* oldStyle, const RenderStyle* newStyle)
673
Node* node = renderer->generatingNode();
674
if (!node || !node->attached())
675
return; // cannot have generated content or if it can have, it will be handled during attaching
676
const CounterDirectiveMap* newCounterDirectives;
677
const CounterDirectiveMap* oldCounterDirectives;
678
if (oldStyle && (oldCounterDirectives = oldStyle->counterDirectives())) {
679
if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
680
CounterDirectiveMap::const_iterator newMapEnd = newCounterDirectives->end();
681
CounterDirectiveMap::const_iterator oldMapEnd = oldCounterDirectives->end();
682
for (CounterDirectiveMap::const_iterator it = newCounterDirectives->begin(); it != newMapEnd; ++it) {
683
CounterDirectiveMap::const_iterator oldMapIt = oldCounterDirectives->find(it->key);
684
if (oldMapIt != oldMapEnd) {
685
if (oldMapIt->value == it->value)
687
RenderCounter::destroyCounterNode(renderer, it->key);
689
// We must create this node here, because the changed node may be a node with no display such as
690
// as those created by the increment or reset directives and the re-layout that will happen will
691
// not catch the change if the node had no children.
692
makeCounterNode(renderer, it->key, false);
694
// Destroying old counters that do not exist in the new counterDirective map.
695
for (CounterDirectiveMap::const_iterator it = oldCounterDirectives->begin(); it !=oldMapEnd; ++it) {
696
if (!newCounterDirectives->contains(it->key))
697
RenderCounter::destroyCounterNode(renderer, it->key);
700
if (renderer->hasCounterNodeMap())
701
RenderCounter::destroyCounterNodes(renderer);
703
} else if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
704
CounterDirectiveMap::const_iterator newMapEnd = newCounterDirectives->end();
705
for (CounterDirectiveMap::const_iterator it = newCounterDirectives->begin(); it != newMapEnd; ++it) {
706
// We must create this node here, because the added node may be a node with no display such as
707
// as those created by the increment or reset directives and the re-layout that will happen will
708
// not catch the change if the node had no children.
709
makeCounterNode(renderer, it->key, false);
714
} // namespace WebCore
718
void showCounterRendererTree(const WebCore::RenderObject* renderer, const char* counterName)
722
const WebCore::RenderObject* root = renderer;
723
while (root->parent())
724
root = root->parent();
726
AtomicString identifier(counterName);
727
for (const WebCore::RenderObject* current = root; current; current = current->nextInPreOrder()) {
728
fprintf(stderr, "%c", (current == renderer) ? '*' : ' ');
729
for (const WebCore::RenderObject* parent = current; parent && parent != root; parent = parent->parent())
730
fprintf(stderr, " ");
731
fprintf(stderr, "%p N:%p P:%p PS:%p NS:%p C:%p\n",
732
current, current->node(), current->parent(), current->previousSibling(),
733
current->nextSibling(), current->hasCounterNodeMap() ?
734
counterName ? WebCore::counterMaps().get(current)->get(identifier).get() : (WebCore::CounterNode*)1 : (WebCore::CounterNode*)0);