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 "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"
63 using namespace WTF::Unicode;
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, PopupContainer* container)
71 : m_deviceSupportsTouch(deviceSupportsTouch)
74 , m_acceptedIndexOnAbandon(-1)
77 , m_maxHeight(defaultMaxHeight)
78 , m_popupClient(client)
81 , m_maxWindowWidth(std::numeric_limits<int>::max())
82 , m_container(container)
86 PopupListBox::~PopupListBox()
90 // Oilpan: the scrollbars of the ScrollView are self-sufficient,
91 // capable of detaching themselves from their animator on
94 setHasVerticalScrollbar(false);
98 void PopupListBox::trace(Visitor* visitor)
100 visitor->trace(m_capturingScrollbar);
101 visitor->trace(m_lastScrollbarUnderMouse);
102 visitor->trace(m_focusedElement);
103 visitor->trace(m_container);
104 visitor->trace(m_verticalScrollbar);
105 Widget::trace(visitor);
108 bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
110 Scrollbar* scrollbar = scrollbarAtWindowPoint(event.position());
112 m_capturingScrollbar = scrollbar;
113 m_capturingScrollbar->mouseDown(event);
117 if (!isPointInBounds(event.position()))
123 bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
125 if (m_capturingScrollbar) {
126 m_capturingScrollbar->mouseMoved(event);
130 Scrollbar* scrollbar = scrollbarAtWindowPoint(event.position());
131 if (m_lastScrollbarUnderMouse != scrollbar) {
132 // Send mouse exited to the old scrollbar.
133 if (m_lastScrollbarUnderMouse)
134 m_lastScrollbarUnderMouse->mouseExited();
135 m_lastScrollbarUnderMouse = scrollbar;
139 scrollbar->mouseMoved(event);
143 if (!isPointInBounds(event.position()))
146 selectIndex(pointToRowIndex(event.position()));
150 bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
152 if (m_capturingScrollbar) {
153 m_capturingScrollbar->mouseUp(event);
154 m_capturingScrollbar = nullptr;
158 if (!isPointInBounds(event.position()))
161 if (acceptIndex(pointToRowIndex(event.position())) && m_focusedElement) {
162 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::mouseup);
163 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::click);
165 // Clear m_focusedElement here, because we cannot clear in hidePopup()
166 // which is called before dispatchMouseEvent() is called.
167 m_focusedElement = nullptr;
173 bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
175 if (!isPointInBounds(event.position())) {
180 ScrollableArea::handleWheelEvent(event);
184 // Should be kept in sync with handleKeyEvent().
185 bool PopupListBox::isInterestedInEventForKey(int keyCode)
203 bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&)
208 bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&)
213 static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
215 // Check whether the event is a character-typed event or not.
216 // We use RawKeyDown/Char/KeyUp event scheme on all platforms,
217 // so PlatformKeyboardEvent::Char (not RawKeyDown) type event
218 // is considered as character type event.
219 return event.type() == PlatformEvent::Char;
222 bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
224 if (event.type() == PlatformEvent::KeyUp)
227 if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
230 switch (event.windowsVirtualKeyCode()) {
232 abandon(); // may delete this
235 if (m_selectedIndex == -1) {
237 // Don't eat the enter if nothing is selected.
240 acceptIndex(m_selectedIndex); // may delete this
249 adjustSelectedIndex(-m_visibleRows);
252 adjustSelectedIndex(m_visibleRows);
255 adjustSelectedIndex(-m_selectedIndex);
258 adjustSelectedIndex(m_items.size());
261 if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
262 && isPrintableChar(event.windowsVirtualKeyCode())
263 && isCharacterTypeEvent(event))
264 typeAheadFind(event);
268 if (event.altKey() && (event.keyIdentifier() == "Down" || event.keyIdentifier() == "Up")) {
273 if (m_originalIndex != m_selectedIndex) {
274 // Keyboard events should update the selection immediately (but we don't
275 // want to fire the onchange event until the popup is closed, to match
276 // IE). We change the original index so we revert to that when the
278 m_acceptedIndexOnAbandon = m_selectedIndex;
280 setOriginalIndex(m_selectedIndex);
281 m_popupClient->setTextFromItem(m_selectedIndex);
283 if (event.windowsVirtualKeyCode() == VKEY_TAB) {
284 // TAB is a special case as it should select the current item if any and
286 if (m_selectedIndex >= 0) {
287 acceptIndex(m_selectedIndex); // May delete us.
288 // Return false so the TAB key event is propagated to the page.
291 // Call abandon() so we honor m_acceptedIndexOnAbandon if set.
293 // Return false so the TAB key event is propagated to the page.
300 HostWindow* PopupListBox::hostWindow() const
302 // Our parent is the root FrameView, so it is the one that has a
303 // HostWindow. FrameView::hostWindow() works similarly.
304 return parent() ? parent()->hostWindow() : 0;
307 bool PopupListBox::shouldPlaceVerticalScrollbarOnLeft() const
309 return m_popupClient->menuStyle().textDirection() == RTL;
312 // From HTMLSelectElement.cpp
313 static String stripLeadingWhiteSpace(const String& string)
315 int length = string.length();
317 for (i = 0; i < length; ++i)
318 if (string[i] != noBreakSpace
319 && !isSpaceOrNewline(string[i]))
322 return string.substring(i, length - i);
325 // From HTMLSelectElement.cpp, with modifications
326 void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
328 TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
329 TimeStamp delta = now - m_lastCharTime;
331 // Reset the time when user types in a character. The time gap between
332 // last character and the current character is used to indicate whether
333 // user typed in a string or just a character as the search prefix.
334 m_lastCharTime = now;
336 UChar c = event.windowsVirtualKeyCode();
339 int searchStartOffset = 1;
340 if (delta > typeAheadTimeoutMs) {
341 m_typedString = prefix = String(&c, 1);
344 m_typedString.append(c);
346 if (c == m_repeatingChar) {
347 // The user is likely trying to cycle through all the items starting
348 // with this character, so just search on the character.
349 prefix = String(&c, 1);
352 prefix = m_typedString;
353 searchStartOffset = 0;
357 // Compute a case-folded copy of the prefix string before beginning the
358 // search for a matching element. This code uses foldCase to work around the
359 // fact that String::startWith does not fold non-ASCII characters. This code
360 // can be changed to use startWith once that is fixed.
361 String prefixWithCaseFolded(prefix.foldCase());
362 int itemCount = numItems();
363 int index = (max(0, m_selectedIndex) + searchStartOffset) % itemCount;
364 for (int i = 0; i < itemCount; i++, index = (index + 1) % itemCount) {
365 if (!isSelectableItem(index))
368 if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
375 void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
377 // Adjust coords for scrolled frame.
378 IntRect r = intersection(rect, frameRect());
379 int tx = x() - scrollX() + ((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar()) ? verticalScrollbar()->width() : 0);
380 int ty = y() - scrollY();
384 // Set clip rect to match revised damage rect.
386 gc->translate(static_cast<float>(tx), static_cast<float>(ty));
389 // FIXME: Can we optimize scrolling to not require repainting the entire
390 // window? Should we?
391 for (int i = 0; i < numItems(); ++i)
394 // Special case for an empty popup.
396 gc->fillRect(r, Color::white);
400 if (m_verticalScrollbar) {
401 GraphicsContextStateSaver stateSaver(*gc);
402 IntRect scrollbarDirtyRect = rect;
403 IntRect visibleAreaWithScrollbars(location(), visibleContentRect(IncludeScrollbars).size());
404 scrollbarDirtyRect.intersect(visibleAreaWithScrollbars);
405 gc->translate(x(), y());
406 scrollbarDirtyRect.moveBy(-location());
407 gc->clip(IntRect(IntPoint(), visibleAreaWithScrollbars.size()));
409 m_verticalScrollbar->paint(gc, scrollbarDirtyRect);
413 static const int separatorPadding = 4;
414 static const int separatorHeight = 1;
415 static const int minRowHeight = 0;
416 static const int optionRowHeightForTouch = 28;
418 void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
420 // This code is based largely on RenderListBox::paint* methods.
422 IntRect rowRect = getRowBounds(rowIndex);
423 if (!rowRect.intersects(rect))
426 PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
429 Color backColor, textColor, labelColor;
430 if (rowIndex == m_selectedIndex) {
431 backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor();
432 textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor();
433 labelColor = textColor;
435 backColor = style.backgroundColor();
436 textColor = style.foregroundColor();
437 #if OS(LINUX) || OS(ANDROID)
438 // On other platforms, the <option> background color is the same as the
439 // <select> background color. On Linux, that makes the <option>
440 // background color very dark, so by default, try to use a lighter
441 // background color for <option>s.
442 if (style.backgroundColorType() == PopupMenuStyle::DefaultBackgroundColor && RenderTheme::theme().systemColor(CSSValueButtonface) == backColor)
443 backColor = RenderTheme::theme().systemColor(CSSValueMenu);
446 // FIXME: for now the label color is hard-coded. It should be added to
447 // the PopupMenuStyle.
448 labelColor = Color(115, 115, 115);
451 // If we have a transparent background, make sure it has a color to blend
453 if (backColor.hasAlpha())
454 gc->fillRect(rowRect, Color::white);
456 gc->fillRect(rowRect, backColor);
458 if (m_popupClient->itemIsSeparator(rowIndex)) {
459 IntRect separatorRect(
460 rowRect.x() + separatorPadding,
461 rowRect.y() + (rowRect.height() - separatorHeight) / 2,
462 rowRect.width() - 2 * separatorPadding, separatorHeight);
463 gc->fillRect(separatorRect, textColor);
467 if (!style.isVisible())
470 gc->setFillColor(textColor);
472 FontCachePurgePreventer fontCachePurgePreventer;
474 Font itemFont = getRowFont(rowIndex);
475 // FIXME: http://crbug.com/19872 We should get the padding of individual option
476 // elements. This probably implies changes to PopupMenuClient.
477 bool rightAligned = m_popupClient->menuStyle().textDirection() == RTL;
481 maxWidth = rowRect.width() - max<int>(0, m_popupClient->clientPaddingRight());
483 textX = max<int>(0, m_popupClient->clientPaddingLeft());
484 maxWidth = rowRect.width() - textX;
486 // Prepare text to be drawn.
487 String itemText = m_popupClient->itemText(rowIndex);
489 // Prepare the directionality to draw text.
490 TextRun textRun(itemText, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
491 // If the text is right-to-left, make it right-aligned by adjusting its
492 // beginning position.
494 textX += maxWidth - itemFont.width(textRun);
496 // Draw the item text.
497 int textY = rowRect.y() + itemFont.fontMetrics().ascent() + (rowRect.height() - itemFont.fontMetrics().height()) / 2;
498 TextRunPaintInfo textRunPaintInfo(textRun);
499 textRunPaintInfo.bounds = rowRect;
500 gc->drawBidiText(itemFont, textRunPaintInfo, IntPoint(textX, textY));
503 Font PopupListBox::getRowFont(int rowIndex) const
505 Font itemFont = m_popupClient->itemStyle(rowIndex).font();
506 if (m_popupClient->itemIsLabel(rowIndex)) {
507 // Bold-ify labels (ie, an <optgroup> heading).
508 FontDescription d = itemFont.fontDescription();
509 d.setWeight(FontWeightBold);
511 font.update(nullptr);
518 void PopupListBox::abandon()
520 RefPtrWillBeRawPtr<PopupListBox> protect(this);
522 m_selectedIndex = m_originalIndex;
526 if (m_acceptedIndexOnAbandon >= 0) {
528 m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
529 m_acceptedIndexOnAbandon = -1;
533 int PopupListBox::pointToRowIndex(const IntPoint& point)
535 int y = scrollY() + point.y();
537 // FIXME: binary search if perf matters.
538 for (int i = 0; i < numItems(); ++i) {
539 if (y < m_items[i]->yOffset)
544 if (y < contentsSize().height())
545 return m_items.size()-1;
550 bool PopupListBox::acceptIndex(int index)
552 // Clear m_acceptedIndexOnAbandon once user accepts the selected index.
553 if (m_acceptedIndexOnAbandon >= 0)
554 m_acceptedIndexOnAbandon = -1;
556 if (index >= numItems())
561 // Enter pressed with no selection, just close the popup.
567 if (isSelectableItem(index)) {
568 RefPtrWillBeRawPtr<PopupListBox> protect(this);
570 // Hide ourselves first since valueChanged may have numerous side-effects.
573 // Tell the <select> PopupMenuClient what index was selected.
574 m_popupClient->valueChanged(index);
582 void PopupListBox::selectIndex(int index)
584 if (index < 0 || index >= numItems())
587 bool isSelectable = isSelectableItem(index);
588 if (index != m_selectedIndex && isSelectable) {
589 invalidateRow(m_selectedIndex);
590 m_selectedIndex = index;
591 invalidateRow(m_selectedIndex);
593 scrollToRevealSelection();
594 m_popupClient->selectionChanged(m_selectedIndex);
595 } else if (!isSelectable)
599 void PopupListBox::setOriginalIndex(int index)
601 m_originalIndex = m_selectedIndex = index;
604 int PopupListBox::getRowHeight(int index) const
606 int minimumHeight = m_deviceSupportsTouch ? optionRowHeightForTouch : minRowHeight;
608 if (index < 0 || m_popupClient->itemStyle(index).isDisplayNone())
609 return minimumHeight;
611 // Separator row height is the same size as itself.
612 if (m_popupClient->itemIsSeparator(index))
613 return max(separatorHeight, minimumHeight);
615 int fontHeight = getRowFont(index).fontMetrics().height();
616 return max(fontHeight, minimumHeight);
619 IntRect PopupListBox::getRowBounds(int index)
622 return IntRect(0, 0, visibleWidth(), getRowHeight(index));
624 return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
627 void PopupListBox::invalidateRow(int index)
632 // Invalidate in the window contents, as invalidateRect paints in the window coordinates.
633 IntRect clipRect = contentsToWindow(getRowBounds(index));
634 if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar())
635 clipRect.move(verticalScrollbar()->width(), 0);
636 invalidateRect(clipRect);
639 void PopupListBox::scrollToRevealRow(int index)
644 IntRect rowRect = getRowBounds(index);
646 if (rowRect.y() < scrollY()) {
647 // Row is above current scroll position, scroll up.
648 updateScrollbars(IntPoint(0, rowRect.y()));
649 } else if (rowRect.maxY() > scrollY() + visibleHeight()) {
650 // Row is below current scroll position, scroll down.
651 updateScrollbars(IntPoint(0, rowRect.maxY() - visibleHeight()));
655 bool PopupListBox::isSelectableItem(int index)
657 ASSERT(index >= 0 && index < numItems());
658 return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
661 void PopupListBox::clearSelection()
663 if (m_selectedIndex != -1) {
664 invalidateRow(m_selectedIndex);
665 m_selectedIndex = -1;
666 m_popupClient->selectionCleared();
670 void PopupListBox::selectNextRow()
672 adjustSelectedIndex(1);
675 void PopupListBox::selectPreviousRow()
677 adjustSelectedIndex(-1);
680 void PopupListBox::adjustSelectedIndex(int delta)
682 int targetIndex = m_selectedIndex + delta;
683 targetIndex = std::min(std::max(targetIndex, 0), numItems() - 1);
684 if (!isSelectableItem(targetIndex)) {
685 // We didn't land on an option. Try to find one.
686 // We try to select the closest index to target, prioritizing any in
687 // the range [current, target].
689 int dir = delta > 0 ? 1 : -1;
690 int testIndex = m_selectedIndex;
691 int bestIndex = m_selectedIndex;
692 bool passedTarget = false;
693 while (testIndex >= 0 && testIndex < numItems()) {
694 if (isSelectableItem(testIndex))
695 bestIndex = testIndex;
696 if (testIndex == targetIndex)
698 if (passedTarget && bestIndex != m_selectedIndex)
704 // Pick the best index, which may mean we don't change.
705 targetIndex = bestIndex;
708 // Select the new index, and ensure its visible. We do this regardless of
709 // whether the selection changed to ensure keyboard events always bring the
710 // selection into view.
711 selectIndex(targetIndex);
712 scrollToRevealSelection();
715 void PopupListBox::hidePopup()
718 if (m_container->client())
719 m_container->client()->popupClosed(m_container);
720 m_container->notifyPopupHidden();
724 m_popupClient->popupDidHide();
727 void PopupListBox::updateFromElement()
731 int size = m_popupClient->listSize();
732 for (int i = 0; i < size; ++i) {
733 PopupItem::Type type;
734 if (m_popupClient->itemIsSeparator(i))
735 type = PopupItem::TypeSeparator;
736 else if (m_popupClient->itemIsLabel(i))
737 type = PopupItem::TypeGroup;
739 type = PopupItem::TypeOption;
740 m_items.append(new PopupItem(m_popupClient->itemText(i), type));
741 m_items[i]->enabled = isSelectableItem(i);
742 PopupMenuStyle style = m_popupClient->itemStyle(i);
743 m_items[i]->textDirection = style.textDirection();
744 m_items[i]->hasTextDirectionOverride = style.hasTextDirectionOverride();
745 m_items[i]->displayNone = style.isDisplayNone();
748 m_selectedIndex = m_popupClient->selectedIndex();
749 setOriginalIndex(m_selectedIndex);
754 void PopupListBox::setMaxWidthAndLayout(int maxWidth)
756 m_maxWindowWidth = maxWidth;
760 int PopupListBox::getRowBaseWidth(int index)
762 Font font = getRowFont(index);
763 PopupMenuStyle style = m_popupClient->itemStyle(index);
764 String text = m_popupClient->itemText(index);
767 TextRun textRun(text, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
768 return font.width(textRun);
771 void PopupListBox::layout()
773 bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
775 // Size our child items.
777 int paddingWidth = 0;
778 int lineEndPaddingWidth = 0;
780 for (int i = 0; i < numItems(); ++i) {
781 // Place the item vertically.
782 m_items[i]->yOffset = y;
783 if (m_popupClient->itemStyle(i).isDisplayNone())
785 y += getRowHeight(i);
787 // Ensure the popup is wide enough to fit this item.
788 baseWidth = max(baseWidth, getRowBaseWidth(i));
789 // FIXME: http://b/1210481 We should get the padding of individual
791 paddingWidth = max<int>(paddingWidth,
792 m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight());
793 lineEndPaddingWidth = max<int>(lineEndPaddingWidth,
794 isRightAligned ? m_popupClient->clientPaddingLeft() : m_popupClient->clientPaddingRight());
797 // Calculate scroll bar width.
798 int windowHeight = 0;
799 m_visibleRows = std::min(numItems(), maxVisibleRows);
801 for (int i = 0; i < m_visibleRows; ++i) {
802 int rowHeight = getRowHeight(i);
804 // Only clip the window height for non-Mac platforms.
805 if (windowHeight + rowHeight > m_maxHeight) {
810 windowHeight += rowHeight;
813 // Set our widget and scrollable contents sizes.
814 int scrollbarWidth = 0;
815 if (m_visibleRows < numItems()) {
816 if (!ScrollbarTheme::theme()->usesOverlayScrollbars())
817 scrollbarWidth = ScrollbarTheme::theme()->scrollbarThickness();
819 // Use minEndOfLinePadding when there is a scrollbar so that we use
820 // as much as (lineEndPaddingWidth - minEndOfLinePadding) padding
821 // space for scrollbar and allow user to use CSS padding to make the
822 // popup listbox align with the select element.
823 paddingWidth = paddingWidth - lineEndPaddingWidth + minEndOfLinePadding;
826 int windowWidth = baseWidth + scrollbarWidth + paddingWidth;
827 if (windowWidth > m_maxWindowWidth) {
828 // windowWidth exceeds m_maxWindowWidth, so we have to clip.
829 windowWidth = m_maxWindowWidth;
830 baseWidth = windowWidth - scrollbarWidth - paddingWidth;
831 m_baseWidth = baseWidth;
833 int contentWidth = windowWidth - scrollbarWidth;
835 if (windowWidth < m_baseWidth) {
836 windowWidth = m_baseWidth;
837 contentWidth = m_baseWidth - scrollbarWidth;
839 m_baseWidth = baseWidth;
842 resize(windowWidth, windowHeight);
843 setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
846 scrollToRevealSelection();
851 void PopupListBox::clear()
853 deleteAllValues(m_items);
857 bool PopupListBox::isPointInBounds(const IntPoint& point)
859 return numItems() && IntRect(0, 0, width(), height()).contains(point);
862 int PopupListBox::popupContentHeight() const
867 void PopupListBox::invalidateRect(const IntRect& rect)
869 if (HostWindow* h = hostWindow())
870 h->invalidateContentsAndRootView(rect);
873 IntRect PopupListBox::windowClipRect() const
875 IntRect clipRect = visibleContentRect();
876 if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar())
877 clipRect.move(verticalScrollbar()->width(), 0);
878 return contentsToWindow(clipRect);
881 void PopupListBox::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
883 // Add in our offset within the FrameView.
884 IntRect dirtyRect = rect;
885 dirtyRect.move(scrollbar->x(), scrollbar->y());
886 invalidateRect(dirtyRect);
889 bool PopupListBox::isActive() const
895 bool PopupListBox::scrollbarsCanBeActive() const
900 IntRect PopupListBox::scrollableAreaBoundingBox() const
902 return windowClipRect();
905 // FIXME: The following methods are based on code in FrameView, with
906 // simplifications for the constraints of PopupListBox (e.g. only vertical
907 // scrollbar, not horizontal). This functionality should be moved into
908 // ScrollableArea after http://crbug.com/417782 is fixed.
910 void PopupListBox::setHasVerticalScrollbar(bool hasBar)
912 if (hasBar && !m_verticalScrollbar) {
913 m_verticalScrollbar = Scrollbar::create(this, VerticalScrollbar, RegularScrollbar);
914 m_verticalScrollbar->setParent(this);
915 didAddScrollbar(m_verticalScrollbar.get(), VerticalScrollbar);
916 m_verticalScrollbar->styleChanged();
917 } else if (!hasBar && m_verticalScrollbar) {
918 m_verticalScrollbar->setParent(0);
919 willRemoveScrollbar(m_verticalScrollbar.get(), VerticalScrollbar);
920 m_verticalScrollbar = nullptr;
924 Scrollbar* PopupListBox::scrollbarAtWindowPoint(const IntPoint& windowPoint)
926 return m_verticalScrollbar && m_verticalScrollbar->frameRect().contains(
927 convertFromContainingWindow(windowPoint)) ? m_verticalScrollbar.get() : 0;
930 IntRect PopupListBox::contentsToWindow(const IntRect& contentsRect) const
932 IntRect viewRect = contentsRect;
933 viewRect.moveBy(-scrollPosition());
934 return convertToContainingWindow(viewRect);
937 void PopupListBox::setContentsSize(const IntSize& newSize)
939 if (contentsSize() == newSize)
941 m_contentsSize = newSize;
942 updateScrollbars(scrollPosition());
945 void PopupListBox::setFrameRect(const IntRect& newRect)
947 IntRect oldRect = frameRect();
948 if (newRect == oldRect)
951 Widget::setFrameRect(newRect);
952 updateScrollbars(scrollPosition());
953 // NOTE: We do not need to call m_verticalScrollbar->frameRectsChanged as
954 // Scrollbar does not implement it.
957 IntRect PopupListBox::visibleContentRect(IncludeScrollbarsInRect scrollbarInclusion) const
959 // NOTE: Unlike FrameView we do not need to incorporate any scaling factor,
960 // and there is only one scrollbar to exclude.
961 IntSize size = frameRect().size();
962 Scrollbar* verticalBar = verticalScrollbar();
963 if (scrollbarInclusion == ExcludeScrollbars && verticalBar && !verticalBar->isOverlayScrollbar()) {
964 size.setWidth(std::max(0, size.width() - verticalBar->width()));
966 return IntRect(m_scrollOffset, size);
969 void PopupListBox::updateScrollbars(IntPoint desiredOffset)
971 IntSize oldVisibleSize = visibleContentRect().size();
972 adjustScrollbarExistence();
973 updateScrollbarGeometry();
974 IntSize newVisibleSize = visibleContentRect().size();
976 if (newVisibleSize.width() > oldVisibleSize.width()) {
977 if (shouldPlaceVerticalScrollbarOnLeft())
978 invalidateRect(IntRect(0, 0, newVisibleSize.width() - oldVisibleSize.width(), newVisibleSize.height()));
980 invalidateRect(IntRect(oldVisibleSize.width(), 0, newVisibleSize.width() - oldVisibleSize.width(), newVisibleSize.height()));
983 desiredOffset = desiredOffset.shrunkTo(maximumScrollPosition());
984 desiredOffset = desiredOffset.expandedTo(minimumScrollPosition());
986 if (desiredOffset != scrollPosition())
987 ScrollableArea::scrollToOffsetWithoutAnimation(desiredOffset);
990 void PopupListBox::adjustScrollbarExistence()
992 bool needsVerticalScrollbar = contentsSize().height() > visibleHeight();
993 if (!!m_verticalScrollbar != needsVerticalScrollbar) {
994 setHasVerticalScrollbar(needsVerticalScrollbar);
999 void PopupListBox::updateScrollbarGeometry()
1001 if (m_verticalScrollbar) {
1002 int clientHeight = visibleHeight();
1003 IntRect oldRect(m_verticalScrollbar->frameRect());
1004 IntRect vBarRect(shouldPlaceVerticalScrollbarOnLeft() ? 0 : (width() - m_verticalScrollbar->width()),
1005 0, m_verticalScrollbar->width(), height());
1006 m_verticalScrollbar->setFrameRect(vBarRect);
1007 if (oldRect != m_verticalScrollbar->frameRect())
1008 m_verticalScrollbar->invalidate();
1010 m_verticalScrollbar->setEnabled(contentsSize().height() > clientHeight);
1011 m_verticalScrollbar->setProportion(clientHeight, contentsSize().height());
1012 m_verticalScrollbar->offsetDidChange();
1013 // NOTE: PopupListBox does not support suppressing scrollbars.
1017 IntPoint PopupListBox::convertChildToSelf(const Widget* child, const IntPoint& point) const
1019 // NOTE: m_verticalScrollbar is the only child.
1020 IntPoint newPoint = point;
1021 newPoint.moveBy(child->location());
1025 IntPoint PopupListBox::convertSelfToChild(const Widget* child, const IntPoint& point) const
1027 // NOTE: m_verticalScrollbar is the only child.
1028 IntPoint newPoint = point;
1029 newPoint.moveBy(-child->location());
1033 int PopupListBox::scrollSize(ScrollbarOrientation orientation) const
1035 return (orientation == HorizontalScrollbar || !m_verticalScrollbar) ?
1036 0 : m_verticalScrollbar->totalSize() - m_verticalScrollbar->visibleSize();
1039 void PopupListBox::setScrollOffset(const IntPoint& newOffset)
1041 // NOTE: We do not support any "fast path" for scrolling. When the scroll
1042 // offset changes, we just repaint the whole popup.
1043 IntSize scrollDelta = newOffset - m_scrollOffset;
1044 if (scrollDelta == IntSize())
1046 m_scrollOffset = newOffset;
1048 if (HostWindow* window = hostWindow()) {
1049 IntRect clipRect = windowClipRect();
1050 IntRect updateRect = clipRect;
1051 updateRect.intersect(convertToContainingWindow(IntRect((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) ? verticalScrollbar()->width() : 0, 0, visibleWidth(), visibleHeight())));
1052 window->invalidateContentsForSlowScroll(updateRect);
1056 IntPoint PopupListBox::maximumScrollPosition() const
1058 IntPoint maximumOffset(contentsSize().width() - visibleWidth() - scrollOrigin().x(), contentsSize().height() - visibleHeight() - scrollOrigin().y());
1059 maximumOffset.clampNegativeToZero();
1060 return maximumOffset;
1063 IntPoint PopupListBox::minimumScrollPosition() const
1065 return IntPoint(-scrollOrigin().x(), -scrollOrigin().y());
1068 } // namespace blink