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