Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / web / PopupListBox.cpp
1 /*
2  * Copyright (c) 2011, Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "PopupListBox.h"
33
34 #include "CSSValueKeywords.h"
35 #include "PopupContainer.h"
36 #include "PopupMenuChromium.h"
37 #include "RuntimeEnabledFeatures.h"
38 #include "core/rendering/RenderTheme.h"
39 #include "platform/KeyboardCodes.h"
40 #include "platform/PlatformGestureEvent.h"
41 #include "platform/PlatformKeyboardEvent.h"
42 #include "platform/PlatformMouseEvent.h"
43 #include "platform/PlatformScreen.h"
44 #include "platform/PlatformTouchEvent.h"
45 #include "platform/PlatformWheelEvent.h"
46 #include "platform/PopupMenuClient.h"
47 #include "platform/fonts/Font.h"
48 #include "platform/fonts/FontCache.h"
49 #include "platform/fonts/FontSelector.h"
50 #include "platform/geometry/IntRect.h"
51 #include "platform/graphics/GraphicsContext.h"
52 #include "platform/scroll/FramelessScrollViewClient.h"
53 #include "platform/scroll/ScrollbarTheme.h"
54 #include "platform/text/StringTruncator.h"
55 #include "platform/text/TextRun.h"
56 #include "wtf/ASCIICType.h"
57 #include "wtf/CurrentTime.h"
58 #include <limits>
59
60 namespace WebCore {
61
62 using namespace WTF::Unicode;
63
64 const int PopupListBox::defaultMaxHeight = 500;
65 static const int maxVisibleRows = 20;
66 static const int minEndOfLinePadding = 2;
67 static const TimeStamp typeAheadTimeoutMs = 1000;
68
69 PopupListBox::PopupListBox(PopupMenuClient* client, bool deviceSupportsTouch)
70     : m_deviceSupportsTouch(deviceSupportsTouch)
71     , m_originalIndex(0)
72     , m_selectedIndex(0)
73     , m_acceptedIndexOnAbandon(-1)
74     , m_visibleRows(0)
75     , m_baseWidth(0)
76     , m_maxHeight(defaultMaxHeight)
77     , m_popupClient(client)
78     , m_repeatingChar(0)
79     , m_lastCharTime(0)
80     , m_maxWindowWidth(std::numeric_limits<int>::max())
81 {
82     setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
83 }
84
85 bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
86 {
87     Scrollbar* scrollbar = scrollbarAtPoint(event.position());
88     if (scrollbar) {
89         m_capturingScrollbar = scrollbar;
90         m_capturingScrollbar->mouseDown(event);
91         return true;
92     }
93
94     if (!isPointInBounds(event.position()))
95         abandon();
96
97     return true;
98 }
99
100 bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
101 {
102     if (m_capturingScrollbar) {
103         m_capturingScrollbar->mouseMoved(event);
104         return true;
105     }
106
107     Scrollbar* scrollbar = scrollbarAtPoint(event.position());
108     if (m_lastScrollbarUnderMouse != scrollbar) {
109         // Send mouse exited to the old scrollbar.
110         if (m_lastScrollbarUnderMouse)
111             m_lastScrollbarUnderMouse->mouseExited();
112         m_lastScrollbarUnderMouse = scrollbar;
113     }
114
115     if (scrollbar) {
116         scrollbar->mouseMoved(event);
117         return true;
118     }
119
120     if (!isPointInBounds(event.position()))
121         return false;
122
123     selectIndex(pointToRowIndex(event.position()));
124     return true;
125 }
126
127 bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
128 {
129     if (m_capturingScrollbar) {
130         m_capturingScrollbar->mouseUp(event);
131         m_capturingScrollbar = 0;
132         return true;
133     }
134
135     if (!isPointInBounds(event.position()))
136         return true;
137
138     if (acceptIndex(pointToRowIndex(event.position())) && m_focusedElement) {
139         m_focusedElement->dispatchMouseEvent(event, EventTypeNames::mouseup);
140         m_focusedElement->dispatchMouseEvent(event, EventTypeNames::click);
141
142         // Clear m_focusedElement here, because we cannot clear in hidePopup()
143         // which is called before dispatchMouseEvent() is called.
144         m_focusedElement = 0;
145     }
146
147     return true;
148 }
149
150 bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
151 {
152     if (!isPointInBounds(event.position())) {
153         abandon();
154         return true;
155     }
156
157     ScrollableArea::handleWheelEvent(event);
158     return true;
159 }
160
161 // Should be kept in sync with handleKeyEvent().
162 bool PopupListBox::isInterestedInEventForKey(int keyCode)
163 {
164     switch (keyCode) {
165     case VKEY_ESCAPE:
166     case VKEY_RETURN:
167     case VKEY_UP:
168     case VKEY_DOWN:
169     case VKEY_PRIOR:
170     case VKEY_NEXT:
171     case VKEY_HOME:
172     case VKEY_END:
173     case VKEY_TAB:
174         return true;
175     default:
176         return false;
177     }
178 }
179
180 bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&)
181 {
182     return false;
183 }
184
185 bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&)
186 {
187     return false;
188 }
189
190 static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
191 {
192     // Check whether the event is a character-typed event or not.
193     // We use RawKeyDown/Char/KeyUp event scheme on all platforms,
194     // so PlatformKeyboardEvent::Char (not RawKeyDown) type event
195     // is considered as character type event.
196     return event.type() == PlatformEvent::Char;
197 }
198
199 bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
200 {
201     if (event.type() == PlatformEvent::KeyUp)
202         return true;
203
204     if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
205         return true;
206
207     switch (event.windowsVirtualKeyCode()) {
208     case VKEY_ESCAPE:
209         abandon(); // may delete this
210         return true;
211     case VKEY_RETURN:
212         if (m_selectedIndex == -1)  {
213             hidePopup();
214             // Don't eat the enter if nothing is selected.
215             return false;
216         }
217         acceptIndex(m_selectedIndex); // may delete this
218         return true;
219     case VKEY_UP:
220         selectPreviousRow();
221         break;
222     case VKEY_DOWN:
223         selectNextRow();
224         break;
225     case VKEY_PRIOR:
226         adjustSelectedIndex(-m_visibleRows);
227         break;
228     case VKEY_NEXT:
229         adjustSelectedIndex(m_visibleRows);
230         break;
231     case VKEY_HOME:
232         adjustSelectedIndex(-m_selectedIndex);
233         break;
234     case VKEY_END:
235         adjustSelectedIndex(m_items.size());
236         break;
237     default:
238         if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
239             && isPrintableChar(event.windowsVirtualKeyCode())
240             && isCharacterTypeEvent(event))
241             typeAheadFind(event);
242         break;
243     }
244
245     if (m_originalIndex != m_selectedIndex) {
246         // Keyboard events should update the selection immediately (but we don't
247         // want to fire the onchange event until the popup is closed, to match
248         // IE). We change the original index so we revert to that when the
249         // popup is closed.
250         m_acceptedIndexOnAbandon = m_selectedIndex;
251
252         setOriginalIndex(m_selectedIndex);
253         m_popupClient->setTextFromItem(m_selectedIndex);
254     }
255     if (event.windowsVirtualKeyCode() == VKEY_TAB) {
256         // TAB is a special case as it should select the current item if any and
257         // advance focus.
258         if (m_selectedIndex >= 0) {
259             acceptIndex(m_selectedIndex); // May delete us.
260             // Return false so the TAB key event is propagated to the page.
261             return false;
262         }
263         // Call abandon() so we honor m_acceptedIndexOnAbandon if set.
264         abandon();
265         // Return false so the TAB key event is propagated to the page.
266         return false;
267     }
268
269     return true;
270 }
271
272 HostWindow* PopupListBox::hostWindow() const
273 {
274     // Our parent is the root ScrollView, so it is the one that has a
275     // HostWindow. FrameView::hostWindow() works similarly.
276     return parent() ? parent()->hostWindow() : 0;
277 }
278
279 bool PopupListBox::shouldPlaceVerticalScrollbarOnLeft() const
280 {
281     return m_popupClient->menuStyle().textDirection() == RTL;
282 }
283
284 // From HTMLSelectElement.cpp
285 static String stripLeadingWhiteSpace(const String& string)
286 {
287     int length = string.length();
288     int i;
289     for (i = 0; i < length; ++i)
290         if (string[i] != noBreakSpace
291             && !isSpaceOrNewline(string[i]))
292             break;
293
294     return string.substring(i, length - i);
295 }
296
297 // From HTMLSelectElement.cpp, with modifications
298 void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
299 {
300     TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
301     TimeStamp delta = now - m_lastCharTime;
302
303     // Reset the time when user types in a character. The time gap between
304     // last character and the current character is used to indicate whether
305     // user typed in a string or just a character as the search prefix.
306     m_lastCharTime = now;
307
308     UChar c = event.windowsVirtualKeyCode();
309
310     String prefix;
311     int searchStartOffset = 1;
312     if (delta > typeAheadTimeoutMs) {
313         m_typedString = prefix = String(&c, 1);
314         m_repeatingChar = c;
315     } else {
316         m_typedString.append(c);
317
318         if (c == m_repeatingChar) {
319             // The user is likely trying to cycle through all the items starting
320             // with this character, so just search on the character.
321             prefix = String(&c, 1);
322         } else {
323             m_repeatingChar = 0;
324             prefix = m_typedString;
325             searchStartOffset = 0;
326         }
327     }
328
329     // Compute a case-folded copy of the prefix string before beginning the
330     // search for a matching element. This code uses foldCase to work around the
331     // fact that String::startWith does not fold non-ASCII characters. This code
332     // can be changed to use startWith once that is fixed.
333     String prefixWithCaseFolded(prefix.foldCase());
334     int itemCount = numItems();
335     int index = (max(0, m_selectedIndex) + searchStartOffset) % itemCount;
336     for (int i = 0; i < itemCount; i++, index = (index + 1) % itemCount) {
337         if (!isSelectableItem(index))
338             continue;
339
340         if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
341             selectIndex(index);
342             return;
343         }
344     }
345 }
346
347 void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
348 {
349     // Adjust coords for scrolled frame.
350     IntRect r = intersection(rect, frameRect());
351     int tx = x() - scrollX() + ((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) ? verticalScrollbar()->width() : 0);
352     int ty = y() - scrollY();
353
354     r.move(-tx, -ty);
355
356     // Set clip rect to match revised damage rect.
357     gc->save();
358     gc->translate(static_cast<float>(tx), static_cast<float>(ty));
359     gc->clip(r);
360
361     // FIXME: Can we optimize scrolling to not require repainting the entire
362     // window? Should we?
363     for (int i = 0; i < numItems(); ++i)
364         paintRow(gc, r, i);
365
366     // Special case for an empty popup.
367     if (!numItems())
368         gc->fillRect(r, Color::white);
369
370     gc->restore();
371
372     ScrollView::paint(gc, rect);
373 }
374
375 static const int separatorPadding = 4;
376 static const int separatorHeight = 1;
377
378 void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
379 {
380     // This code is based largely on RenderListBox::paint* methods.
381
382     IntRect rowRect = getRowBounds(rowIndex);
383     if (!rowRect.intersects(rect))
384         return;
385
386     PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
387
388     // Paint background
389     Color backColor, textColor, labelColor;
390     if (rowIndex == m_selectedIndex) {
391         backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor();
392         textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor();
393         labelColor = textColor;
394     } else {
395         backColor = style.backgroundColor();
396         textColor = style.foregroundColor();
397
398 #if OS(LINUX) || OS(ANDROID)
399         // On other platforms, the <option> background color is the same as the
400         // <select> background color. On Linux, that makes the <option>
401         // background color very dark, so by default, try to use a lighter
402         // background color for <option>s.
403         if (style.backgroundColorType() == PopupMenuStyle::DefaultBackgroundColor && RenderTheme::theme().systemColor(CSSValueButtonface) == backColor)
404             backColor = RenderTheme::theme().systemColor(CSSValueMenu);
405 #endif
406
407         // FIXME: for now the label color is hard-coded. It should be added to
408         // the PopupMenuStyle.
409         labelColor = Color(115, 115, 115);
410     }
411
412     // If we have a transparent background, make sure it has a color to blend
413     // against.
414     if (backColor.hasAlpha())
415         gc->fillRect(rowRect, Color::white);
416
417     gc->fillRect(rowRect, backColor);
418
419     if (m_popupClient->itemIsSeparator(rowIndex)) {
420         IntRect separatorRect(
421             rowRect.x() + separatorPadding,
422             rowRect.y() + (rowRect.height() - separatorHeight) / 2,
423             rowRect.width() - 2 * separatorPadding, separatorHeight);
424         gc->fillRect(separatorRect, textColor);
425         return;
426     }
427
428     if (!style.isVisible())
429         return;
430
431     gc->setFillColor(textColor);
432
433     FontCachePurgePreventer fontCachePurgePreventer;
434
435     Font itemFont = getRowFont(rowIndex);
436     // FIXME: http://crbug.com/19872 We should get the padding of individual option
437     // elements. This probably implies changes to PopupMenuClient.
438     bool rightAligned = m_popupClient->menuStyle().textDirection() == RTL;
439     int textX = 0;
440     int maxWidth = 0;
441     if (rightAligned) {
442         maxWidth = rowRect.width() - max<int>(0, m_popupClient->clientPaddingRight());
443     } else {
444         textX = max<int>(0, m_popupClient->clientPaddingLeft());
445         maxWidth = rowRect.width() - textX;
446     }
447     // Prepare text to be drawn.
448     String itemText = m_popupClient->itemText(rowIndex);
449
450     // Prepare the directionality to draw text.
451     TextRun textRun(itemText, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
452     // If the text is right-to-left, make it right-aligned by adjusting its
453     // beginning position.
454     if (rightAligned)
455         textX += maxWidth - itemFont.width(textRun);
456
457     // Draw the item text.
458     int textY = rowRect.y() + itemFont.fontMetrics().ascent() + (rowRect.height() - itemFont.fontMetrics().height()) / 2;
459     TextRunPaintInfo textRunPaintInfo(textRun);
460     textRunPaintInfo.bounds = rowRect;
461     gc->drawBidiText(itemFont, textRunPaintInfo, IntPoint(textX, textY));
462 }
463
464 Font PopupListBox::getRowFont(int rowIndex)
465 {
466     Font itemFont = m_popupClient->itemStyle(rowIndex).font();
467     if (m_popupClient->itemIsLabel(rowIndex)) {
468         // Bold-ify labels (ie, an <optgroup> heading).
469         FontDescription d = itemFont.fontDescription();
470         d.setWeight(FontWeightBold);
471         Font font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
472         font.update(0);
473         return font;
474     }
475
476     return itemFont;
477 }
478
479 void PopupListBox::abandon()
480 {
481     RefPtr<PopupListBox> keepAlive(this);
482
483     m_selectedIndex = m_originalIndex;
484
485     hidePopup();
486
487     if (m_acceptedIndexOnAbandon >= 0) {
488         if (m_popupClient)
489             m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
490         m_acceptedIndexOnAbandon = -1;
491     }
492 }
493
494 int PopupListBox::pointToRowIndex(const IntPoint& point)
495 {
496     int y = scrollY() + point.y();
497
498     // FIXME: binary search if perf matters.
499     for (int i = 0; i < numItems(); ++i) {
500         if (y < m_items[i]->yOffset)
501             return i-1;
502     }
503
504     // Last item?
505     if (y < contentsHeight())
506         return m_items.size()-1;
507
508     return -1;
509 }
510
511 bool PopupListBox::acceptIndex(int index)
512 {
513     // Clear m_acceptedIndexOnAbandon once user accepts the selected index.
514     if (m_acceptedIndexOnAbandon >= 0)
515         m_acceptedIndexOnAbandon = -1;
516
517     if (index >= numItems())
518         return false;
519
520     if (index < 0) {
521         if (m_popupClient) {
522             // Enter pressed with no selection, just close the popup.
523             hidePopup();
524         }
525         return false;
526     }
527
528     if (isSelectableItem(index)) {
529         RefPtr<PopupListBox> keepAlive(this);
530
531         // Hide ourselves first since valueChanged may have numerous side-effects.
532         hidePopup();
533
534         // Tell the <select> PopupMenuClient what index was selected.
535         m_popupClient->valueChanged(index);
536
537         return true;
538     }
539
540     return false;
541 }
542
543 void PopupListBox::selectIndex(int index)
544 {
545     if (index < 0 || index >= numItems())
546         return;
547
548     bool isSelectable = isSelectableItem(index);
549     if (index != m_selectedIndex && isSelectable) {
550         invalidateRow(m_selectedIndex);
551         m_selectedIndex = index;
552         invalidateRow(m_selectedIndex);
553
554         scrollToRevealSelection();
555         m_popupClient->selectionChanged(m_selectedIndex);
556     } else if (!isSelectable)
557         clearSelection();
558 }
559
560 void PopupListBox::setOriginalIndex(int index)
561 {
562     m_originalIndex = m_selectedIndex = index;
563 }
564
565 int PopupListBox::getRowHeight(int index)
566 {
567     int minimumHeight = PopupMenuChromium::minimumRowHeight();
568     if (m_deviceSupportsTouch)
569         minimumHeight = max(minimumHeight, PopupMenuChromium::optionRowHeightForTouch());
570
571     if (index < 0 || m_popupClient->itemStyle(index).isDisplayNone())
572         return minimumHeight;
573
574     // Separator row height is the same size as itself.
575     if (m_popupClient->itemIsSeparator(index))
576         return max(separatorHeight, minimumHeight);
577
578     int fontHeight = getRowFont(index).fontMetrics().height();
579     return max(fontHeight, minimumHeight);
580 }
581
582 IntRect PopupListBox::getRowBounds(int index)
583 {
584     if (index < 0)
585         return IntRect(0, 0, visibleWidth(), getRowHeight(index));
586
587     return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
588 }
589
590 void PopupListBox::invalidateRow(int index)
591 {
592     if (index < 0)
593         return;
594
595     // Invalidate in the window contents, as FramelessScrollView::invalidateRect
596     // paints in the window coordinates.
597     IntRect clipRect = contentsToWindow(getRowBounds(index));
598     if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar())
599         clipRect.move(verticalScrollbar()->width(), 0);
600     invalidateRect(clipRect);
601 }
602
603 void PopupListBox::scrollToRevealRow(int index)
604 {
605     if (index < 0)
606         return;
607
608     IntRect rowRect = getRowBounds(index);
609
610     if (rowRect.y() < scrollY()) {
611         // Row is above current scroll position, scroll up.
612         ScrollView::setScrollPosition(IntPoint(0, rowRect.y()));
613     } else if (rowRect.maxY() > scrollY() + visibleHeight()) {
614         // Row is below current scroll position, scroll down.
615         ScrollView::setScrollPosition(IntPoint(0, rowRect.maxY() - visibleHeight()));
616     }
617 }
618
619 bool PopupListBox::isSelectableItem(int index)
620 {
621     ASSERT(index >= 0 && index < numItems());
622     return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
623 }
624
625 void PopupListBox::clearSelection()
626 {
627     if (m_selectedIndex != -1) {
628         invalidateRow(m_selectedIndex);
629         m_selectedIndex = -1;
630         m_popupClient->selectionCleared();
631     }
632 }
633
634 void PopupListBox::selectNextRow()
635 {
636     adjustSelectedIndex(1);
637 }
638
639 void PopupListBox::selectPreviousRow()
640 {
641     adjustSelectedIndex(-1);
642 }
643
644 void PopupListBox::adjustSelectedIndex(int delta)
645 {
646     int targetIndex = m_selectedIndex + delta;
647     targetIndex = std::min(std::max(targetIndex, 0), numItems() - 1);
648     if (!isSelectableItem(targetIndex)) {
649         // We didn't land on an option. Try to find one.
650         // We try to select the closest index to target, prioritizing any in
651         // the range [current, target].
652
653         int dir = delta > 0 ? 1 : -1;
654         int testIndex = m_selectedIndex;
655         int bestIndex = m_selectedIndex;
656         bool passedTarget = false;
657         while (testIndex >= 0 && testIndex < numItems()) {
658             if (isSelectableItem(testIndex))
659                 bestIndex = testIndex;
660             if (testIndex == targetIndex)
661                 passedTarget = true;
662             if (passedTarget && bestIndex != m_selectedIndex)
663                 break;
664
665             testIndex += dir;
666         }
667
668         // Pick the best index, which may mean we don't change.
669         targetIndex = bestIndex;
670     }
671
672     // Select the new index, and ensure its visible. We do this regardless of
673     // whether the selection changed to ensure keyboard events always bring the
674     // selection into view.
675     selectIndex(targetIndex);
676     scrollToRevealSelection();
677 }
678
679 void PopupListBox::hidePopup()
680 {
681     if (parent()) {
682         PopupContainer* container = static_cast<PopupContainer*>(parent());
683         if (container->client())
684             container->client()->popupClosed(container);
685         container->notifyPopupHidden();
686     }
687
688     if (m_popupClient)
689         m_popupClient->popupDidHide();
690 }
691
692 void PopupListBox::updateFromElement()
693 {
694     clear();
695
696     int size = m_popupClient->listSize();
697     for (int i = 0; i < size; ++i) {
698         PopupItem::Type type;
699         if (m_popupClient->itemIsSeparator(i))
700             type = PopupItem::TypeSeparator;
701         else if (m_popupClient->itemIsLabel(i))
702             type = PopupItem::TypeGroup;
703         else
704             type = PopupItem::TypeOption;
705         m_items.append(new PopupItem(m_popupClient->itemText(i), type));
706         m_items[i]->enabled = isSelectableItem(i);
707         PopupMenuStyle style = m_popupClient->itemStyle(i);
708         m_items[i]->textDirection = style.textDirection();
709         m_items[i]->hasTextDirectionOverride = style.hasTextDirectionOverride();
710     }
711
712     m_selectedIndex = m_popupClient->selectedIndex();
713     setOriginalIndex(m_selectedIndex);
714
715     layout();
716 }
717
718 void PopupListBox::setMaxWidthAndLayout(int maxWidth)
719 {
720     m_maxWindowWidth = maxWidth;
721     layout();
722 }
723
724 void PopupListBox::layout()
725 {
726     bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
727
728     // Size our child items.
729     int baseWidth = 0;
730     int paddingWidth = 0;
731     int lineEndPaddingWidth = 0;
732     int y = 0;
733     for (int i = 0; i < numItems(); ++i) {
734         // Place the item vertically.
735         m_items[i]->yOffset = y;
736         if (m_popupClient->itemStyle(i).isDisplayNone())
737             continue;
738         y += getRowHeight(i);
739
740         // Ensure the popup is wide enough to fit this item.
741         Font itemFont = getRowFont(i);
742         String text = m_popupClient->itemText(i);
743         int width = 0;
744         if (!text.isEmpty())
745             width = itemFont.width(TextRun(text));
746
747         baseWidth = max(baseWidth, width);
748         // FIXME: http://b/1210481 We should get the padding of individual
749         // option elements.
750         paddingWidth = max<int>(paddingWidth,
751             m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight());
752         lineEndPaddingWidth = max<int>(lineEndPaddingWidth,
753             isRightAligned ? m_popupClient->clientPaddingLeft() : m_popupClient->clientPaddingRight());
754     }
755
756     // Calculate scroll bar width.
757     int windowHeight = 0;
758     m_visibleRows = std::min(numItems(), maxVisibleRows);
759
760     for (int i = 0; i < m_visibleRows; ++i) {
761         int rowHeight = getRowHeight(i);
762
763         // Only clip the window height for non-Mac platforms.
764         if (windowHeight + rowHeight > m_maxHeight) {
765             m_visibleRows = i;
766             break;
767         }
768
769         windowHeight += rowHeight;
770     }
771
772     // Set our widget and scrollable contents sizes.
773     int scrollbarWidth = 0;
774     if (m_visibleRows < numItems()) {
775         scrollbarWidth = ScrollbarTheme::theme()->scrollbarThickness();
776
777         // Use minEndOfLinePadding when there is a scrollbar so that we use
778         // as much as (lineEndPaddingWidth - minEndOfLinePadding) padding
779         // space for scrollbar and allow user to use CSS padding to make the
780         // popup listbox align with the select element.
781         paddingWidth = paddingWidth - lineEndPaddingWidth + minEndOfLinePadding;
782     }
783
784     int windowWidth = baseWidth + scrollbarWidth + paddingWidth;
785     if (windowWidth > m_maxWindowWidth) {
786         // windowWidth exceeds m_maxWindowWidth, so we have to clip.
787         windowWidth = m_maxWindowWidth;
788         baseWidth = windowWidth - scrollbarWidth - paddingWidth;
789         m_baseWidth = baseWidth;
790     }
791     int contentWidth = windowWidth - scrollbarWidth;
792
793     if (windowWidth < m_baseWidth) {
794         windowWidth = m_baseWidth;
795         contentWidth = m_baseWidth - scrollbarWidth;
796     } else {
797         m_baseWidth = baseWidth;
798     }
799
800     resize(windowWidth, windowHeight);
801     setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
802
803     if (hostWindow())
804         scrollToRevealSelection();
805
806     invalidate();
807 }
808
809 void PopupListBox::clear()
810 {
811     for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it)
812         delete *it;
813     m_items.clear();
814 }
815
816 bool PopupListBox::isPointInBounds(const IntPoint& point)
817 {
818     return numItems() && IntRect(0, 0, width(), height()).contains(point);
819 }
820
821 int PopupListBox::popupContentHeight() const
822 {
823     return height();
824 }
825
826 } // namespace WebCore