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/graphics/GraphicsContextStateSaver.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/PopupContainerClient.h"
56#include "web/PopupMenuChromium.h"
57#include "wtf/ASCIICType.h"
58#include "wtf/CurrentTime.h"
59#include <limits>
60
61namespace blink {
62
63using namespace WTF::Unicode;
64
65const int PopupListBox::defaultMaxHeight = 500;
66static const int maxVisibleRows = 20;
67static const int minEndOfLinePadding = 2;
68static const TimeStamp typeAheadTimeoutMs = 1000;
69
70PopupListBox::PopupListBox(PopupMenuClient* client, bool deviceSupportsTouch, PopupContainer* container)
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    , m_container(container)
83{
84}
85
86PopupListBox::~PopupListBox()
87{
88    clear();
89
90    setHasVerticalScrollbar(false);
91}
92
93bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
94{
95    Scrollbar* scrollbar = scrollbarAtWindowPoint(event.position());
96    if (scrollbar) {
97        m_capturingScrollbar = scrollbar;
98        m_capturingScrollbar->mouseDown(event);
99        return true;
100    }
101
102    if (!isPointInBounds(event.position()))
103        abandon();
104
105    return true;
106}
107
108bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
109{
110    if (m_capturingScrollbar) {
111        m_capturingScrollbar->mouseMoved(event);
112        return true;
113    }
114
115    Scrollbar* scrollbar = scrollbarAtWindowPoint(event.position());
116    if (m_lastScrollbarUnderMouse != scrollbar) {
117        // Send mouse exited to the old scrollbar.
118        if (m_lastScrollbarUnderMouse)
119            m_lastScrollbarUnderMouse->mouseExited();
120        m_lastScrollbarUnderMouse = scrollbar;
121    }
122
123    if (scrollbar) {
124        scrollbar->mouseMoved(event);
125        return true;
126    }
127
128    if (!isPointInBounds(event.position()))
129        return false;
130
131    selectIndex(pointToRowIndex(event.position()));
132    return true;
133}
134
135bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
136{
137    if (m_capturingScrollbar) {
138        m_capturingScrollbar->mouseUp(event);
139        m_capturingScrollbar = nullptr;
140        return true;
141    }
142
143    if (!isPointInBounds(event.position()))
144        return true;
145
146    if (acceptIndex(pointToRowIndex(event.position())) && m_focusedElement) {
147        m_focusedElement->dispatchMouseEvent(event, EventTypeNames::mouseup);
148        m_focusedElement->dispatchMouseEvent(event, EventTypeNames::click);
149
150        // Clear m_focusedElement here, because we cannot clear in hidePopup()
151        // which is called before dispatchMouseEvent() is called.
152        m_focusedElement = nullptr;
153    }
154
155    return true;
156}
157
158bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
159{
160    if (!isPointInBounds(event.position())) {
161        abandon();
162        return true;
163    }
164
165    ScrollableArea::handleWheelEvent(event);
166    return true;
167}
168
169// Should be kept in sync with handleKeyEvent().
170bool PopupListBox::isInterestedInEventForKey(int keyCode)
171{
172    switch (keyCode) {
173    case VKEY_ESCAPE:
174    case VKEY_RETURN:
175    case VKEY_UP:
176    case VKEY_DOWN:
177    case VKEY_PRIOR:
178    case VKEY_NEXT:
179    case VKEY_HOME:
180    case VKEY_END:
181    case VKEY_TAB:
182        return true;
183    default:
184        return false;
185    }
186}
187
188bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&)
189{
190    return false;
191}
192
193bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&)
194{
195    return false;
196}
197
198static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
199{
200    // Check whether the event is a character-typed event or not.
201    // We use RawKeyDown/Char/KeyUp event scheme on all platforms,
202    // so PlatformKeyboardEvent::Char (not RawKeyDown) type event
203    // is considered as character type event.
204    return event.type() == PlatformEvent::Char;
205}
206
207bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
208{
209    if (event.type() == PlatformEvent::KeyUp)
210        return true;
211
212    if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
213        return true;
214
215    switch (event.windowsVirtualKeyCode()) {
216    case VKEY_ESCAPE:
217        abandon(); // may delete this
218        return true;
219    case VKEY_RETURN:
220        if (m_selectedIndex == -1)  {
221            hidePopup();
222            // Don't eat the enter if nothing is selected.
223            return false;
224        }
225        acceptIndex(m_selectedIndex); // may delete this
226        return true;
227    case VKEY_UP:
228        selectPreviousRow();
229        break;
230    case VKEY_DOWN:
231        selectNextRow();
232        break;
233    case VKEY_PRIOR:
234        adjustSelectedIndex(-m_visibleRows);
235        break;
236    case VKEY_NEXT:
237        adjustSelectedIndex(m_visibleRows);
238        break;
239    case VKEY_HOME:
240        adjustSelectedIndex(-m_selectedIndex);
241        break;
242    case VKEY_END:
243        adjustSelectedIndex(m_items.size());
244        break;
245    default:
246        if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
247            && isPrintableChar(event.windowsVirtualKeyCode())
248            && isCharacterTypeEvent(event))
249            typeAheadFind(event);
250        break;
251    }
252
253    if (event.altKey() && (event.keyIdentifier() == "Down" || event.keyIdentifier() == "Up")) {
254        hidePopup();
255        return true;
256    }
257
258    if (m_originalIndex != m_selectedIndex) {
259        // Keyboard events should update the selection immediately (but we don't
260        // want to fire the onchange event until the popup is closed, to match
261        // IE). We change the original index so we revert to that when the
262        // popup is closed.
263        m_acceptedIndexOnAbandon = m_selectedIndex;
264
265        setOriginalIndex(m_selectedIndex);
266        m_popupClient->setTextFromItem(m_selectedIndex);
267    }
268    if (event.windowsVirtualKeyCode() == VKEY_TAB) {
269        // TAB is a special case as it should select the current item if any and
270        // advance focus.
271        if (m_selectedIndex >= 0) {
272            acceptIndex(m_selectedIndex); // May delete us.
273            // Return false so the TAB key event is propagated to the page.
274            return false;
275        }
276        // Call abandon() so we honor m_acceptedIndexOnAbandon if set.
277        abandon();
278        // Return false so the TAB key event is propagated to the page.
279        return false;
280    }
281
282    return true;
283}
284
285HostWindow* PopupListBox::hostWindow() const
286{
287    // Our parent is the root ScrollView, so it is the one that has a
288    // HostWindow. FrameView::hostWindow() works similarly.
289    return parent() ? parent()->hostWindow() : 0;
290}
291
292bool PopupListBox::shouldPlaceVerticalScrollbarOnLeft() const
293{
294    return m_popupClient->menuStyle().textDirection() == RTL;
295}
296
297// From HTMLSelectElement.cpp
298static String stripLeadingWhiteSpace(const String& string)
299{
300    int length = string.length();
301    int i;
302    for (i = 0; i < length; ++i)
303        if (string[i] != noBreakSpace
304            && !isSpaceOrNewline(string[i]))
305            break;
306
307    return string.substring(i, length - i);
308}
309
310// From HTMLSelectElement.cpp, with modifications
311void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
312{
313    TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
314    TimeStamp delta = now - m_lastCharTime;
315
316    // Reset the time when user types in a character. The time gap between
317    // last character and the current character is used to indicate whether
318    // user typed in a string or just a character as the search prefix.
319    m_lastCharTime = now;
320
321    UChar c = event.windowsVirtualKeyCode();
322
323    String prefix;
324    int searchStartOffset = 1;
325    if (delta > typeAheadTimeoutMs) {
326        m_typedString = prefix = String(&c, 1);
327        m_repeatingChar = c;
328    } else {
329        m_typedString.append(c);
330
331        if (c == m_repeatingChar) {
332            // The user is likely trying to cycle through all the items starting
333            // with this character, so just search on the character.
334            prefix = String(&c, 1);
335        } else {
336            m_repeatingChar = 0;
337            prefix = m_typedString;
338            searchStartOffset = 0;
339        }
340    }
341
342    // Compute a case-folded copy of the prefix string before beginning the
343    // search for a matching element. This code uses foldCase to work around the
344    // fact that String::startWith does not fold non-ASCII characters. This code
345    // can be changed to use startWith once that is fixed.
346    String prefixWithCaseFolded(prefix.foldCase());
347    int itemCount = numItems();
348    int index = (max(0, m_selectedIndex) + searchStartOffset) % itemCount;
349    for (int i = 0; i < itemCount; i++, index = (index + 1) % itemCount) {
350        if (!isSelectableItem(index))
351            continue;
352
353        if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
354            selectIndex(index);
355            return;
356        }
357    }
358}
359
360void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
361{
362    // Adjust coords for scrolled frame.
363    IntRect r = intersection(rect, frameRect());
364    int tx = x() - scrollX() + ((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar()) ? verticalScrollbar()->width() : 0);
365    int ty = y() - scrollY();
366
367    r.move(-tx, -ty);
368
369    // Set clip rect to match revised damage rect.
370    gc->save();
371    gc->translate(static_cast<float>(tx), static_cast<float>(ty));
372    gc->clip(r);
373
374    // FIXME: Can we optimize scrolling to not require repainting the entire
375    // window? Should we?
376    for (int i = 0; i < numItems(); ++i)
377        paintRow(gc, r, i);
378
379    // Special case for an empty popup.
380    if (!numItems())
381        gc->fillRect(r, Color::white);
382
383    gc->restore();
384
385    if (m_verticalScrollbar) {
386        GraphicsContextStateSaver stateSaver(*gc);
387        IntRect scrollbarDirtyRect = rect;
388        IntRect visibleAreaWithScrollbars(location(), visibleContentRect(IncludeScrollbars).size());
389        scrollbarDirtyRect.intersect(visibleAreaWithScrollbars);
390        gc->translate(x(), y());
391        scrollbarDirtyRect.moveBy(-location());
392        gc->clip(IntRect(IntPoint(), visibleAreaWithScrollbars.size()));
393
394        m_verticalScrollbar->paint(gc, scrollbarDirtyRect);
395    }
396}
397
398static const int separatorPadding = 4;
399static const int separatorHeight = 1;
400static const int minRowHeight = 0;
401static const int optionRowHeightForTouch = 28;
402
403void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
404{
405    // This code is based largely on RenderListBox::paint* methods.
406
407    IntRect rowRect = getRowBounds(rowIndex);
408    if (!rowRect.intersects(rect))
409        return;
410
411    PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
412
413    // Paint background
414    Color backColor, textColor, labelColor;
415    if (rowIndex == m_selectedIndex) {
416        backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor();
417        textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor();
418        labelColor = textColor;
419    } else {
420        backColor = style.backgroundColor();
421        textColor = style.foregroundColor();
422#if OS(LINUX) || OS(ANDROID)
423        // On other platforms, the <option> background color is the same as the
424        // <select> background color. On Linux, that makes the <option>
425        // background color very dark, so by default, try to use a lighter
426        // background color for <option>s.
427        if (style.backgroundColorType() == PopupMenuStyle::DefaultBackgroundColor && RenderTheme::theme().systemColor(CSSValueButtonface) == backColor)
428            backColor = RenderTheme::theme().systemColor(CSSValueMenu);
429#endif
430
431        // FIXME: for now the label color is hard-coded. It should be added to
432        // the PopupMenuStyle.
433        labelColor = Color(115, 115, 115);
434    }
435
436    // If we have a transparent background, make sure it has a color to blend
437    // against.
438    if (backColor.hasAlpha())
439        gc->fillRect(rowRect, Color::white);
440
441    gc->fillRect(rowRect, backColor);
442
443    if (m_popupClient->itemIsSeparator(rowIndex)) {
444        IntRect separatorRect(
445            rowRect.x() + separatorPadding,
446            rowRect.y() + (rowRect.height() - separatorHeight) / 2,
447            rowRect.width() - 2 * separatorPadding, separatorHeight);
448        gc->fillRect(separatorRect, textColor);
449        return;
450    }
451
452    if (!style.isVisible())
453        return;
454
455    gc->setFillColor(textColor);
456
457    FontCachePurgePreventer fontCachePurgePreventer;
458
459    Font itemFont = getRowFont(rowIndex);
460    // FIXME: http://crbug.com/19872 We should get the padding of individual option
461    // elements. This probably implies changes to PopupMenuClient.
462    bool rightAligned = m_popupClient->menuStyle().textDirection() == RTL;
463    int textX = 0;
464    int maxWidth = 0;
465    if (rightAligned) {
466        maxWidth = rowRect.width() - max<int>(0, m_popupClient->clientPaddingRight());
467    } else {
468        textX = max<int>(0, m_popupClient->clientPaddingLeft());
469        maxWidth = rowRect.width() - textX;
470    }
471    // Prepare text to be drawn.
472    String itemText = m_popupClient->itemText(rowIndex);
473
474    // Prepare the directionality to draw text.
475    TextRun textRun(itemText, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
476    // If the text is right-to-left, make it right-aligned by adjusting its
477    // beginning position.
478    if (rightAligned)
479        textX += maxWidth - itemFont.width(textRun);
480
481    // Draw the item text.
482    int textY = rowRect.y() + itemFont.fontMetrics().ascent() + (rowRect.height() - itemFont.fontMetrics().height()) / 2;
483    TextRunPaintInfo textRunPaintInfo(textRun);
484    textRunPaintInfo.bounds = rowRect;
485    gc->drawBidiText(itemFont, textRunPaintInfo, IntPoint(textX, textY));
486}
487
488Font PopupListBox::getRowFont(int rowIndex) const
489{
490    Font itemFont = m_popupClient->itemStyle(rowIndex).font();
491    if (m_popupClient->itemIsLabel(rowIndex)) {
492        // Bold-ify labels (ie, an <optgroup> heading).
493        FontDescription d = itemFont.fontDescription();
494        d.setWeight(FontWeightBold);
495        Font font(d);
496        font.update(nullptr);
497        return font;
498    }
499
500    return itemFont;
501}
502
503void PopupListBox::abandon()
504{
505    RefPtr<PopupListBox> keepAlive(this);
506
507    m_selectedIndex = m_originalIndex;
508
509    hidePopup();
510
511    if (m_acceptedIndexOnAbandon >= 0) {
512        if (m_popupClient)
513            m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
514        m_acceptedIndexOnAbandon = -1;
515    }
516}
517
518int PopupListBox::pointToRowIndex(const IntPoint& point)
519{
520    int y = scrollY() + point.y();
521
522    // FIXME: binary search if perf matters.
523    for (int i = 0; i < numItems(); ++i) {
524        if (y < m_items[i]->yOffset)
525            return i-1;
526    }
527
528    // Last item?
529    if (y < contentsSize().height())
530        return m_items.size()-1;
531
532    return -1;
533}
534
535bool PopupListBox::acceptIndex(int index)
536{
537    // Clear m_acceptedIndexOnAbandon once user accepts the selected index.
538    if (m_acceptedIndexOnAbandon >= 0)
539        m_acceptedIndexOnAbandon = -1;
540
541    if (index >= numItems())
542        return false;
543
544    if (index < 0) {
545        if (m_popupClient) {
546            // Enter pressed with no selection, just close the popup.
547            hidePopup();
548        }
549        return false;
550    }
551
552    if (isSelectableItem(index)) {
553        RefPtr<PopupListBox> keepAlive(this);
554
555        // Hide ourselves first since valueChanged may have numerous side-effects.
556        hidePopup();
557
558        // Tell the <select> PopupMenuClient what index was selected.
559        m_popupClient->valueChanged(index);
560
561        return true;
562    }
563
564    return false;
565}
566
567void PopupListBox::selectIndex(int index)
568{
569    if (index < 0 || index >= numItems())
570        return;
571
572    bool isSelectable = isSelectableItem(index);
573    if (index != m_selectedIndex && isSelectable) {
574        invalidateRow(m_selectedIndex);
575        m_selectedIndex = index;
576        invalidateRow(m_selectedIndex);
577
578        scrollToRevealSelection();
579        m_popupClient->selectionChanged(m_selectedIndex);
580    } else if (!isSelectable)
581        clearSelection();
582}
583
584void PopupListBox::setOriginalIndex(int index)
585{
586    m_originalIndex = m_selectedIndex = index;
587}
588
589int PopupListBox::getRowHeight(int index) const
590{
591    int minimumHeight = m_deviceSupportsTouch ? optionRowHeightForTouch : minRowHeight;
592
593    if (index < 0 || m_popupClient->itemStyle(index).isDisplayNone())
594        return minimumHeight;
595
596    // Separator row height is the same size as itself.
597    if (m_popupClient->itemIsSeparator(index))
598        return max(separatorHeight, minimumHeight);
599
600    int fontHeight = getRowFont(index).fontMetrics().height();
601    return max(fontHeight, minimumHeight);
602}
603
604IntRect PopupListBox::getRowBounds(int index)
605{
606    if (index < 0)
607        return IntRect(0, 0, visibleWidth(), getRowHeight(index));
608
609    return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
610}
611
612void PopupListBox::invalidateRow(int index)
613{
614    if (index < 0)
615        return;
616
617    // Invalidate in the window contents, as invalidateRect paints in the window coordinates.
618    IntRect clipRect = contentsToWindow(getRowBounds(index));
619    if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar())
620        clipRect.move(verticalScrollbar()->width(), 0);
621    invalidateRect(clipRect);
622}
623
624void PopupListBox::scrollToRevealRow(int index)
625{
626    if (index < 0)
627        return;
628
629    IntRect rowRect = getRowBounds(index);
630
631    if (rowRect.y() < scrollY()) {
632        // Row is above current scroll position, scroll up.
633        updateScrollbars(IntPoint(0, rowRect.y()));
634    } else if (rowRect.maxY() > scrollY() + visibleHeight()) {
635        // Row is below current scroll position, scroll down.
636        updateScrollbars(IntPoint(0, rowRect.maxY() - visibleHeight()));
637    }
638}
639
640bool PopupListBox::isSelectableItem(int index)
641{
642    ASSERT(index >= 0 && index < numItems());
643    return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
644}
645
646void PopupListBox::clearSelection()
647{
648    if (m_selectedIndex != -1) {
649        invalidateRow(m_selectedIndex);
650        m_selectedIndex = -1;
651        m_popupClient->selectionCleared();
652    }
653}
654
655void PopupListBox::selectNextRow()
656{
657    adjustSelectedIndex(1);
658}
659
660void PopupListBox::selectPreviousRow()
661{
662    adjustSelectedIndex(-1);
663}
664
665void PopupListBox::adjustSelectedIndex(int delta)
666{
667    int targetIndex = m_selectedIndex + delta;
668    targetIndex = std::min(std::max(targetIndex, 0), numItems() - 1);
669    if (!isSelectableItem(targetIndex)) {
670        // We didn't land on an option. Try to find one.
671        // We try to select the closest index to target, prioritizing any in
672        // the range [current, target].
673
674        int dir = delta > 0 ? 1 : -1;
675        int testIndex = m_selectedIndex;
676        int bestIndex = m_selectedIndex;
677        bool passedTarget = false;
678        while (testIndex >= 0 && testIndex < numItems()) {
679            if (isSelectableItem(testIndex))
680                bestIndex = testIndex;
681            if (testIndex == targetIndex)
682                passedTarget = true;
683            if (passedTarget && bestIndex != m_selectedIndex)
684                break;
685
686            testIndex += dir;
687        }
688
689        // Pick the best index, which may mean we don't change.
690        targetIndex = bestIndex;
691    }
692
693    // Select the new index, and ensure its visible. We do this regardless of
694    // whether the selection changed to ensure keyboard events always bring the
695    // selection into view.
696    selectIndex(targetIndex);
697    scrollToRevealSelection();
698}
699
700void PopupListBox::hidePopup()
701{
702    if (parent()) {
703        if (m_container->client())
704            m_container->client()->popupClosed(m_container);
705        m_container->notifyPopupHidden();
706    }
707
708    if (m_popupClient)
709        m_popupClient->popupDidHide();
710}
711
712void PopupListBox::updateFromElement()
713{
714    clear();
715
716    int size = m_popupClient->listSize();
717    for (int i = 0; i < size; ++i) {
718        PopupItem::Type type;
719        if (m_popupClient->itemIsSeparator(i))
720            type = PopupItem::TypeSeparator;
721        else if (m_popupClient->itemIsLabel(i))
722            type = PopupItem::TypeGroup;
723        else
724            type = PopupItem::TypeOption;
725        m_items.append(new PopupItem(m_popupClient->itemText(i), type));
726        m_items[i]->enabled = isSelectableItem(i);
727        PopupMenuStyle style = m_popupClient->itemStyle(i);
728        m_items[i]->textDirection = style.textDirection();
729        m_items[i]->hasTextDirectionOverride = style.hasTextDirectionOverride();
730        m_items[i]->displayNone = style.isDisplayNone();
731    }
732
733    m_selectedIndex = m_popupClient->selectedIndex();
734    setOriginalIndex(m_selectedIndex);
735
736    layout();
737}
738
739void PopupListBox::setMaxWidthAndLayout(int maxWidth)
740{
741    m_maxWindowWidth = maxWidth;
742    layout();
743}
744
745int PopupListBox::getRowBaseWidth(int index)
746{
747    Font font = getRowFont(index);
748    PopupMenuStyle style = m_popupClient->itemStyle(index);
749    String text = m_popupClient->itemText(index);
750    if (text.isEmpty())
751        return 0;
752    TextRun textRun(text, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
753    return font.width(textRun);
754}
755
756void PopupListBox::layout()
757{
758    bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
759
760    // Size our child items.
761    int baseWidth = 0;
762    int paddingWidth = 0;
763    int lineEndPaddingWidth = 0;
764    int y = 0;
765    for (int i = 0; i < numItems(); ++i) {
766        // Place the item vertically.
767        m_items[i]->yOffset = y;
768        if (m_popupClient->itemStyle(i).isDisplayNone())
769            continue;
770        y += getRowHeight(i);
771
772        // Ensure the popup is wide enough to fit this item.
773        baseWidth = max(baseWidth, getRowBaseWidth(i));
774        // FIXME: http://b/1210481 We should get the padding of individual
775        // option elements.
776        paddingWidth = max<int>(paddingWidth,
777            m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight());
778        lineEndPaddingWidth = max<int>(lineEndPaddingWidth,
779            isRightAligned ? m_popupClient->clientPaddingLeft() : m_popupClient->clientPaddingRight());
780    }
781
782    // Calculate scroll bar width.
783    int windowHeight = 0;
784    m_visibleRows = std::min(numItems(), maxVisibleRows);
785
786    for (int i = 0; i < m_visibleRows; ++i) {
787        int rowHeight = getRowHeight(i);
788
789        // Only clip the window height for non-Mac platforms.
790        if (windowHeight + rowHeight > m_maxHeight) {
791            m_visibleRows = i;
792            break;
793        }
794
795        windowHeight += rowHeight;
796    }
797
798    // Set our widget and scrollable contents sizes.
799    int scrollbarWidth = 0;
800    if (m_visibleRows < numItems()) {
801        if (!ScrollbarTheme::theme()->usesOverlayScrollbars())
802            scrollbarWidth = ScrollbarTheme::theme()->scrollbarThickness();
803
804        // Use minEndOfLinePadding when there is a scrollbar so that we use
805        // as much as (lineEndPaddingWidth - minEndOfLinePadding) padding
806        // space for scrollbar and allow user to use CSS padding to make the
807        // popup listbox align with the select element.
808        paddingWidth = paddingWidth - lineEndPaddingWidth + minEndOfLinePadding;
809    }
810
811    int windowWidth = baseWidth + scrollbarWidth + paddingWidth;
812    if (windowWidth > m_maxWindowWidth) {
813        // windowWidth exceeds m_maxWindowWidth, so we have to clip.
814        windowWidth = m_maxWindowWidth;
815        baseWidth = windowWidth - scrollbarWidth - paddingWidth;
816        m_baseWidth = baseWidth;
817    }
818    int contentWidth = windowWidth - scrollbarWidth;
819
820    if (windowWidth < m_baseWidth) {
821        windowWidth = m_baseWidth;
822        contentWidth = m_baseWidth - scrollbarWidth;
823    } else {
824        m_baseWidth = baseWidth;
825    }
826
827    resize(windowWidth, windowHeight);
828    setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
829
830    if (hostWindow())
831        scrollToRevealSelection();
832
833    invalidate();
834}
835
836void PopupListBox::clear()
837{
838    for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it)
839        delete *it;
840    m_items.clear();
841}
842
843bool PopupListBox::isPointInBounds(const IntPoint& point)
844{
845    return numItems() && IntRect(0, 0, width(), height()).contains(point);
846}
847
848int PopupListBox::popupContentHeight() const
849{
850    return height();
851}
852
853void PopupListBox::invalidateRect(const IntRect& rect)
854{
855    if (HostWindow* h = hostWindow())
856        h->invalidateContentsAndRootView(rect);
857}
858
859IntRect PopupListBox::windowClipRect() const
860{
861    IntRect clipRect = visibleContentRect();
862    if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar())
863        clipRect.move(verticalScrollbar()->width(), 0);
864    return contentsToWindow(clipRect);
865}
866
867void PopupListBox::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
868{
869    // Add in our offset within the ScrollView.
870    IntRect dirtyRect = rect;
871    dirtyRect.move(scrollbar->x(), scrollbar->y());
872    invalidateRect(dirtyRect);
873}
874
875bool PopupListBox::isActive() const
876{
877    // FIXME
878    return true;
879}
880
881bool PopupListBox::scrollbarsCanBeActive() const
882{
883    return isActive();
884}
885
886IntRect PopupListBox::scrollableAreaBoundingBox() const
887{
888    return windowClipRect();
889}
890
891// FIXME: The following methods are based on code in ScrollView, with
892// simplifications for the constraints of PopupListBox (e.g. only vertical
893// scrollbar, not horizontal). This functionality should be moved into
894// ScrollableArea after http://crbug.com/417782 is fixed.
895
896void PopupListBox::setHasVerticalScrollbar(bool hasBar)
897{
898    if (hasBar && !m_verticalScrollbar) {
899        m_verticalScrollbar = Scrollbar::create(this, VerticalScrollbar, RegularScrollbar);
900        m_verticalScrollbar->setParent(this);
901        didAddScrollbar(m_verticalScrollbar.get(), VerticalScrollbar);
902        m_verticalScrollbar->styleChanged();
903    } else if (!hasBar && m_verticalScrollbar) {
904        m_verticalScrollbar->setParent(0);
905        willRemoveScrollbar(m_verticalScrollbar.get(), VerticalScrollbar);
906        m_verticalScrollbar = nullptr;
907    }
908}
909
910Scrollbar* PopupListBox::scrollbarAtWindowPoint(const IntPoint& windowPoint)
911{
912    return m_verticalScrollbar && m_verticalScrollbar->frameRect().contains(
913        convertFromContainingWindow(windowPoint)) ? m_verticalScrollbar.get() : 0;
914}
915
916IntRect PopupListBox::contentsToWindow(const IntRect& contentsRect) const
917{
918    IntRect viewRect = contentsRect;
919    viewRect.moveBy(-scrollPosition());
920    return convertToContainingWindow(viewRect);
921}
922
923void PopupListBox::setContentsSize(const IntSize& newSize)
924{
925    if (contentsSize() == newSize)
926        return;
927    m_contentsSize = newSize;
928    updateScrollbars(scrollPosition());
929}
930
931void PopupListBox::setFrameRect(const IntRect& newRect)
932{
933    IntRect oldRect = frameRect();
934    if (newRect == oldRect)
935        return;
936
937    Widget::setFrameRect(newRect);
938    updateScrollbars(scrollPosition());
939    // NOTE: We do not need to call m_verticalScrollbar->frameRectsChanged as
940    // Scrollbar does not implement it.
941}
942
943IntRect PopupListBox::visibleContentRect(IncludeScrollbarsInRect scrollbarInclusion) const
944{
945    // NOTE: Unlike ScrollView we do not need to incorporate any scaling factor,
946    // and there is only one scrollbar to exclude.
947    IntSize size = frameRect().size();
948    Scrollbar* verticalBar = verticalScrollbar();
949    if (scrollbarInclusion == ExcludeScrollbars && verticalBar && !verticalBar->isOverlayScrollbar()) {
950        size.setWidth(std::max(0, size.width() - verticalBar->width()));
951    }
952    return IntRect(m_scrollOffset, size);
953}
954
955void PopupListBox::updateScrollbars(IntPoint desiredOffset)
956{
957    IntSize oldVisibleSize = visibleContentRect().size();
958    adjustScrollbarExistence();
959    updateScrollbarGeometry();
960    IntSize newVisibleSize = visibleContentRect().size();
961
962    if (newVisibleSize.width() > oldVisibleSize.width()) {
963        if (shouldPlaceVerticalScrollbarOnLeft())
964            invalidateRect(IntRect(0, 0, newVisibleSize.width() - oldVisibleSize.width(), newVisibleSize.height()));
965        else
966            invalidateRect(IntRect(oldVisibleSize.width(), 0, newVisibleSize.width() - oldVisibleSize.width(), newVisibleSize.height()));
967    }
968
969    desiredOffset = desiredOffset.shrunkTo(maximumScrollPosition());
970    desiredOffset = desiredOffset.expandedTo(minimumScrollPosition());
971
972    if (desiredOffset != scrollPosition())
973        ScrollableArea::scrollToOffsetWithoutAnimation(desiredOffset);
974}
975
976void PopupListBox::adjustScrollbarExistence()
977{
978    bool needsVerticalScrollbar = contentsSize().height() > visibleHeight();
979    if (!!m_verticalScrollbar != needsVerticalScrollbar) {
980        setHasVerticalScrollbar(needsVerticalScrollbar);
981        contentsResized();
982    }
983}
984
985void PopupListBox::updateScrollbarGeometry()
986{
987    if (m_verticalScrollbar) {
988        int clientHeight = visibleHeight();
989        IntRect oldRect(m_verticalScrollbar->frameRect());
990        IntRect vBarRect(shouldPlaceVerticalScrollbarOnLeft() ? 0 : (width() - m_verticalScrollbar->width()),
991            0, m_verticalScrollbar->width(), height());
992        m_verticalScrollbar->setFrameRect(vBarRect);
993        if (oldRect != m_verticalScrollbar->frameRect())
994            m_verticalScrollbar->invalidate();
995
996        m_verticalScrollbar->setEnabled(contentsSize().height() > clientHeight);
997        m_verticalScrollbar->setProportion(clientHeight, contentsSize().height());
998        m_verticalScrollbar->offsetDidChange();
999        // NOTE: PopupListBox does not support suppressing scrollbars.
1000    }
1001}
1002
1003IntPoint PopupListBox::convertChildToSelf(const Widget* child, const IntPoint& point) const
1004{
1005    // NOTE: m_verticalScrollbar is the only child.
1006    IntPoint newPoint = point;
1007    newPoint.moveBy(child->location());
1008    return newPoint;
1009}
1010
1011IntPoint PopupListBox::convertSelfToChild(const Widget* child, const IntPoint& point) const
1012{
1013    // NOTE: m_verticalScrollbar is the only child.
1014    IntPoint newPoint = point;
1015    newPoint.moveBy(-child->location());
1016    return newPoint;
1017}
1018
1019int PopupListBox::scrollSize(ScrollbarOrientation orientation) const
1020{
1021    return (orientation == HorizontalScrollbar || !m_verticalScrollbar) ?
1022        0 : m_verticalScrollbar->totalSize() - m_verticalScrollbar->visibleSize();
1023}
1024
1025void PopupListBox::setScrollOffset(const IntPoint& newOffset)
1026{
1027    // NOTE: We do not support any "fast path" for scrolling. When the scroll
1028    // offset changes, we just repaint the whole popup.
1029    IntSize scrollDelta = newOffset - m_scrollOffset;
1030    if (scrollDelta == IntSize())
1031        return;
1032    m_scrollOffset = newOffset;
1033
1034    if (HostWindow* window = hostWindow()) {
1035        IntRect clipRect = windowClipRect();
1036        IntRect updateRect = clipRect;
1037        updateRect.intersect(convertToContainingWindow(IntRect((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) ? verticalScrollbar()->width() : 0, 0, visibleWidth(), visibleHeight())));
1038        window->invalidateContentsForSlowScroll(updateRect);
1039    }
1040}
1041
1042IntPoint PopupListBox::maximumScrollPosition() const
1043{
1044    IntPoint maximumOffset(contentsSize().width() - visibleWidth() - scrollOrigin().x(), contentsSize().height() - visibleHeight() - scrollOrigin().y());
1045    maximumOffset.clampNegativeToZero();
1046    return maximumOffset;
1047}
1048
1049IntPoint PopupListBox::minimumScrollPosition() const
1050{
1051    return IntPoint(-scrollOrigin().x(), -scrollOrigin().y());
1052}
1053
1054} // namespace blink
1055