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 "PopupListBox.h"
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"
62 using namespace WTF::Unicode;
64 const int PopupListBox::defaultMaxHeight = 500;
65 static const int maxVisibleRows = 20;
66 static const int minEndOfLinePadding = 2;
67 static const TimeStamp typeAheadTimeoutMs = 1000;
69 PopupListBox::PopupListBox(PopupMenuClient* client, bool deviceSupportsTouch)
70 : m_deviceSupportsTouch(deviceSupportsTouch)
73 , m_acceptedIndexOnAbandon(-1)
76 , m_maxHeight(defaultMaxHeight)
77 , m_popupClient(client)
80 , m_maxWindowWidth(std::numeric_limits<int>::max())
82 setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
85 bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
87 Scrollbar* scrollbar = scrollbarAtPoint(event.position());
89 m_capturingScrollbar = scrollbar;
90 m_capturingScrollbar->mouseDown(event);
94 if (!isPointInBounds(event.position()))
100 bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
102 if (m_capturingScrollbar) {
103 m_capturingScrollbar->mouseMoved(event);
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;
116 scrollbar->mouseMoved(event);
120 if (!isPointInBounds(event.position()))
123 selectIndex(pointToRowIndex(event.position()));
127 bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
129 if (m_capturingScrollbar) {
130 m_capturingScrollbar->mouseUp(event);
131 m_capturingScrollbar = 0;
135 if (!isPointInBounds(event.position()))
138 if (acceptIndex(pointToRowIndex(event.position())) && m_focusedElement) {
139 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::mouseup);
140 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::click);
142 // Clear m_focusedElement here, because we cannot clear in hidePopup()
143 // which is called before dispatchMouseEvent() is called.
144 m_focusedElement = 0;
150 bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
152 if (!isPointInBounds(event.position())) {
157 ScrollableArea::handleWheelEvent(event);
161 // Should be kept in sync with handleKeyEvent().
162 bool PopupListBox::isInterestedInEventForKey(int keyCode)
180 bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&)
185 bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&)
190 static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
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;
199 bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
201 if (event.type() == PlatformEvent::KeyUp)
204 if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
207 switch (event.windowsVirtualKeyCode()) {
209 abandon(); // may delete this
212 if (m_selectedIndex == -1) {
214 // Don't eat the enter if nothing is selected.
217 acceptIndex(m_selectedIndex); // may delete this
226 adjustSelectedIndex(-m_visibleRows);
229 adjustSelectedIndex(m_visibleRows);
232 adjustSelectedIndex(-m_selectedIndex);
235 adjustSelectedIndex(m_items.size());
238 if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
239 && isPrintableChar(event.windowsVirtualKeyCode())
240 && isCharacterTypeEvent(event))
241 typeAheadFind(event);
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
250 m_acceptedIndexOnAbandon = m_selectedIndex;
252 setOriginalIndex(m_selectedIndex);
253 m_popupClient->setTextFromItem(m_selectedIndex);
255 if (event.windowsVirtualKeyCode() == VKEY_TAB) {
256 // TAB is a special case as it should select the current item if any and
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.
263 // Call abandon() so we honor m_acceptedIndexOnAbandon if set.
265 // Return false so the TAB key event is propagated to the page.
272 HostWindow* PopupListBox::hostWindow() const
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;
279 bool PopupListBox::shouldPlaceVerticalScrollbarOnLeft() const
281 return m_popupClient->menuStyle().textDirection() == RTL;
284 // From HTMLSelectElement.cpp
285 static String stripLeadingWhiteSpace(const String& string)
287 int length = string.length();
289 for (i = 0; i < length; ++i)
290 if (string[i] != noBreakSpace
291 && !isSpaceOrNewline(string[i]))
294 return string.substring(i, length - i);
297 // From HTMLSelectElement.cpp, with modifications
298 void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
300 TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
301 TimeStamp delta = now - m_lastCharTime;
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;
308 UChar c = event.windowsVirtualKeyCode();
311 int searchStartOffset = 1;
312 if (delta > typeAheadTimeoutMs) {
313 m_typedString = prefix = String(&c, 1);
316 m_typedString.append(c);
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);
324 prefix = m_typedString;
325 searchStartOffset = 0;
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))
340 if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
347 void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
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();
356 // Set clip rect to match revised damage rect.
358 gc->translate(static_cast<float>(tx), static_cast<float>(ty));
361 // FIXME: Can we optimize scrolling to not require repainting the entire
362 // window? Should we?
363 for (int i = 0; i < numItems(); ++i)
366 // Special case for an empty popup.
368 gc->fillRect(r, Color::white);
372 ScrollView::paint(gc, rect);
375 static const int separatorPadding = 4;
376 static const int separatorHeight = 1;
378 void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
380 // This code is based largely on RenderListBox::paint* methods.
382 IntRect rowRect = getRowBounds(rowIndex);
383 if (!rowRect.intersects(rect))
386 PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
389 Color backColor, textColor, labelColor;
390 if (rowIndex == m_selectedIndex) {
391 backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor();
392 textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor();
393 labelColor = textColor;
395 backColor = style.backgroundColor();
396 textColor = style.foregroundColor();
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);
407 // FIXME: for now the label color is hard-coded. It should be added to
408 // the PopupMenuStyle.
409 labelColor = Color(115, 115, 115);
412 // If we have a transparent background, make sure it has a color to blend
414 if (backColor.hasAlpha())
415 gc->fillRect(rowRect, Color::white);
417 gc->fillRect(rowRect, backColor);
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);
428 if (!style.isVisible())
431 gc->setFillColor(textColor);
433 FontCachePurgePreventer fontCachePurgePreventer;
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;
442 maxWidth = rowRect.width() - max<int>(0, m_popupClient->clientPaddingRight());
444 textX = max<int>(0, m_popupClient->clientPaddingLeft());
445 maxWidth = rowRect.width() - textX;
447 // Prepare text to be drawn.
448 String itemText = m_popupClient->itemText(rowIndex);
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.
455 textX += maxWidth - itemFont.width(textRun);
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));
464 Font PopupListBox::getRowFont(int rowIndex)
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());
479 void PopupListBox::abandon()
481 RefPtr<PopupListBox> keepAlive(this);
483 m_selectedIndex = m_originalIndex;
487 if (m_acceptedIndexOnAbandon >= 0) {
489 m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
490 m_acceptedIndexOnAbandon = -1;
494 int PopupListBox::pointToRowIndex(const IntPoint& point)
496 int y = scrollY() + point.y();
498 // FIXME: binary search if perf matters.
499 for (int i = 0; i < numItems(); ++i) {
500 if (y < m_items[i]->yOffset)
505 if (y < contentsHeight())
506 return m_items.size()-1;
511 bool PopupListBox::acceptIndex(int index)
513 // Clear m_acceptedIndexOnAbandon once user accepts the selected index.
514 if (m_acceptedIndexOnAbandon >= 0)
515 m_acceptedIndexOnAbandon = -1;
517 if (index >= numItems())
522 // Enter pressed with no selection, just close the popup.
528 if (isSelectableItem(index)) {
529 RefPtr<PopupListBox> keepAlive(this);
531 // Hide ourselves first since valueChanged may have numerous side-effects.
534 // Tell the <select> PopupMenuClient what index was selected.
535 m_popupClient->valueChanged(index);
543 void PopupListBox::selectIndex(int index)
545 if (index < 0 || index >= numItems())
548 bool isSelectable = isSelectableItem(index);
549 if (index != m_selectedIndex && isSelectable) {
550 invalidateRow(m_selectedIndex);
551 m_selectedIndex = index;
552 invalidateRow(m_selectedIndex);
554 scrollToRevealSelection();
555 m_popupClient->selectionChanged(m_selectedIndex);
556 } else if (!isSelectable)
560 void PopupListBox::setOriginalIndex(int index)
562 m_originalIndex = m_selectedIndex = index;
565 int PopupListBox::getRowHeight(int index)
567 int minimumHeight = PopupMenuChromium::minimumRowHeight();
568 if (m_deviceSupportsTouch)
569 minimumHeight = max(minimumHeight, PopupMenuChromium::optionRowHeightForTouch());
571 if (index < 0 || m_popupClient->itemStyle(index).isDisplayNone())
572 return minimumHeight;
574 // Separator row height is the same size as itself.
575 if (m_popupClient->itemIsSeparator(index))
576 return max(separatorHeight, minimumHeight);
578 int fontHeight = getRowFont(index).fontMetrics().height();
579 return max(fontHeight, minimumHeight);
582 IntRect PopupListBox::getRowBounds(int index)
585 return IntRect(0, 0, visibleWidth(), getRowHeight(index));
587 return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
590 void PopupListBox::invalidateRow(int index)
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);
603 void PopupListBox::scrollToRevealRow(int index)
608 IntRect rowRect = getRowBounds(index);
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()));
619 bool PopupListBox::isSelectableItem(int index)
621 ASSERT(index >= 0 && index < numItems());
622 return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
625 void PopupListBox::clearSelection()
627 if (m_selectedIndex != -1) {
628 invalidateRow(m_selectedIndex);
629 m_selectedIndex = -1;
630 m_popupClient->selectionCleared();
634 void PopupListBox::selectNextRow()
636 adjustSelectedIndex(1);
639 void PopupListBox::selectPreviousRow()
641 adjustSelectedIndex(-1);
644 void PopupListBox::adjustSelectedIndex(int delta)
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].
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)
662 if (passedTarget && bestIndex != m_selectedIndex)
668 // Pick the best index, which may mean we don't change.
669 targetIndex = bestIndex;
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();
679 void PopupListBox::hidePopup()
682 PopupContainer* container = static_cast<PopupContainer*>(parent());
683 if (container->client())
684 container->client()->popupClosed(container);
685 container->notifyPopupHidden();
689 m_popupClient->popupDidHide();
692 void PopupListBox::updateFromElement()
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;
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();
712 m_selectedIndex = m_popupClient->selectedIndex();
713 setOriginalIndex(m_selectedIndex);
718 void PopupListBox::setMaxWidthAndLayout(int maxWidth)
720 m_maxWindowWidth = maxWidth;
724 void PopupListBox::layout()
726 bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
728 // Size our child items.
730 int paddingWidth = 0;
731 int lineEndPaddingWidth = 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())
738 y += getRowHeight(i);
740 // Ensure the popup is wide enough to fit this item.
741 Font itemFont = getRowFont(i);
742 String text = m_popupClient->itemText(i);
745 width = itemFont.width(TextRun(text));
747 baseWidth = max(baseWidth, width);
748 // FIXME: http://b/1210481 We should get the padding of individual
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());
756 // Calculate scroll bar width.
757 int windowHeight = 0;
758 m_visibleRows = std::min(numItems(), maxVisibleRows);
760 for (int i = 0; i < m_visibleRows; ++i) {
761 int rowHeight = getRowHeight(i);
763 // Only clip the window height for non-Mac platforms.
764 if (windowHeight + rowHeight > m_maxHeight) {
769 windowHeight += rowHeight;
772 // Set our widget and scrollable contents sizes.
773 int scrollbarWidth = 0;
774 if (m_visibleRows < numItems()) {
775 scrollbarWidth = ScrollbarTheme::theme()->scrollbarThickness();
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;
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;
791 int contentWidth = windowWidth - scrollbarWidth;
793 if (windowWidth < m_baseWidth) {
794 windowWidth = m_baseWidth;
795 contentWidth = m_baseWidth - scrollbarWidth;
797 m_baseWidth = baseWidth;
800 resize(windowWidth, windowHeight);
801 setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
804 scrollToRevealSelection();
809 void PopupListBox::clear()
811 for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it)
816 bool PopupListBox::isPointInBounds(const IntPoint& point)
818 return numItems() && IntRect(0, 0, width(), height()).contains(point);
821 int PopupListBox::popupContentHeight() const
826 } // namespace WebCore