17c0cfcde3c193a5765690c01d82649a7292a0d8
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / RenderListItem.cpp
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 "core/rendering/RenderListItem.h"
26
27 #include "core/HTMLNames.h"
28 #include "core/dom/NodeRenderingTraversal.h"
29 #include "core/html/HTMLOListElement.h"
30 #include "core/rendering/FastTextAutosizer.h"
31 #include "core/rendering/RenderListMarker.h"
32 #include "core/rendering/RenderView.h"
33 #include "wtf/StdLibExtras.h"
34 #include "wtf/text/StringBuilder.h"
35
36 using namespace std;
37
38 namespace WebCore {
39
40 using namespace HTMLNames;
41
42 RenderListItem::RenderListItem(Element* element)
43     : RenderBlockFlow(element)
44     , m_marker(0)
45     , m_hasExplicitValue(false)
46     , m_isValueUpToDate(false)
47     , m_notInList(false)
48 {
49     setInline(false);
50 }
51
52 void RenderListItem::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
53 {
54     RenderBlockFlow::styleDidChange(diff, oldStyle);
55
56     if (style()->listStyleType() != NoneListStyle
57         || (style()->listStyleImage() && !style()->listStyleImage()->errorOccurred())) {
58         RefPtr<RenderStyle> newStyle = RenderStyle::create();
59         // The marker always inherits from the list item, regardless of where it might end
60         // up (e.g., in some deeply nested line box). See CSS3 spec.
61         newStyle->inheritFrom(style());
62         if (!m_marker)
63             m_marker = RenderListMarker::createAnonymous(this);
64         m_marker->setStyle(newStyle.release());
65     } else if (m_marker) {
66         m_marker->destroy();
67         m_marker = 0;
68     }
69 }
70
71 void RenderListItem::willBeDestroyed()
72 {
73     if (m_marker) {
74         m_marker->destroy();
75         m_marker = 0;
76     }
77     RenderBlockFlow::willBeDestroyed();
78 }
79
80 void RenderListItem::insertedIntoTree()
81 {
82     RenderBlockFlow::insertedIntoTree();
83
84     updateListMarkerNumbers();
85 }
86
87 void RenderListItem::willBeRemovedFromTree()
88 {
89     RenderBlockFlow::willBeRemovedFromTree();
90
91     updateListMarkerNumbers();
92 }
93
94 static bool isList(const Node& node)
95 {
96     return isHTMLUListElement(node) || isHTMLOListElement(node);
97 }
98
99 // Returns the enclosing list with respect to the DOM order.
100 static Node* enclosingList(const RenderListItem* listItem)
101 {
102     Node* listItemNode = listItem->node();
103     Node* firstNode = 0;
104     // We use parentNode because the enclosing list could be a ShadowRoot that's not Element.
105     for (Node* parent = NodeRenderingTraversal::parent(listItemNode); parent; parent = NodeRenderingTraversal::parent(parent)) {
106         if (isList(*parent))
107             return parent;
108         if (!firstNode)
109             firstNode = parent;
110     }
111
112     // If there's no actual <ul> or <ol> list element, then the first found
113     // node acts as our list for purposes of determining what other list items
114     // should be numbered as part of the same list.
115     return firstNode;
116 }
117
118 // Returns the next list item with respect to the DOM order.
119 static RenderListItem* nextListItem(const Node* listNode, const RenderListItem* item = 0)
120 {
121     if (!listNode)
122         return 0;
123
124     const Node* current = item ? item->node() : listNode;
125     ASSERT(current);
126     ASSERT(!current->document().childNeedsDistributionRecalc());
127     current = NodeRenderingTraversal::next(current, listNode);
128
129     while (current) {
130         if (isList(*current)) {
131             // We've found a nested, independent list: nothing to do here.
132             current = NodeRenderingTraversal::next(current, listNode);
133             continue;
134         }
135
136         RenderObject* renderer = current->renderer();
137         if (renderer && renderer->isListItem())
138             return toRenderListItem(renderer);
139
140         // FIXME: Can this be optimized to skip the children of the elements without a renderer?
141         current = NodeRenderingTraversal::next(current, listNode);
142     }
143
144     return 0;
145 }
146
147 // Returns the previous list item with respect to the DOM order.
148 static RenderListItem* previousListItem(const Node* listNode, const RenderListItem* item)
149 {
150     Node* current = item->node();
151     ASSERT(current);
152     ASSERT(!current->document().childNeedsDistributionRecalc());
153     for (current = NodeRenderingTraversal::previous(current, listNode); current && current != listNode; current = NodeRenderingTraversal::previous(current, listNode)) {
154         RenderObject* renderer = current->renderer();
155         if (!renderer || (renderer && !renderer->isListItem()))
156             continue;
157         Node* otherList = enclosingList(toRenderListItem(renderer));
158         // This item is part of our current list, so it's what we're looking for.
159         if (listNode == otherList)
160             return toRenderListItem(renderer);
161         // We found ourself inside another list; lets skip the rest of it.
162         // Use nextIncludingPseudo() here because the other list itself may actually
163         // be a list item itself. We need to examine it, so we do this to counteract
164         // the previousIncludingPseudo() that will be done by the loop.
165         if (otherList)
166             current = NodeRenderingTraversal::next(otherList, listNode);
167     }
168     return 0;
169 }
170
171 void RenderListItem::updateItemValuesForOrderedList(const HTMLOListElement* listNode)
172 {
173     ASSERT(listNode);
174
175     for (RenderListItem* listItem = nextListItem(listNode); listItem; listItem = nextListItem(listNode, listItem))
176         listItem->updateValue();
177 }
178
179 unsigned RenderListItem::itemCountForOrderedList(const HTMLOListElement* listNode)
180 {
181     ASSERT(listNode);
182
183     unsigned itemCount = 0;
184     for (RenderListItem* listItem = nextListItem(listNode); listItem; listItem = nextListItem(listNode, listItem))
185         itemCount++;
186
187     return itemCount;
188 }
189
190 inline int RenderListItem::calcValue() const
191 {
192     if (m_hasExplicitValue)
193         return m_explicitValue;
194
195     Node* list = enclosingList(this);
196     HTMLOListElement* oListElement = isHTMLOListElement(list) ? toHTMLOListElement(list) : 0;
197     int valueStep = 1;
198     if (oListElement && oListElement->isReversed())
199         valueStep = -1;
200
201     // FIXME: This recurses to a possible depth of the length of the list.
202     // That's not good -- we need to change this to an iterative algorithm.
203     if (RenderListItem* previousItem = previousListItem(list, this))
204         return previousItem->value() + valueStep;
205
206     if (oListElement)
207         return oListElement->start();
208
209     return 1;
210 }
211
212 void RenderListItem::updateValueNow() const
213 {
214     m_value = calcValue();
215     m_isValueUpToDate = true;
216 }
217
218 bool RenderListItem::isEmpty() const
219 {
220     return lastChild() == m_marker;
221 }
222
223 static RenderObject* getParentOfFirstLineBox(RenderBlockFlow* curr, RenderObject* marker)
224 {
225     RenderObject* firstChild = curr->firstChild();
226     if (!firstChild)
227         return 0;
228
229     bool inQuirksMode = curr->document().inQuirksMode();
230     for (RenderObject* currChild = firstChild; currChild; currChild = currChild->nextSibling()) {
231         if (currChild == marker)
232             continue;
233
234         if (currChild->isInline() && (!currChild->isRenderInline() || curr->generatesLineBoxesForInlineChild(currChild)))
235             return curr;
236
237         if (currChild->isFloating() || currChild->isOutOfFlowPositioned())
238             continue;
239
240         if (!currChild->isRenderBlockFlow() || (currChild->isBox() && toRenderBox(currChild)->isWritingModeRoot()))
241             break;
242
243         if (curr->isListItem() && inQuirksMode && currChild->node() &&
244             (isHTMLUListElement(*currChild->node()) || isHTMLOListElement(*currChild->node())))
245             break;
246
247         RenderObject* lineBox = getParentOfFirstLineBox(toRenderBlockFlow(currChild), marker);
248         if (lineBox)
249             return lineBox;
250     }
251
252     return 0;
253 }
254
255 void RenderListItem::updateValue()
256 {
257     if (!m_hasExplicitValue) {
258         m_isValueUpToDate = false;
259         if (m_marker)
260             m_marker->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
261     }
262 }
263
264 static RenderObject* firstNonMarkerChild(RenderObject* parent)
265 {
266     RenderObject* result = parent->slowFirstChild();
267     while (result && result->isListMarker())
268         result = result->nextSibling();
269     return result;
270 }
271
272 void RenderListItem::updateMarkerLocation()
273 {
274     // Sanity check the location of our marker.
275     if (m_marker) {
276         RenderObject* markerParent = m_marker->parent();
277         RenderObject* lineBoxParent = getParentOfFirstLineBox(this, m_marker);
278         if (!lineBoxParent) {
279             // If the marker is currently contained inside an anonymous box,
280             // then we are the only item in that anonymous box (since no line box
281             // parent was found).  It's ok to just leave the marker where it is
282             // in this case.
283             if (markerParent && markerParent->isAnonymousBlock())
284                 lineBoxParent = markerParent;
285             else
286                 lineBoxParent = this;
287         }
288
289         if (markerParent != lineBoxParent || m_marker->preferredLogicalWidthsDirty()) {
290             // FIXME: We should not modify the structure of the render tree
291             // during layout. crbug.com/370461
292             DeprecatedDisableModifyRenderTreeStructureAsserts disabler;
293
294             // Removing and adding the marker can trigger repainting in
295             // containers other than ourselves, so we need to disable LayoutState.
296             ForceHorriblySlowRectMapping slowRectMapping(*this);
297             updateFirstLetter();
298             m_marker->remove();
299             if (markerParent)
300                 markerParent->dirtyLinesFromChangedChild(m_marker);
301             if (!lineBoxParent)
302                 lineBoxParent = this;
303             lineBoxParent->addChild(m_marker, firstNonMarkerChild(lineBoxParent));
304             m_marker->updateMarginsAndContent();
305             // If markerParent is an anonymous block that has lost all its children, destroy it.
306             if (markerParent && markerParent->isAnonymousBlock() && !toRenderBlock(markerParent)->firstChild() && !toRenderBlock(markerParent)->continuation())
307                 markerParent->destroy();
308
309             // If the marker is inside we need to redo the preferred width calculations
310             // as the size of the item now includes the size of the list marker.
311             if (m_marker->isInside())
312                 containingBlock()->updateLogicalWidth();
313         }
314     }
315 }
316
317 void RenderListItem::layout()
318 {
319     ASSERT(needsLayout());
320
321     // The marker must be autosized before calling updateMarkerLocation.
322     // It cannot be done in the parent's beginLayout because it is not yet in the render tree.
323     if (m_marker) {
324         FastTextAutosizer* textAutosizer = document().fastTextAutosizer();
325         if (textAutosizer)
326             textAutosizer->inflateListItem(this, m_marker);
327     }
328
329     updateMarkerLocation();
330     RenderBlockFlow::layout();
331 }
332
333 void RenderListItem::addOverflowFromChildren()
334 {
335     RenderBlockFlow::addOverflowFromChildren();
336     positionListMarker();
337 }
338
339 void RenderListItem::positionListMarker()
340 {
341     if (m_marker && m_marker->parent()->isBox() && !m_marker->isInside() && m_marker->inlineBoxWrapper()) {
342         LayoutUnit markerOldLogicalLeft = m_marker->logicalLeft();
343         LayoutUnit blockOffset = 0;
344         LayoutUnit lineOffset = 0;
345         for (RenderBox* o = m_marker->parentBox(); o != this; o = o->parentBox()) {
346             blockOffset += o->logicalTop();
347             lineOffset += o->logicalLeft();
348         }
349
350         bool adjustOverflow = false;
351         LayoutUnit markerLogicalLeft;
352         RootInlineBox& root = m_marker->inlineBoxWrapper()->root();
353         bool hitSelfPaintingLayer = false;
354
355         LayoutUnit lineTop = root.lineTop();
356         LayoutUnit lineBottom = root.lineBottom();
357
358         // FIXME: Need to account for relative positioning in the layout overflow.
359         if (style()->isLeftToRightDirection()) {
360             LayoutUnit leftLineOffset = logicalLeftOffsetForLine(blockOffset, logicalLeftOffsetForLine(blockOffset, false), false);
361             markerLogicalLeft = leftLineOffset - lineOffset - paddingStart() - borderStart() + m_marker->marginStart();
362             m_marker->inlineBoxWrapper()->adjustLineDirectionPosition((markerLogicalLeft - markerOldLogicalLeft).toFloat());
363             for (InlineFlowBox* box = m_marker->inlineBoxWrapper()->parent(); box; box = box->parent()) {
364                 LayoutRect newLogicalVisualOverflowRect = box->logicalVisualOverflowRect(lineTop, lineBottom);
365                 LayoutRect newLogicalLayoutOverflowRect = box->logicalLayoutOverflowRect(lineTop, lineBottom);
366                 if (markerLogicalLeft < newLogicalVisualOverflowRect.x() && !hitSelfPaintingLayer) {
367                     newLogicalVisualOverflowRect.setWidth(newLogicalVisualOverflowRect.maxX() - markerLogicalLeft);
368                     newLogicalVisualOverflowRect.setX(markerLogicalLeft);
369                     if (box == root)
370                         adjustOverflow = true;
371                 }
372                 if (markerLogicalLeft < newLogicalLayoutOverflowRect.x()) {
373                     newLogicalLayoutOverflowRect.setWidth(newLogicalLayoutOverflowRect.maxX() - markerLogicalLeft);
374                     newLogicalLayoutOverflowRect.setX(markerLogicalLeft);
375                     if (box == root)
376                         adjustOverflow = true;
377                 }
378                 box->setOverflowFromLogicalRects(newLogicalLayoutOverflowRect, newLogicalVisualOverflowRect, lineTop, lineBottom);
379                 if (box->boxModelObject()->hasSelfPaintingLayer())
380                     hitSelfPaintingLayer = true;
381             }
382         } else {
383             LayoutUnit rightLineOffset = logicalRightOffsetForLine(blockOffset, logicalRightOffsetForLine(blockOffset, false), false);
384             markerLogicalLeft = rightLineOffset - lineOffset + paddingStart() + borderStart() + m_marker->marginEnd();
385             m_marker->inlineBoxWrapper()->adjustLineDirectionPosition((markerLogicalLeft - markerOldLogicalLeft).toFloat());
386             for (InlineFlowBox* box = m_marker->inlineBoxWrapper()->parent(); box; box = box->parent()) {
387                 LayoutRect newLogicalVisualOverflowRect = box->logicalVisualOverflowRect(lineTop, lineBottom);
388                 LayoutRect newLogicalLayoutOverflowRect = box->logicalLayoutOverflowRect(lineTop, lineBottom);
389                 if (markerLogicalLeft + m_marker->logicalWidth() > newLogicalVisualOverflowRect.maxX() && !hitSelfPaintingLayer) {
390                     newLogicalVisualOverflowRect.setWidth(markerLogicalLeft + m_marker->logicalWidth() - newLogicalVisualOverflowRect.x());
391                     if (box == root)
392                         adjustOverflow = true;
393                 }
394                 if (markerLogicalLeft + m_marker->logicalWidth() > newLogicalLayoutOverflowRect.maxX()) {
395                     newLogicalLayoutOverflowRect.setWidth(markerLogicalLeft + m_marker->logicalWidth() - newLogicalLayoutOverflowRect.x());
396                     if (box == root)
397                         adjustOverflow = true;
398                 }
399                 box->setOverflowFromLogicalRects(newLogicalLayoutOverflowRect, newLogicalVisualOverflowRect, lineTop, lineBottom);
400
401                 if (box->boxModelObject()->hasSelfPaintingLayer())
402                     hitSelfPaintingLayer = true;
403             }
404         }
405
406         if (adjustOverflow) {
407             LayoutRect markerRect(markerLogicalLeft + lineOffset, blockOffset, m_marker->width(), m_marker->height());
408             if (!style()->isHorizontalWritingMode())
409                 markerRect = markerRect.transposedRect();
410             RenderBox* o = m_marker;
411             bool propagateVisualOverflow = true;
412             bool propagateLayoutOverflow = true;
413             do {
414                 o = o->parentBox();
415                 if (o->isRenderBlock()) {
416                     if (propagateVisualOverflow)
417                         toRenderBlock(o)->addContentsVisualOverflow(markerRect);
418                     if (propagateLayoutOverflow)
419                         toRenderBlock(o)->addLayoutOverflow(markerRect);
420                 }
421                 if (o->hasOverflowClip()) {
422                     propagateLayoutOverflow = false;
423                     propagateVisualOverflow = false;
424                 }
425                 if (o->hasSelfPaintingLayer())
426                     propagateVisualOverflow = false;
427                 markerRect.moveBy(-o->location());
428             } while (o != this && propagateVisualOverflow && propagateLayoutOverflow);
429         }
430     }
431 }
432
433 void RenderListItem::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
434 {
435     if (!logicalHeight() && hasOverflowClip())
436         return;
437
438     RenderBlockFlow::paint(paintInfo, paintOffset);
439 }
440
441 const String& RenderListItem::markerText() const
442 {
443     if (m_marker)
444         return m_marker->text();
445     return nullAtom.string();
446 }
447
448 void RenderListItem::explicitValueChanged()
449 {
450     if (m_marker)
451         m_marker->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
452     Node* listNode = enclosingList(this);
453     for (RenderListItem* item = this; item; item = nextListItem(listNode, item))
454         item->updateValue();
455 }
456
457 void RenderListItem::setExplicitValue(int value)
458 {
459     ASSERT(node());
460
461     if (m_hasExplicitValue && m_explicitValue == value)
462         return;
463     m_explicitValue = value;
464     m_value = value;
465     m_hasExplicitValue = true;
466     explicitValueChanged();
467 }
468
469 void RenderListItem::clearExplicitValue()
470 {
471     ASSERT(node());
472
473     if (!m_hasExplicitValue)
474         return;
475     m_hasExplicitValue = false;
476     m_isValueUpToDate = false;
477     explicitValueChanged();
478 }
479
480 static RenderListItem* previousOrNextItem(bool isListReversed, Node* list, RenderListItem* item)
481 {
482     return isListReversed ? previousListItem(list, item) : nextListItem(list, item);
483 }
484
485 void RenderListItem::updateListMarkerNumbers()
486 {
487     // If distribution recalc is needed, updateListMarkerNumber will be re-invoked
488     // after distribution is calculated.
489     if (node()->document().childNeedsDistributionRecalc())
490         return;
491
492     Node* listNode = enclosingList(this);
493     ASSERT(listNode);
494
495     bool isListReversed = false;
496     HTMLOListElement* oListElement = isHTMLOListElement(listNode) ? toHTMLOListElement(listNode) : 0;
497     if (oListElement) {
498         oListElement->itemCountChanged();
499         isListReversed = oListElement->isReversed();
500     }
501
502     // FIXME: The n^2 protection below doesn't help if the elements were inserted after the
503     // the list had already been displayed.
504
505     // Avoid an O(n^2) walk over the children below when they're all known to be attaching.
506     if (listNode->needsAttach())
507         return;
508
509     for (RenderListItem* item = previousOrNextItem(isListReversed, listNode, this); item; item = previousOrNextItem(isListReversed, listNode, item)) {
510         if (!item->m_isValueUpToDate) {
511             // If an item has been marked for update before, we can safely
512             // assume that all the following ones have too.
513             // This gives us the opportunity to stop here and avoid
514             // marking the same nodes again.
515             break;
516         }
517         item->updateValue();
518     }
519 }
520
521 } // namespace WebCore