1/**
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * Copyright (C) 2003, 2004, 2005, 2006, 2010 Apple Inc. All rights reserved.
5 * Copyright (C) 2006 Andrew Wellington (proton@wiretapped.net)
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Library General Public License for more details.
16 *
17 * You should have received a copy of the GNU Library General Public License
18 * along with this library; see the file COPYING.LIB.  If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
21 *
22 */
23
24#include "config.h"
25#include "RenderListItem.h"
26
27#include "CachedImage.h"
28#include "HTMLNames.h"
29#include "HTMLOListElement.h"
30#include "RenderListMarker.h"
31#include "RenderView.h"
32#include <wtf/StdLibExtras.h>
33
34using namespace std;
35
36namespace WebCore {
37
38using namespace HTMLNames;
39
40RenderListItem::RenderListItem(Node* node)
41    : RenderBlock(node)
42    , m_marker(0)
43    , m_hasExplicitValue(false)
44    , m_isValueUpToDate(false)
45    , m_notInList(false)
46{
47    setInline(false);
48}
49
50void RenderListItem::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
51{
52    RenderBlock::styleDidChange(diff, oldStyle);
53
54    if (style()->listStyleType() != NoneListStyle
55        || (style()->listStyleImage() && !style()->listStyleImage()->errorOccurred())) {
56        RefPtr<RenderStyle> newStyle = RenderStyle::create();
57        // The marker always inherits from the list item, regardless of where it might end
58        // up (e.g., in some deeply nested line box). See CSS3 spec.
59        newStyle->inheritFrom(style());
60        if (!m_marker)
61            m_marker = new (renderArena()) RenderListMarker(this);
62        m_marker->setStyle(newStyle.release());
63    } else if (m_marker) {
64        m_marker->destroy();
65        m_marker = 0;
66    }
67}
68
69void RenderListItem::destroy()
70{
71    if (m_marker) {
72        m_marker->destroy();
73        m_marker = 0;
74    }
75    RenderBlock::destroy();
76}
77
78static bool isList(Node* node)
79{
80    return (node->hasTagName(ulTag) || node->hasTagName(olTag));
81}
82
83static Node* enclosingList(const RenderListItem* listItem)
84{
85    Node* firstNode = 0;
86
87    for (const RenderObject* renderer = listItem->parent(); renderer; renderer = renderer->parent()) {
88        Node* node = renderer->node();
89        if (node) {
90            if (isList(node))
91                return node;
92            if (!firstNode)
93                firstNode = node;
94        }
95    }
96
97    // If there's no actual <ul> or <ol> list element, then the first found
98    // node acts as our list for purposes of determining what other list items
99    // should be numbered as part of the same list.
100    return firstNode;
101}
102
103static RenderListItem* previousListItem(Node* list, const RenderListItem* item)
104{
105    for (RenderObject* renderer = item->previousInPreOrder(); renderer && renderer != list->renderer(); renderer = renderer->previousInPreOrder()) {
106        if (!renderer->isListItem())
107            continue;
108        Node* otherList = enclosingList(toRenderListItem(renderer));
109        // This item is part of our current list, so it's what we're looking for.
110        if (list == otherList)
111            return toRenderListItem(renderer);
112        // We found ourself inside another list; lets skip the rest of it.
113        // Use nextInPreOrder() here because the other list itself may actually
114        // be a list item itself. We need to examine it, so we do this to counteract
115        // the previousInPreOrder() that will be done by the loop.
116        if (otherList)
117            renderer = otherList->renderer()->nextInPreOrder();
118    }
119    return 0;
120}
121
122inline int RenderListItem::calcValue() const
123{
124    if (m_hasExplicitValue)
125        return m_explicitValue;
126    Node* list = enclosingList(this);
127    // FIXME: This recurses to a possible depth of the length of the list.
128    // That's not good -- we need to change this to an iterative algorithm.
129    if (RenderListItem* previousItem = previousListItem(list, this))
130        return previousItem->value() + 1;
131    if (list && list->hasTagName(olTag))
132        return static_cast<HTMLOListElement*>(list)->start();
133    return 1;
134}
135
136void RenderListItem::updateValueNow() const
137{
138    m_value = calcValue();
139    m_isValueUpToDate = true;
140}
141
142bool RenderListItem::isEmpty() const
143{
144    return lastChild() == m_marker;
145}
146
147static RenderObject* getParentOfFirstLineBox(RenderBlock* curr, RenderObject* marker)
148{
149    RenderObject* firstChild = curr->firstChild();
150    if (!firstChild)
151        return 0;
152
153    bool inQuirksMode = curr->document()->inQuirksMode();
154    for (RenderObject* currChild = firstChild; currChild; currChild = currChild->nextSibling()) {
155        if (currChild == marker)
156            continue;
157
158        if (currChild->isInline() && (!currChild->isRenderInline() || curr->generatesLineBoxesForInlineChild(currChild)))
159            return curr;
160
161        if (currChild->isFloating() || currChild->isPositioned())
162            continue;
163
164        if (currChild->isTable() || !currChild->isRenderBlock() || (currChild->isBox() && toRenderBox(currChild)->isWritingModeRoot()))
165            break;
166
167        if (curr->isListItem() && inQuirksMode && currChild->node() &&
168            (currChild->node()->hasTagName(ulTag)|| currChild->node()->hasTagName(olTag)))
169            break;
170
171        RenderObject* lineBox = getParentOfFirstLineBox(toRenderBlock(currChild), marker);
172        if (lineBox)
173            return lineBox;
174    }
175
176    return 0;
177}
178
179void RenderListItem::updateValue()
180{
181    if (!m_hasExplicitValue) {
182        m_isValueUpToDate = false;
183        if (m_marker)
184            m_marker->setNeedsLayoutAndPrefWidthsRecalc();
185    }
186}
187
188static RenderObject* firstNonMarkerChild(RenderObject* parent)
189{
190    RenderObject* result = parent->firstChild();
191    while (result && result->isListMarker())
192        result = result->nextSibling();
193    return result;
194}
195
196void RenderListItem::updateMarkerLocation()
197{
198    // Sanity check the location of our marker.
199    if (m_marker) {
200        RenderObject* markerPar = m_marker->parent();
201        RenderObject* lineBoxParent = getParentOfFirstLineBox(this, m_marker);
202        if (!lineBoxParent) {
203            // If the marker is currently contained inside an anonymous box,
204            // then we are the only item in that anonymous box (since no line box
205            // parent was found).  It's ok to just leave the marker where it is
206            // in this case.
207            if (markerPar && markerPar->isAnonymousBlock())
208                lineBoxParent = markerPar;
209            else
210                lineBoxParent = this;
211        }
212
213        if (markerPar != lineBoxParent || m_marker->preferredLogicalWidthsDirty()) {
214            // Removing and adding the marker can trigger repainting in
215            // containers other than ourselves, so we need to disable LayoutState.
216            view()->disableLayoutState();
217            updateFirstLetter();
218            m_marker->remove();
219            if (!lineBoxParent)
220                lineBoxParent = this;
221            lineBoxParent->addChild(m_marker, firstNonMarkerChild(lineBoxParent));
222            if (m_marker->preferredLogicalWidthsDirty())
223                m_marker->computePreferredLogicalWidths();
224            view()->enableLayoutState();
225        }
226    }
227}
228
229void RenderListItem::computePreferredLogicalWidths()
230{
231    ASSERT(preferredLogicalWidthsDirty());
232
233    updateMarkerLocation();
234
235    RenderBlock::computePreferredLogicalWidths();
236}
237
238void RenderListItem::layout()
239{
240    ASSERT(needsLayout());
241
242    updateMarkerLocation();
243    RenderBlock::layout();
244}
245
246void RenderListItem::addOverflowFromChildren()
247{
248    RenderBlock::addOverflowFromChildren();
249    positionListMarker();
250}
251
252void RenderListItem::positionListMarker()
253{
254    if (m_marker && m_marker->parent()->isBox() && !m_marker->isInside() && m_marker->inlineBoxWrapper()) {
255        int markerOldLogicalLeft = m_marker->logicalLeft();
256        int blockOffset = 0;
257        int lineOffset = 0;
258        for (RenderBox* o = m_marker->parentBox(); o != this; o = o->parentBox()) {
259            blockOffset += o->logicalTop();
260            lineOffset += o->logicalLeft();
261        }
262
263        bool adjustOverflow = false;
264        int markerLogicalLeft;
265        RootInlineBox* root = m_marker->inlineBoxWrapper()->root();
266        bool hitSelfPaintingLayer = false;
267
268        RootInlineBox* rootBox = m_marker->inlineBoxWrapper()->root();
269        int lineTop = rootBox->lineTop();
270        int lineBottom = rootBox->lineBottom();
271
272        // FIXME: Need to account for relative positioning in the layout overflow.
273        if (style()->isLeftToRightDirection()) {
274            int leftLineOffset = logicalLeftOffsetForLine(blockOffset, logicalLeftOffsetForLine(blockOffset, false), false);
275            markerLogicalLeft = leftLineOffset - lineOffset - paddingStart() - borderStart() + m_marker->marginStart();
276            m_marker->inlineBoxWrapper()->adjustLineDirectionPosition(markerLogicalLeft - markerOldLogicalLeft);
277            for (InlineFlowBox* box = m_marker->inlineBoxWrapper()->parent(); box; box = box->parent()) {
278                IntRect newLogicalVisualOverflowRect = box->logicalVisualOverflowRect(lineTop, lineBottom);
279                IntRect newLogicalLayoutOverflowRect = box->logicalLayoutOverflowRect(lineTop, lineBottom);
280                if (markerLogicalLeft < newLogicalVisualOverflowRect.x() && !hitSelfPaintingLayer) {
281                    newLogicalVisualOverflowRect.setWidth(newLogicalVisualOverflowRect.maxX() - markerLogicalLeft);
282                    newLogicalVisualOverflowRect.setX(markerLogicalLeft);
283                    if (box == root)
284                        adjustOverflow = true;
285                }
286                if (markerLogicalLeft < newLogicalLayoutOverflowRect.x()) {
287                    newLogicalLayoutOverflowRect.setWidth(newLogicalLayoutOverflowRect.maxX() - markerLogicalLeft);
288                    newLogicalLayoutOverflowRect.setX(markerLogicalLeft);
289                    if (box == root)
290                        adjustOverflow = true;
291                }
292                box->setOverflowFromLogicalRects(newLogicalLayoutOverflowRect, newLogicalVisualOverflowRect, lineTop, lineBottom);
293                if (box->boxModelObject()->hasSelfPaintingLayer())
294                    hitSelfPaintingLayer = true;
295            }
296        } else {
297            markerLogicalLeft = m_marker->logicalLeft() + paddingStart() + borderStart() + m_marker->marginEnd();
298            int rightLineOffset = logicalRightOffsetForLine(blockOffset, logicalRightOffsetForLine(blockOffset, false), false);
299            markerLogicalLeft = rightLineOffset - lineOffset + paddingStart() + borderStart() + m_marker->marginEnd();
300            m_marker->inlineBoxWrapper()->adjustLineDirectionPosition(markerLogicalLeft - markerOldLogicalLeft);
301            for (InlineFlowBox* box = m_marker->inlineBoxWrapper()->parent(); box; box = box->parent()) {
302                IntRect newLogicalVisualOverflowRect = box->logicalVisualOverflowRect(lineTop, lineBottom);
303                IntRect newLogicalLayoutOverflowRect = box->logicalLayoutOverflowRect(lineTop, lineBottom);
304                if (markerLogicalLeft + m_marker->logicalWidth() > newLogicalVisualOverflowRect.maxX() && !hitSelfPaintingLayer) {
305                    newLogicalVisualOverflowRect.setWidth(markerLogicalLeft + m_marker->logicalWidth() - newLogicalVisualOverflowRect.x());
306                    if (box == root)
307                        adjustOverflow = true;
308                }
309                if (markerLogicalLeft + m_marker->logicalWidth() > newLogicalLayoutOverflowRect.maxX()) {
310                    newLogicalLayoutOverflowRect.setWidth(markerLogicalLeft + m_marker->logicalWidth() - newLogicalLayoutOverflowRect.x());
311                    if (box == root)
312                        adjustOverflow = true;
313                }
314                box->setOverflowFromLogicalRects(newLogicalLayoutOverflowRect, newLogicalVisualOverflowRect, lineTop, lineBottom);
315
316                if (box->boxModelObject()->hasSelfPaintingLayer())
317                    hitSelfPaintingLayer = true;
318            }
319        }
320
321        if (adjustOverflow) {
322            IntRect markerRect(markerLogicalLeft + lineOffset, blockOffset, m_marker->width(), m_marker->height());
323            if (!style()->isHorizontalWritingMode())
324                markerRect = markerRect.transposedRect();
325            RenderBox* o = m_marker;
326            bool propagateVisualOverflow = true;
327            bool propagateLayoutOverflow = true;
328            do {
329                o = o->parentBox();
330                if (o->hasOverflowClip())
331                    propagateVisualOverflow = false;
332                if (o->isRenderBlock()) {
333                    if (propagateVisualOverflow)
334                        toRenderBlock(o)->addVisualOverflow(markerRect);
335                    if (propagateLayoutOverflow)
336                        toRenderBlock(o)->addLayoutOverflow(markerRect);
337                }
338                if (o->hasOverflowClip())
339                    propagateLayoutOverflow = false;
340                if (o->hasSelfPaintingLayer())
341                    propagateVisualOverflow = false;
342                markerRect.move(-o->x(), -o->y());
343            } while (o != this && propagateVisualOverflow && propagateLayoutOverflow);
344        }
345    }
346}
347
348void RenderListItem::paint(PaintInfo& paintInfo, int tx, int ty)
349{
350    if (!logicalHeight())
351        return;
352
353    RenderBlock::paint(paintInfo, tx, ty);
354}
355
356const String& RenderListItem::markerText() const
357{
358    if (m_marker)
359        return m_marker->text();
360    DEFINE_STATIC_LOCAL(String, staticNullString, ());
361    return staticNullString;
362}
363
364String RenderListItem::markerTextWithSuffix() const
365{
366    if (!m_marker)
367        return String();
368
369    // Append the suffix for the marker in the right place depending
370    // on the direction of the text (right-to-left or left-to-right).
371
372    const String& markerText = m_marker->text();
373    const String markerSuffix = m_marker->suffix();
374    Vector<UChar> resultVector;
375
376    if (!m_marker->style()->isLeftToRightDirection())
377        resultVector.append(markerSuffix.characters(), markerSuffix.length());
378
379    resultVector.append(markerText.characters(), markerText.length());
380
381    if (m_marker->style()->isLeftToRightDirection())
382        resultVector.append(markerSuffix.characters(), markerSuffix.length());
383
384    return String::adopt(resultVector);
385}
386
387void RenderListItem::explicitValueChanged()
388{
389    if (m_marker)
390        m_marker->setNeedsLayoutAndPrefWidthsRecalc();
391    Node* listNode = enclosingList(this);
392    RenderObject* listRenderer = 0;
393    if (listNode)
394        listRenderer = listNode->renderer();
395    for (RenderObject* renderer = this; renderer; renderer = renderer->nextInPreOrder(listRenderer))
396        if (renderer->isListItem()) {
397            RenderListItem* item = toRenderListItem(renderer);
398            if (!item->m_hasExplicitValue) {
399                item->m_isValueUpToDate = false;
400                if (RenderListMarker* marker = item->m_marker)
401                    marker->setNeedsLayoutAndPrefWidthsRecalc();
402            }
403        }
404}
405
406void RenderListItem::setExplicitValue(int value)
407{
408    ASSERT(node());
409
410    if (m_hasExplicitValue && m_explicitValue == value)
411        return;
412    m_explicitValue = value;
413    m_value = value;
414    m_hasExplicitValue = true;
415    explicitValueChanged();
416}
417
418void RenderListItem::clearExplicitValue()
419{
420    ASSERT(node());
421
422    if (!m_hasExplicitValue)
423        return;
424    m_hasExplicitValue = false;
425    m_isValueUpToDate = false;
426    explicitValueChanged();
427}
428
429void RenderListItem::updateListMarkerNumbers()
430{
431    Node* listNode = enclosingList(this);
432    ASSERT(listNode && listNode->renderer());
433    if (!listNode || !listNode->renderer())
434        return;
435
436    RenderObject* list = listNode->renderer();
437    RenderObject* child = nextInPreOrder(list);
438    while (child) {
439        if (child->node() && isList(child->node())) {
440            // We've found a nested, independent list: nothing to do here.
441            child = child->nextInPreOrderAfterChildren(list);
442            continue;
443        }
444
445        if (child->isListItem()) {
446            RenderListItem* item = toRenderListItem(child);
447
448            if (!item->m_isValueUpToDate) {
449                // If an item has been marked for update before, we can safely
450                // assume that all the following ones have too.
451                // This gives us the opportunity to stop here and avoid
452                // marking the same nodes again.
453                break;
454            }
455
456            item->updateValue();
457        }
458
459        child = child->nextInPreOrder(list);
460    }
461}
462
463} // namespace WebCore
464