OSDN Git Service

Merge WebKit at r78450: Initial merge by git.
[android-x86/external-webkit.git] / Source / WebCore / rendering / RenderMenuList.cpp
1 /*
2  * This file is part of the select element renderer in WebCore.
3  *
4  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
5  * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6  *               2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  *
23  */
24
25 #include "config.h"
26 #include "RenderMenuList.h"
27
28 #include "AXObjectCache.h"
29 #include "Chrome.h"
30 #include "CSSStyleSelector.h"
31 #include "Frame.h"
32 #include "FrameView.h"
33 #include "HTMLNames.h"
34 #include "NodeRenderStyle.h"
35 #include "OptionElement.h"
36 #include "OptionGroupElement.h"
37 #include "PopupMenu.h"
38 #include "RenderBR.h"
39 #include "RenderScrollbar.h"
40 #include "RenderTheme.h"
41 #include "SelectElement.h"
42 #include "TextRun.h"
43 #include <math.h>
44
45 using namespace std;
46
47 namespace WebCore {
48
49 using namespace HTMLNames;
50
51 RenderMenuList::RenderMenuList(Element* element)
52     : RenderFlexibleBox(element)
53     , m_buttonText(0)
54     , m_innerBlock(0)
55     , m_optionsChanged(true)
56     , m_optionsWidth(0)
57     , m_lastSelectedIndex(-1)
58     , m_popupIsVisible(false)
59 {
60 }
61
62 RenderMenuList::~RenderMenuList()
63 {
64     if (m_popup)
65         m_popup->disconnectClient();
66     m_popup = 0;
67 }
68
69 void RenderMenuList::createInnerBlock()
70 {
71     if (m_innerBlock) {
72         ASSERT(firstChild() == m_innerBlock);
73         ASSERT(!m_innerBlock->nextSibling());
74         return;
75     }
76
77     // Create an anonymous block.
78     ASSERT(!firstChild());
79     m_innerBlock = createAnonymousBlock();
80     adjustInnerStyle();
81     RenderFlexibleBox::addChild(m_innerBlock);
82 }
83
84 void RenderMenuList::adjustInnerStyle()
85 {
86     RenderStyle* innerStyle = m_innerBlock->style();
87     innerStyle->setBoxFlex(1);
88     
89     innerStyle->setPaddingLeft(Length(theme()->popupInternalPaddingLeft(style()), Fixed));
90     innerStyle->setPaddingRight(Length(theme()->popupInternalPaddingRight(style()), Fixed));
91     innerStyle->setPaddingTop(Length(theme()->popupInternalPaddingTop(style()), Fixed));
92     innerStyle->setPaddingBottom(Length(theme()->popupInternalPaddingBottom(style()), Fixed));
93
94     if (document()->page()->chrome()->selectItemWritingDirectionIsNatural()) {
95         // Items in the popup will not respect the CSS text-align and direction properties,
96         // so we must adjust our own style to match.
97         innerStyle->setTextAlign(LEFT);
98         TextDirection direction = (m_buttonText && m_buttonText->text()->defaultWritingDirection() == WTF::Unicode::RightToLeft) ? RTL : LTR;
99         innerStyle->setDirection(direction);
100     } else if (m_optionStyle && document()->page()->chrome()->selectItemAlignmentFollowsMenuWritingDirection()) {
101         if ((m_optionStyle->direction() != innerStyle->direction() || m_optionStyle->unicodeBidi() != innerStyle->unicodeBidi()))
102             m_innerBlock->setNeedsLayoutAndPrefWidthsRecalc();
103         innerStyle->setTextAlign(style()->isLeftToRightDirection() ? LEFT : RIGHT);
104         innerStyle->setDirection(m_optionStyle->direction());
105         innerStyle->setUnicodeBidi(m_optionStyle->unicodeBidi());
106     }
107 }
108
109 void RenderMenuList::addChild(RenderObject* newChild, RenderObject* beforeChild)
110 {
111     createInnerBlock();
112     m_innerBlock->addChild(newChild, beforeChild);
113 }
114
115 void RenderMenuList::removeChild(RenderObject* oldChild)
116 {
117     if (oldChild == m_innerBlock || !m_innerBlock) {
118         RenderFlexibleBox::removeChild(oldChild);
119         m_innerBlock = 0;
120     } else
121         m_innerBlock->removeChild(oldChild);
122 }
123
124 void RenderMenuList::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
125 {
126     RenderBlock::styleDidChange(diff, oldStyle);
127
128     if (m_buttonText)
129         m_buttonText->setStyle(style());
130     if (m_innerBlock) // RenderBlock handled updating the anonymous block's style.
131         adjustInnerStyle();
132
133     bool fontChanged = !oldStyle || oldStyle->font() != style()->font();
134     if (fontChanged)
135         updateOptionsWidth();
136 }
137
138 void RenderMenuList::updateOptionsWidth()
139 {
140     float maxOptionWidth = 0;
141     const Vector<Element*>& listItems = toSelectElement(static_cast<Element*>(node()))->listItems();
142     int size = listItems.size();    
143     for (int i = 0; i < size; ++i) {
144         Element* element = listItems[i];
145         OptionElement* optionElement = toOptionElement(element);
146         if (!optionElement)
147             continue;
148
149         String text = optionElement->textIndentedToRespectGroupLabel();
150         if (theme()->popupOptionSupportsTextIndent()) {
151             // Add in the option's text indent.  We can't calculate percentage values for now.
152             float optionWidth = 0;
153             if (RenderStyle* optionStyle = element->renderStyle())
154                 optionWidth += optionStyle->textIndent().calcMinValue(0);
155             if (!text.isEmpty())
156                 optionWidth += style()->font().floatWidth(text);
157             maxOptionWidth = max(maxOptionWidth, optionWidth);
158         } else if (!text.isEmpty())
159             maxOptionWidth = max(maxOptionWidth, style()->font().floatWidth(text));
160     }
161
162     int width = static_cast<int>(ceilf(maxOptionWidth));
163     if (m_optionsWidth == width)
164         return;
165
166     m_optionsWidth = width;
167     if (parent())
168         setNeedsLayoutAndPrefWidthsRecalc();
169 }
170
171 void RenderMenuList::updateFromElement()
172 {
173     if (m_optionsChanged) {
174         updateOptionsWidth();
175         m_optionsChanged = false;
176     }
177
178     if (m_popupIsVisible)
179         m_popup->updateFromElement();
180     else
181         setTextFromOption(toSelectElement(static_cast<Element*>(node()))->selectedIndex());
182 }
183
184 void RenderMenuList::setTextFromOption(int optionIndex)
185 {
186     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
187     const Vector<Element*>& listItems = select->listItems();
188     int size = listItems.size();
189
190     int i = select->optionToListIndex(optionIndex);
191     String text = "";
192     if (i >= 0 && i < size) {
193         Element* element = listItems[i];
194         if (OptionElement* optionElement = toOptionElement(element)) {
195             text = optionElement->textIndentedToRespectGroupLabel();
196             m_optionStyle = element->renderStyle();
197         }
198     }
199
200     setText(text.stripWhiteSpace());
201 }
202
203 void RenderMenuList::setText(const String& s)
204 {
205     if (s.isEmpty()) {
206         if (!m_buttonText || !m_buttonText->isBR()) {
207             if (m_buttonText)
208                 m_buttonText->destroy();
209             m_buttonText = new (renderArena()) RenderBR(document());
210             m_buttonText->setStyle(style());
211             addChild(m_buttonText);
212         }
213     } else {
214         if (m_buttonText && !m_buttonText->isBR())
215             m_buttonText->setText(s.impl());
216         else {
217             if (m_buttonText)
218                 m_buttonText->destroy();
219             m_buttonText = new (renderArena()) RenderText(document(), s.impl());
220             m_buttonText->setStyle(style());
221             addChild(m_buttonText);
222         }
223         adjustInnerStyle();
224     }
225 }
226
227 String RenderMenuList::text() const
228 {
229     return m_buttonText ? m_buttonText->text() : 0;
230 }
231
232 IntRect RenderMenuList::controlClipRect(int tx, int ty) const
233 {
234     // Clip to the intersection of the content box and the content box for the inner box
235     // This will leave room for the arrows which sit in the inner box padding,
236     // and if the inner box ever spills out of the outer box, that will get clipped too.
237     IntRect outerBox(tx + borderLeft() + paddingLeft(), 
238                    ty + borderTop() + paddingTop(),
239                    contentWidth(), 
240                    contentHeight());
241     
242     IntRect innerBox(tx + m_innerBlock->x() + m_innerBlock->paddingLeft(), 
243                    ty + m_innerBlock->y() + m_innerBlock->paddingTop(),
244                    m_innerBlock->contentWidth(), 
245                    m_innerBlock->contentHeight());
246
247     return intersection(outerBox, innerBox);
248 }
249
250 void RenderMenuList::computePreferredLogicalWidths()
251 {
252     m_minPreferredLogicalWidth = 0;
253     m_maxPreferredLogicalWidth = 0;
254     
255     if (style()->width().isFixed() && style()->width().value() > 0)
256         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = computeContentBoxLogicalWidth(style()->width().value());
257     else
258         m_maxPreferredLogicalWidth = max(m_optionsWidth, theme()->minimumMenuListSize(style())) + m_innerBlock->paddingLeft() + m_innerBlock->paddingRight();
259
260     if (style()->minWidth().isFixed() && style()->minWidth().value() > 0) {
261         m_maxPreferredLogicalWidth = max(m_maxPreferredLogicalWidth, computeContentBoxLogicalWidth(style()->minWidth().value()));
262         m_minPreferredLogicalWidth = max(m_minPreferredLogicalWidth, computeContentBoxLogicalWidth(style()->minWidth().value()));
263     } else if (style()->width().isPercent() || (style()->width().isAuto() && style()->height().isPercent()))
264         m_minPreferredLogicalWidth = 0;
265     else
266         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth;
267
268     if (style()->maxWidth().isFixed() && style()->maxWidth().value() != undefinedLength) {
269         m_maxPreferredLogicalWidth = min(m_maxPreferredLogicalWidth, computeContentBoxLogicalWidth(style()->maxWidth().value()));
270         m_minPreferredLogicalWidth = min(m_minPreferredLogicalWidth, computeContentBoxLogicalWidth(style()->maxWidth().value()));
271     }
272
273     int toAdd = borderAndPaddingWidth();
274     m_minPreferredLogicalWidth += toAdd;
275     m_maxPreferredLogicalWidth += toAdd;
276
277     setPreferredLogicalWidthsDirty(false);
278 }
279
280 void RenderMenuList::showPopup()
281 {
282     if (m_popupIsVisible)
283         return;
284
285     // Create m_innerBlock here so it ends up as the first child.
286     // This is important because otherwise we might try to create m_innerBlock
287     // inside the showPopup call and it would fail.
288     createInnerBlock();
289     if (!m_popup)
290         m_popup = document()->page()->chrome()->createPopupMenu(this);
291     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
292     m_popupIsVisible = true;
293
294     // Compute the top left taking transforms into account, but use
295     // the actual width of the element to size the popup.
296     FloatPoint absTopLeft = localToAbsolute(FloatPoint(), false, true);
297     IntRect absBounds = absoluteBoundingBoxRect();
298     absBounds.setLocation(roundedIntPoint(absTopLeft));
299     m_popup->show(absBounds, document()->view(),
300         select->optionToListIndex(select->selectedIndex()));
301 }
302
303 void RenderMenuList::hidePopup()
304 {
305     if (m_popup)
306         m_popup->hide();
307 }
308
309 void RenderMenuList::valueChanged(unsigned listIndex, bool fireOnChange)
310 {
311     // Check to ensure a page navigation has not occurred while
312     // the popup was up.
313     Document* doc = static_cast<Element*>(node())->document();
314     if (!doc || doc != doc->frame()->document())
315         return;
316     
317     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
318     select->setSelectedIndexByUser(select->listToOptionIndex(listIndex), true, fireOnChange);
319 }
320
321 #if ENABLE(NO_LISTBOX_RENDERING)
322 void RenderMenuList::listBoxSelectItem(int listIndex, bool allowMultiplySelections, bool shift, bool fireOnChangeNow)
323 {
324     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
325     select->listBoxSelectItem(listIndex, allowMultiplySelections, shift, fireOnChangeNow);
326 }
327
328 bool RenderMenuList::multiple()
329 {
330     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
331     return select->multiple();
332 }
333 #endif
334
335 void RenderMenuList::didSetSelectedIndex()
336 {
337     int index = selectedIndex();
338     if (m_lastSelectedIndex == index)
339         return;
340
341     m_lastSelectedIndex = index;
342
343     if (AXObjectCache::accessibilityEnabled())
344         document()->axObjectCache()->postNotification(this, AXObjectCache::AXMenuListValueChanged, true, PostSynchronously);
345 }
346
347 String RenderMenuList::itemText(unsigned listIndex) const
348 {
349     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
350     const Vector<Element*>& listItems = select->listItems();
351     if (listIndex >= listItems.size())
352         return String();
353     Element* element = listItems[listIndex];
354     if (OptionGroupElement* optionGroupElement = toOptionGroupElement(element))
355         return optionGroupElement->groupLabelText();
356     else if (OptionElement* optionElement = toOptionElement(element))
357         return optionElement->textIndentedToRespectGroupLabel();
358     return String();
359 }
360
361 String RenderMenuList::itemLabel(unsigned) const
362 {
363     return String();
364 }
365
366 String RenderMenuList::itemIcon(unsigned) const
367 {
368     return String();
369 }
370
371 String RenderMenuList::itemAccessibilityText(unsigned listIndex) const
372 {
373     // Allow the accessible name be changed if necessary.
374     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
375     const Vector<Element*>& listItems = select->listItems();
376     if (listIndex >= listItems.size())
377         return String();
378
379     return listItems[listIndex]->getAttribute(aria_labelAttr);
380 }
381     
382 String RenderMenuList::itemToolTip(unsigned listIndex) const
383 {
384     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
385     const Vector<Element*>& listItems = select->listItems();
386     if (listIndex >= listItems.size())
387         return String();
388     Element* element = listItems[listIndex];
389     return element->title();
390 }
391
392 bool RenderMenuList::itemIsEnabled(unsigned listIndex) const
393 {
394     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
395     const Vector<Element*>& listItems = select->listItems();
396     if (listIndex >= listItems.size())
397         return false;
398     Element* element = listItems[listIndex];
399     if (!isOptionElement(element))
400         return false;
401
402     bool groupEnabled = true;
403     if (Element* parentElement = element->parentElement()) {
404         if (isOptionGroupElement(parentElement))
405             groupEnabled = parentElement->isEnabledFormControl();
406     }
407     if (!groupEnabled)
408         return false;
409
410     return element->isEnabledFormControl();
411 }
412
413 PopupMenuStyle RenderMenuList::itemStyle(unsigned listIndex) const
414 {
415     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
416     const Vector<Element*>& listItems = select->listItems();
417     if (listIndex >= listItems.size()) {
418         // If we are making an out of bounds access, then we want to use the style
419         // of a different option element (index 0). However, if there isn't an option element
420         // before at index 0, we fall back to the menu's style.
421         if (!listIndex)
422             return menuStyle();
423
424         // Try to retrieve the style of an option element we know exists (index 0).
425         listIndex = 0;
426     }
427     Element* element = listItems[listIndex];
428     
429     RenderStyle* style = element->renderStyle() ? element->renderStyle() : element->computedStyle();
430     return style ? PopupMenuStyle(style->visitedDependentColor(CSSPropertyColor), itemBackgroundColor(listIndex), style->font(), style->visibility() == VISIBLE, style->display() == NONE, style->textIndent(), style->direction(), style->unicodeBidi() == Override) : menuStyle();
431 }
432
433 Color RenderMenuList::itemBackgroundColor(unsigned listIndex) const
434 {
435     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
436     const Vector<Element*>& listItems = select->listItems();
437     if (listIndex >= listItems.size())
438         return style()->visitedDependentColor(CSSPropertyBackgroundColor);
439     Element* element = listItems[listIndex];
440
441     Color backgroundColor;
442     if (element->renderStyle())
443         backgroundColor = element->renderStyle()->visitedDependentColor(CSSPropertyBackgroundColor);
444     // If the item has an opaque background color, return that.
445     if (!backgroundColor.hasAlpha())
446         return backgroundColor;
447
448     // Otherwise, the item's background is overlayed on top of the menu background.
449     backgroundColor = style()->visitedDependentColor(CSSPropertyBackgroundColor).blend(backgroundColor);
450     if (!backgroundColor.hasAlpha())
451         return backgroundColor;
452
453     // If the menu background is not opaque, then add an opaque white background behind.
454     return Color(Color::white).blend(backgroundColor);
455 }
456
457 PopupMenuStyle RenderMenuList::menuStyle() const
458 {
459     RenderStyle* s = m_innerBlock ? m_innerBlock->style() : style();
460     return PopupMenuStyle(s->visitedDependentColor(CSSPropertyColor), s->visitedDependentColor(CSSPropertyBackgroundColor), s->font(), s->visibility() == VISIBLE, s->display() == NONE, s->textIndent(), style()->direction(), style()->unicodeBidi() == Override);
461 }
462
463 HostWindow* RenderMenuList::hostWindow() const
464 {
465     return document()->view()->hostWindow();
466 }
467
468 PassRefPtr<Scrollbar> RenderMenuList::createScrollbar(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, ScrollbarControlSize controlSize)
469 {
470     RefPtr<Scrollbar> widget;
471     bool hasCustomScrollbarStyle = style()->hasPseudoStyle(SCROLLBAR);
472     if (hasCustomScrollbarStyle)
473         widget = RenderScrollbar::createCustomScrollbar(scrollableArea, orientation, this);
474     else
475         widget = Scrollbar::createNativeScrollbar(scrollableArea, orientation, controlSize);
476     return widget.release();
477 }
478
479 int RenderMenuList::clientInsetLeft() const
480 {
481     return 0;
482 }
483
484 int RenderMenuList::clientInsetRight() const
485 {
486     return 0;
487 }
488
489 int RenderMenuList::clientPaddingLeft() const
490 {
491     return paddingLeft() + m_innerBlock->paddingLeft();
492 }
493
494 const int endOfLinePadding = 2;
495 int RenderMenuList::clientPaddingRight() const
496 {
497     if (style()->appearance() == MenulistPart || style()->appearance() == MenulistButtonPart) {
498         // For these appearance values, the theme applies padding to leave room for the
499         // drop-down button. But leaving room for the button inside the popup menu itself
500         // looks strange, so we return a small default padding to avoid having a large empty
501         // space appear on the side of the popup menu.
502         return endOfLinePadding;
503     }
504
505     // If the appearance isn't MenulistPart, then the select is styled (non-native), so
506     // we want to return the user specified padding.
507     return paddingRight() + m_innerBlock->paddingRight();
508 }
509
510 int RenderMenuList::listSize() const
511 {
512     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
513     return select->listItems().size();
514 }
515
516 int RenderMenuList::selectedIndex() const
517 {
518     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
519     return select->optionToListIndex(select->selectedIndex());
520 }
521
522 void RenderMenuList::popupDidHide()
523 {
524     m_popupIsVisible = false;
525 }
526
527 bool RenderMenuList::itemIsSeparator(unsigned listIndex) const
528 {
529     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
530     const Vector<Element*>& listItems = select->listItems();
531     if (listIndex >= listItems.size())
532         return false;
533     Element* element = listItems[listIndex];
534     return element->hasTagName(hrTag);
535 }
536
537 bool RenderMenuList::itemIsLabel(unsigned listIndex) const
538 {
539     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
540     const Vector<Element*>& listItems = select->listItems();
541     if (listIndex >= listItems.size())
542         return false;
543     Element* element = listItems[listIndex];
544     return isOptionGroupElement(element);
545 }
546
547 bool RenderMenuList::itemIsSelected(unsigned listIndex) const
548 {
549     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
550     const Vector<Element*>& listItems = select->listItems();
551     if (listIndex >= listItems.size())
552         return false;
553     Element* element = listItems[listIndex];
554     if (OptionElement* optionElement = toOptionElement(element))
555         return optionElement->selected();
556     return false;
557 }
558
559 void RenderMenuList::setTextFromItem(unsigned listIndex)
560 {
561     SelectElement* select = toSelectElement(static_cast<Element*>(node()));
562     setTextFromOption(select->listToOptionIndex(listIndex));
563 }
564
565 FontSelector* RenderMenuList::fontSelector() const
566 {
567     return document()->styleSelector()->fontSelector();
568 }
569
570 }