2 * Copyright (c) 2011, Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
32 #include "web/PopupListBox.h"
34 #include "CSSValueKeywords.h"
35 #include "RuntimeEnabledFeatures.h"
36 #include "core/rendering/RenderTheme.h"
37 #include "platform/KeyboardCodes.h"
38 #include "platform/PlatformGestureEvent.h"
39 #include "platform/PlatformKeyboardEvent.h"
40 #include "platform/PlatformMouseEvent.h"
41 #include "platform/PlatformScreen.h"
42 #include "platform/PlatformTouchEvent.h"
43 #include "platform/PlatformWheelEvent.h"
44 #include "platform/PopupMenuClient.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"
62 using namespace WTF::Unicode;
63 using namespace WebCore;
65 const int PopupListBox::defaultMaxHeight = 500;
66 static const int maxVisibleRows = 20;
67 static const int minEndOfLinePadding = 2;
68 static const TimeStamp typeAheadTimeoutMs = 1000;
70 PopupListBox::PopupListBox(PopupMenuClient* client, bool deviceSupportsTouch)
71 : m_deviceSupportsTouch(deviceSupportsTouch)
74 , m_acceptedIndexOnAbandon(-1)
77 , m_maxHeight(defaultMaxHeight)
78 , m_popupClient(client)
81 , m_maxWindowWidth(std::numeric_limits<int>::max())
83 setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
86 bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
88 Scrollbar* scrollbar = scrollbarAtPoint(event.position());
90 m_capturingScrollbar = scrollbar;
91 m_capturingScrollbar->mouseDown(event);
95 if (!isPointInBounds(event.position()))
101 bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
103 if (m_capturingScrollbar) {
104 m_capturingScrollbar->mouseMoved(event);
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;
117 scrollbar->mouseMoved(event);
121 if (!isPointInBounds(event.position()))
124 selectIndex(pointToRowIndex(event.position()));
128 bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
130 if (m_capturingScrollbar) {
131 m_capturingScrollbar->mouseUp(event);
132 m_capturingScrollbar = nullptr;
136 if (!isPointInBounds(event.position()))
139 if (acceptIndex(pointToRowIndex(event.position())) && m_focusedElement) {
140 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::mouseup);
141 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::click);
143 // Clear m_focusedElement here, because we cannot clear in hidePopup()
144 // which is called before dispatchMouseEvent() is called.
145 m_focusedElement = nullptr;
151 bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
153 if (!isPointInBounds(event.position())) {
158 ScrollableArea::handleWheelEvent(event);
162 // Should be kept in sync with handleKeyEvent().
163 bool PopupListBox::isInterestedInEventForKey(int keyCode)
181 bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&)
186 bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&)
191 static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
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;
200 bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
202 if (event.type() == PlatformEvent::KeyUp)
205 if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
208 switch (event.windowsVirtualKeyCode()) {
210 abandon(); // may delete this
213 if (m_selectedIndex == -1) {
215 // Don't eat the enter if nothing is selected.
218 acceptIndex(m_selectedIndex); // may delete this
227 adjustSelectedIndex(-m_visibleRows);
230 adjustSelectedIndex(m_visibleRows);
233 adjustSelectedIndex(-m_selectedIndex);
236 adjustSelectedIndex(m_items.size());
239 if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
240 && isPrintableChar(event.windowsVirtualKeyCode())
241 && isCharacterTypeEvent(event))
242 typeAheadFind(event);
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
251 m_acceptedIndexOnAbandon = m_selectedIndex;
253 setOriginalIndex(m_selectedIndex);
254 m_popupClient->setTextFromItem(m_selectedIndex);
256 if (event.windowsVirtualKeyCode() == VKEY_TAB) {
257 // TAB is a special case as it should select the current item if any and
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.
264 // Call abandon() so we honor m_acceptedIndexOnAbandon if set.
266 // Return false so the TAB key event is propagated to the page.
273 HostWindow* PopupListBox::hostWindow() const
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;
280 bool PopupListBox::shouldPlaceVerticalScrollbarOnLeft() const
282 return m_popupClient->menuStyle().textDirection() == RTL;
285 // From HTMLSelectElement.cpp
286 static String stripLeadingWhiteSpace(const String& string)
288 int length = string.length();
290 for (i = 0; i < length; ++i)
291 if (string[i] != noBreakSpace
292 && !isSpaceOrNewline(string[i]))
295 return string.substring(i, length - i);
298 // From HTMLSelectElement.cpp, with modifications
299 void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
301 TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
302 TimeStamp delta = now - m_lastCharTime;
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;
309 UChar c = event.windowsVirtualKeyCode();
312 int searchStartOffset = 1;
313 if (delta > typeAheadTimeoutMs) {
314 m_typedString = prefix = String(&c, 1);
317 m_typedString.append(c);
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);
325 prefix = m_typedString;
326 searchStartOffset = 0;
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))
341 if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
348 void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
350 // Adjust coords for scrolled frame.
351 IntRect r = intersection(rect, frameRect());
352 int tx = x() - scrollX() + ((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) ? verticalScrollbar()->width() : 0);
353 int ty = y() - scrollY();
357 // Set clip rect to match revised damage rect.
359 gc->translate(static_cast<float>(tx), static_cast<float>(ty));
362 // FIXME: Can we optimize scrolling to not require repainting the entire
363 // window? Should we?
364 for (int i = 0; i < numItems(); ++i)
367 // Special case for an empty popup.
369 gc->fillRect(r, Color::white);
373 ScrollView::paint(gc, rect);
376 static const int separatorPadding = 4;
377 static const int separatorHeight = 1;
378 static const int minRowHeight = 0;
379 static const int optionRowHeightForTouch = 28;
381 void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
383 // This code is based largely on RenderListBox::paint* methods.
385 IntRect rowRect = getRowBounds(rowIndex);
386 if (!rowRect.intersects(rect))
389 PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
392 Color backColor, textColor, labelColor;
393 if (rowIndex == m_selectedIndex) {
394 backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor();
395 textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor();
396 labelColor = textColor;
398 backColor = style.backgroundColor();
399 textColor = style.foregroundColor();
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);
410 // FIXME: for now the label color is hard-coded. It should be added to
411 // the PopupMenuStyle.
412 labelColor = Color(115, 115, 115);
415 // If we have a transparent background, make sure it has a color to blend
417 if (backColor.hasAlpha())
418 gc->fillRect(rowRect, Color::white);
420 gc->fillRect(rowRect, backColor);
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);
431 if (!style.isVisible())
434 gc->setFillColor(textColor);
436 FontCachePurgePreventer fontCachePurgePreventer;
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;
445 maxWidth = rowRect.width() - max<int>(0, m_popupClient->clientPaddingRight());
447 textX = max<int>(0, m_popupClient->clientPaddingLeft());
448 maxWidth = rowRect.width() - textX;
450 // Prepare text to be drawn.
451 String itemText = m_popupClient->itemText(rowIndex);
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.
458 textX += maxWidth - itemFont.width(textRun);
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));
467 Font PopupListBox::getRowFont(int rowIndex)
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);
475 font.update(nullptr);
482 void PopupListBox::abandon()
484 RefPtr<PopupListBox> keepAlive(this);
486 m_selectedIndex = m_originalIndex;
490 if (m_acceptedIndexOnAbandon >= 0) {
492 m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
493 m_acceptedIndexOnAbandon = -1;
497 int PopupListBox::pointToRowIndex(const IntPoint& point)
499 int y = scrollY() + point.y();
501 // FIXME: binary search if perf matters.
502 for (int i = 0; i < numItems(); ++i) {
503 if (y < m_items[i]->yOffset)
508 if (y < contentsHeight())
509 return m_items.size()-1;
514 bool PopupListBox::acceptIndex(int index)
516 // Clear m_acceptedIndexOnAbandon once user accepts the selected index.
517 if (m_acceptedIndexOnAbandon >= 0)
518 m_acceptedIndexOnAbandon = -1;
520 if (index >= numItems())
525 // Enter pressed with no selection, just close the popup.
531 if (isSelectableItem(index)) {
532 RefPtr<PopupListBox> keepAlive(this);
534 // Hide ourselves first since valueChanged may have numerous side-effects.
537 // Tell the <select> PopupMenuClient what index was selected.
538 m_popupClient->valueChanged(index);
546 void PopupListBox::selectIndex(int index)
548 if (index < 0 || index >= numItems())
551 bool isSelectable = isSelectableItem(index);
552 if (index != m_selectedIndex && isSelectable) {
553 invalidateRow(m_selectedIndex);
554 m_selectedIndex = index;
555 invalidateRow(m_selectedIndex);
557 scrollToRevealSelection();
558 m_popupClient->selectionChanged(m_selectedIndex);
559 } else if (!isSelectable)
563 void PopupListBox::setOriginalIndex(int index)
565 m_originalIndex = m_selectedIndex = index;
568 int PopupListBox::getRowHeight(int index)
570 int minimumHeight = m_deviceSupportsTouch ? optionRowHeightForTouch : minRowHeight;
572 if (index < 0 || m_popupClient->itemStyle(index).isDisplayNone())
573 return minimumHeight;
575 // Separator row height is the same size as itself.
576 if (m_popupClient->itemIsSeparator(index))
577 return max(separatorHeight, minimumHeight);
579 int fontHeight = getRowFont(index).fontMetrics().height();
580 return max(fontHeight, minimumHeight);
583 IntRect PopupListBox::getRowBounds(int index)
586 return IntRect(0, 0, visibleWidth(), getRowHeight(index));
588 return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
591 void PopupListBox::invalidateRow(int index)
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())
600 clipRect.move(verticalScrollbar()->width(), 0);
601 invalidateRect(clipRect);
604 void PopupListBox::scrollToRevealRow(int index)
609 IntRect rowRect = getRowBounds(index);
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()));
620 bool PopupListBox::isSelectableItem(int index)
622 ASSERT(index >= 0 && index < numItems());
623 return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
626 void PopupListBox::clearSelection()
628 if (m_selectedIndex != -1) {
629 invalidateRow(m_selectedIndex);
630 m_selectedIndex = -1;
631 m_popupClient->selectionCleared();
635 void PopupListBox::selectNextRow()
637 adjustSelectedIndex(1);
640 void PopupListBox::selectPreviousRow()
642 adjustSelectedIndex(-1);
645 void PopupListBox::adjustSelectedIndex(int delta)
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].
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)
663 if (passedTarget && bestIndex != m_selectedIndex)
669 // Pick the best index, which may mean we don't change.
670 targetIndex = bestIndex;
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();
680 void PopupListBox::hidePopup()
683 PopupContainer* container = static_cast<PopupContainer*>(parent());
684 if (container->client())
685 container->client()->popupClosed(container);
686 container->notifyPopupHidden();
690 m_popupClient->popupDidHide();
693 void PopupListBox::updateFromElement()
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;
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();
713 m_selectedIndex = m_popupClient->selectedIndex();
714 setOriginalIndex(m_selectedIndex);
719 void PopupListBox::setMaxWidthAndLayout(int maxWidth)
721 m_maxWindowWidth = maxWidth;
725 void PopupListBox::layout()
727 bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
729 // Size our child items.
731 int paddingWidth = 0;
732 int lineEndPaddingWidth = 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())
739 y += getRowHeight(i);
741 // Ensure the popup is wide enough to fit this item.
742 Font itemFont = getRowFont(i);
743 String text = m_popupClient->itemText(i);
746 width = itemFont.width(TextRun(text));
748 baseWidth = max(baseWidth, width);
749 // FIXME: http://b/1210481 We should get the padding of individual
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());
757 // Calculate scroll bar width.
758 int windowHeight = 0;
759 m_visibleRows = std::min(numItems(), maxVisibleRows);
761 for (int i = 0; i < m_visibleRows; ++i) {
762 int rowHeight = getRowHeight(i);
764 // Only clip the window height for non-Mac platforms.
765 if (windowHeight + rowHeight > m_maxHeight) {
770 windowHeight += rowHeight;
773 // Set our widget and scrollable contents sizes.
774 int scrollbarWidth = 0;
775 if (m_visibleRows < numItems()) {
776 scrollbarWidth = ScrollbarTheme::theme()->scrollbarThickness();
778 // Use minEndOfLinePadding when there is a scrollbar so that we use
779 // as much as (lineEndPaddingWidth - minEndOfLinePadding) padding
780 // space for scrollbar and allow user to use CSS padding to make the
781 // popup listbox align with the select element.
782 paddingWidth = paddingWidth - lineEndPaddingWidth + minEndOfLinePadding;
785 int windowWidth = baseWidth + scrollbarWidth + paddingWidth;
786 if (windowWidth > m_maxWindowWidth) {
787 // windowWidth exceeds m_maxWindowWidth, so we have to clip.
788 windowWidth = m_maxWindowWidth;
789 baseWidth = windowWidth - scrollbarWidth - paddingWidth;
790 m_baseWidth = baseWidth;
792 int contentWidth = windowWidth - scrollbarWidth;
794 if (windowWidth < m_baseWidth) {
795 windowWidth = m_baseWidth;
796 contentWidth = m_baseWidth - scrollbarWidth;
798 m_baseWidth = baseWidth;
801 resize(windowWidth, windowHeight);
802 setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
805 scrollToRevealSelection();
810 void PopupListBox::clear()
812 for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it)
817 bool PopupListBox::isPointInBounds(const IntPoint& point)
819 return numItems() && IntRect(0, 0, width(), height()).contains(point);
822 int PopupListBox::popupContentHeight() const