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