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 setHasVerticalScrollbar(false);
93 bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
95 Scrollbar* scrollbar = scrollbarAtWindowPoint(event.position());
97 m_capturingScrollbar = scrollbar;
98 m_capturingScrollbar->mouseDown(event);
102 if (!isPointInBounds(event.position()))
108 bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
110 if (m_capturingScrollbar) {
111 m_capturingScrollbar->mouseMoved(event);
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;
124 scrollbar->mouseMoved(event);
128 if (!isPointInBounds(event.position()))
131 selectIndex(pointToRowIndex(event.position()));
135 bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
137 if (m_capturingScrollbar) {
138 m_capturingScrollbar->mouseUp(event);
139 m_capturingScrollbar = nullptr;
143 if (!isPointInBounds(event.position()))
146 if (acceptIndex(pointToRowIndex(event.position())) && m_focusedElement) {
147 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::mouseup);
148 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::click);
150 // Clear m_focusedElement here, because we cannot clear in hidePopup()
151 // which is called before dispatchMouseEvent() is called.
152 m_focusedElement = nullptr;
158 bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
160 if (!isPointInBounds(event.position())) {
165 ScrollableArea::handleWheelEvent(event);
169 // Should be kept in sync with handleKeyEvent().
170 bool PopupListBox::isInterestedInEventForKey(int keyCode)
188 bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&)
193 bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&)
198 static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
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;
207 bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
209 if (event.type() == PlatformEvent::KeyUp)
212 if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
215 switch (event.windowsVirtualKeyCode()) {
217 abandon(); // may delete this
220 if (m_selectedIndex == -1) {
222 // Don't eat the enter if nothing is selected.
225 acceptIndex(m_selectedIndex); // may delete this
234 adjustSelectedIndex(-m_visibleRows);
237 adjustSelectedIndex(m_visibleRows);
240 adjustSelectedIndex(-m_selectedIndex);
243 adjustSelectedIndex(m_items.size());
246 if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
247 && isPrintableChar(event.windowsVirtualKeyCode())
248 && isCharacterTypeEvent(event))
249 typeAheadFind(event);
253 if (event.altKey() && (event.keyIdentifier() == "Down" || event.keyIdentifier() == "Up")) {
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
263 m_acceptedIndexOnAbandon = m_selectedIndex;
265 setOriginalIndex(m_selectedIndex);
266 m_popupClient->setTextFromItem(m_selectedIndex);
268 if (event.windowsVirtualKeyCode() == VKEY_TAB) {
269 // TAB is a special case as it should select the current item if any and
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.
276 // Call abandon() so we honor m_acceptedIndexOnAbandon if set.
278 // Return false so the TAB key event is propagated to the page.
285 HostWindow* PopupListBox::hostWindow() const
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;
292 bool PopupListBox::shouldPlaceVerticalScrollbarOnLeft() const
294 return m_popupClient->menuStyle().textDirection() == RTL;
297 // From HTMLSelectElement.cpp
298 static String stripLeadingWhiteSpace(const String& string)
300 int length = string.length();
302 for (i = 0; i < length; ++i)
303 if (string[i] != noBreakSpace
304 && !isSpaceOrNewline(string[i]))
307 return string.substring(i, length - i);
310 // From HTMLSelectElement.cpp, with modifications
311 void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
313 TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
314 TimeStamp delta = now - m_lastCharTime;
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;
321 UChar c = event.windowsVirtualKeyCode();
324 int searchStartOffset = 1;
325 if (delta > typeAheadTimeoutMs) {
326 m_typedString = prefix = String(&c, 1);
329 m_typedString.append(c);
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);
337 prefix = m_typedString;
338 searchStartOffset = 0;
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))
353 if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
360 void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
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();
369 // Set clip rect to match revised damage rect.
371 gc->translate(static_cast<float>(tx), static_cast<float>(ty));
374 // FIXME: Can we optimize scrolling to not require repainting the entire
375 // window? Should we?
376 for (int i = 0; i < numItems(); ++i)
379 // Special case for an empty popup.
381 gc->fillRect(r, Color::white);
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()));
394 m_verticalScrollbar->paint(gc, scrollbarDirtyRect);
398 static const int separatorPadding = 4;
399 static const int separatorHeight = 1;
400 static const int minRowHeight = 0;
401 static const int optionRowHeightForTouch = 28;
403 void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
405 // This code is based largely on RenderListBox::paint* methods.
407 IntRect rowRect = getRowBounds(rowIndex);
408 if (!rowRect.intersects(rect))
411 PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
414 Color backColor, textColor, labelColor;
415 if (rowIndex == m_selectedIndex) {
416 backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor();
417 textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor();
418 labelColor = textColor;
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);
431 // FIXME: for now the label color is hard-coded. It should be added to
432 // the PopupMenuStyle.
433 labelColor = Color(115, 115, 115);
436 // If we have a transparent background, make sure it has a color to blend
438 if (backColor.hasAlpha())
439 gc->fillRect(rowRect, Color::white);
441 gc->fillRect(rowRect, backColor);
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);
452 if (!style.isVisible())
455 gc->setFillColor(textColor);
457 FontCachePurgePreventer fontCachePurgePreventer;
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;
466 maxWidth = rowRect.width() - max<int>(0, m_popupClient->clientPaddingRight());
468 textX = max<int>(0, m_popupClient->clientPaddingLeft());
469 maxWidth = rowRect.width() - textX;
471 // Prepare text to be drawn.
472 String itemText = m_popupClient->itemText(rowIndex);
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.
479 textX += maxWidth - itemFont.width(textRun);
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));
488 Font PopupListBox::getRowFont(int rowIndex) const
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);
496 font.update(nullptr);
503 void PopupListBox::abandon()
505 RefPtr<PopupListBox> keepAlive(this);
507 m_selectedIndex = m_originalIndex;
511 if (m_acceptedIndexOnAbandon >= 0) {
513 m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
514 m_acceptedIndexOnAbandon = -1;
518 int PopupListBox::pointToRowIndex(const IntPoint& point)
520 int y = scrollY() + point.y();
522 // FIXME: binary search if perf matters.
523 for (int i = 0; i < numItems(); ++i) {
524 if (y < m_items[i]->yOffset)
529 if (y < contentsSize().height())
530 return m_items.size()-1;
535 bool PopupListBox::acceptIndex(int index)
537 // Clear m_acceptedIndexOnAbandon once user accepts the selected index.
538 if (m_acceptedIndexOnAbandon >= 0)
539 m_acceptedIndexOnAbandon = -1;
541 if (index >= numItems())
546 // Enter pressed with no selection, just close the popup.
552 if (isSelectableItem(index)) {
553 RefPtr<PopupListBox> keepAlive(this);
555 // Hide ourselves first since valueChanged may have numerous side-effects.
558 // Tell the <select> PopupMenuClient what index was selected.
559 m_popupClient->valueChanged(index);
567 void PopupListBox::selectIndex(int index)
569 if (index < 0 || index >= numItems())
572 bool isSelectable = isSelectableItem(index);
573 if (index != m_selectedIndex && isSelectable) {
574 invalidateRow(m_selectedIndex);
575 m_selectedIndex = index;
576 invalidateRow(m_selectedIndex);
578 scrollToRevealSelection();
579 m_popupClient->selectionChanged(m_selectedIndex);
580 } else if (!isSelectable)
584 void PopupListBox::setOriginalIndex(int index)
586 m_originalIndex = m_selectedIndex = index;
589 int PopupListBox::getRowHeight(int index) const
591 int minimumHeight = m_deviceSupportsTouch ? optionRowHeightForTouch : minRowHeight;
593 if (index < 0 || m_popupClient->itemStyle(index).isDisplayNone())
594 return minimumHeight;
596 // Separator row height is the same size as itself.
597 if (m_popupClient->itemIsSeparator(index))
598 return max(separatorHeight, minimumHeight);
600 int fontHeight = getRowFont(index).fontMetrics().height();
601 return max(fontHeight, minimumHeight);
604 IntRect PopupListBox::getRowBounds(int index)
607 return IntRect(0, 0, visibleWidth(), getRowHeight(index));
609 return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
612 void PopupListBox::invalidateRow(int index)
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);
624 void PopupListBox::scrollToRevealRow(int index)
629 IntRect rowRect = getRowBounds(index);
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()));
640 bool PopupListBox::isSelectableItem(int index)
642 ASSERT(index >= 0 && index < numItems());
643 return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
646 void PopupListBox::clearSelection()
648 if (m_selectedIndex != -1) {
649 invalidateRow(m_selectedIndex);
650 m_selectedIndex = -1;
651 m_popupClient->selectionCleared();
655 void PopupListBox::selectNextRow()
657 adjustSelectedIndex(1);
660 void PopupListBox::selectPreviousRow()
662 adjustSelectedIndex(-1);
665 void PopupListBox::adjustSelectedIndex(int delta)
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].
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)
683 if (passedTarget && bestIndex != m_selectedIndex)
689 // Pick the best index, which may mean we don't change.
690 targetIndex = bestIndex;
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();
700 void PopupListBox::hidePopup()
703 if (m_container->client())
704 m_container->client()->popupClosed(m_container);
705 m_container->notifyPopupHidden();
709 m_popupClient->popupDidHide();
712 void PopupListBox::updateFromElement()
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;
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();
733 m_selectedIndex = m_popupClient->selectedIndex();
734 setOriginalIndex(m_selectedIndex);
739 void PopupListBox::setMaxWidthAndLayout(int maxWidth)
741 m_maxWindowWidth = maxWidth;
745 int PopupListBox::getRowBaseWidth(int index)
747 Font font = getRowFont(index);
748 PopupMenuStyle style = m_popupClient->itemStyle(index);
749 String text = m_popupClient->itemText(index);
752 TextRun textRun(text, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
753 return font.width(textRun);
756 void PopupListBox::layout()
758 bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
760 // Size our child items.
762 int paddingWidth = 0;
763 int lineEndPaddingWidth = 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())
770 y += getRowHeight(i);
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
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());
782 // Calculate scroll bar width.
783 int windowHeight = 0;
784 m_visibleRows = std::min(numItems(), maxVisibleRows);
786 for (int i = 0; i < m_visibleRows; ++i) {
787 int rowHeight = getRowHeight(i);
789 // Only clip the window height for non-Mac platforms.
790 if (windowHeight + rowHeight > m_maxHeight) {
795 windowHeight += rowHeight;
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();
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;
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;
818 int contentWidth = windowWidth - scrollbarWidth;
820 if (windowWidth < m_baseWidth) {
821 windowWidth = m_baseWidth;
822 contentWidth = m_baseWidth - scrollbarWidth;
824 m_baseWidth = baseWidth;
827 resize(windowWidth, windowHeight);
828 setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
831 scrollToRevealSelection();
836 void PopupListBox::clear()
838 for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it)
843 bool PopupListBox::isPointInBounds(const IntPoint& point)
845 return numItems() && IntRect(0, 0, width(), height()).contains(point);
848 int PopupListBox::popupContentHeight() const
853 void PopupListBox::invalidateRect(const IntRect& rect)
855 if (HostWindow* h = hostWindow())
856 h->invalidateContentsAndRootView(rect);
859 IntRect PopupListBox::windowClipRect() const
861 IntRect clipRect = visibleContentRect();
862 if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar())
863 clipRect.move(verticalScrollbar()->width(), 0);
864 return contentsToWindow(clipRect);
867 void PopupListBox::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
869 // Add in our offset within the ScrollView.
870 IntRect dirtyRect = rect;
871 dirtyRect.move(scrollbar->x(), scrollbar->y());
872 invalidateRect(dirtyRect);
875 bool PopupListBox::isActive() const
881 bool PopupListBox::scrollbarsCanBeActive() const
886 IntRect PopupListBox::scrollableAreaBoundingBox() const
888 return windowClipRect();
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.
896 void PopupListBox::setHasVerticalScrollbar(bool hasBar)
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;
910 Scrollbar* PopupListBox::scrollbarAtWindowPoint(const IntPoint& windowPoint)
912 return m_verticalScrollbar && m_verticalScrollbar->frameRect().contains(
913 convertFromContainingWindow(windowPoint)) ? m_verticalScrollbar.get() : 0;
916 IntRect PopupListBox::contentsToWindow(const IntRect& contentsRect) const
918 IntRect viewRect = contentsRect;
919 viewRect.moveBy(-scrollPosition());
920 return convertToContainingWindow(viewRect);
923 void PopupListBox::setContentsSize(const IntSize& newSize)
925 if (contentsSize() == newSize)
927 m_contentsSize = newSize;
928 updateScrollbars(scrollPosition());
931 void PopupListBox::setFrameRect(const IntRect& newRect)
933 IntRect oldRect = frameRect();
934 if (newRect == oldRect)
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.
943 IntRect PopupListBox::visibleContentRect(IncludeScrollbarsInRect scrollbarInclusion) const
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()));
952 return IntRect(m_scrollOffset, size);
955 void PopupListBox::updateScrollbars(const IntPoint& desiredOffset)
957 IntSize oldVisibleSize = visibleContentRect().size();
958 adjustScrollbarExistence();
959 updateScrollbarGeometry();
960 IntSize newVisibleSize = visibleContentRect().size();
962 if (newVisibleSize.width() > oldVisibleSize.width()) {
963 if (shouldPlaceVerticalScrollbarOnLeft())
964 invalidateRect(IntRect(0, 0, newVisibleSize.width() - oldVisibleSize.width(), newVisibleSize.height()));
966 invalidateRect(IntRect(oldVisibleSize.width(), 0, newVisibleSize.width() - oldVisibleSize.width(), newVisibleSize.height()));
968 if (desiredOffset != scrollPosition())
969 ScrollableArea::scrollToOffsetWithoutAnimation(desiredOffset);
972 void PopupListBox::adjustScrollbarExistence()
974 bool needsVerticalScrollbar = contentsSize().height() > visibleHeight();
975 if (!!m_verticalScrollbar != needsVerticalScrollbar) {
976 setHasVerticalScrollbar(needsVerticalScrollbar);
981 void PopupListBox::updateScrollbarGeometry()
983 if (m_verticalScrollbar) {
984 int clientHeight = visibleHeight();
985 IntRect oldRect(m_verticalScrollbar->frameRect());
986 IntRect vBarRect(shouldPlaceVerticalScrollbarOnLeft() ? 0 : (width() - m_verticalScrollbar->width()),
987 0, m_verticalScrollbar->width(), height());
988 m_verticalScrollbar->setFrameRect(vBarRect);
989 if (oldRect != m_verticalScrollbar->frameRect())
990 m_verticalScrollbar->invalidate();
992 m_verticalScrollbar->setEnabled(contentsSize().height() > clientHeight);
993 m_verticalScrollbar->setProportion(clientHeight, contentsSize().height());
994 m_verticalScrollbar->offsetDidChange();
995 // NOTE: PopupListBox does not support suppressing scrollbars.
999 IntPoint PopupListBox::convertChildToSelf(const Widget* child, const IntPoint& point) const
1001 // NOTE: m_verticalScrollbar is the only child.
1002 IntPoint newPoint = point;
1003 newPoint.moveBy(child->location());
1007 IntPoint PopupListBox::convertSelfToChild(const Widget* child, const IntPoint& point) const
1009 // NOTE: m_verticalScrollbar is the only child.
1010 IntPoint newPoint = point;
1011 newPoint.moveBy(-child->location());
1015 int PopupListBox::scrollSize(ScrollbarOrientation orientation) const
1017 return (orientation == HorizontalScrollbar || !m_verticalScrollbar) ?
1018 0 : m_verticalScrollbar->totalSize() - m_verticalScrollbar->visibleSize();
1021 void PopupListBox::setScrollOffset(const IntPoint& newOffset)
1023 // NOTE: We do not support any "fast path" for scrolling. When the scroll
1024 // offset changes, we just repaint the whole popup.
1025 IntSize scrollDelta = newOffset - m_scrollOffset;
1026 if (scrollDelta == IntSize())
1028 m_scrollOffset = newOffset;
1030 if (HostWindow* window = hostWindow()) {
1031 IntRect clipRect = windowClipRect();
1032 IntRect updateRect = clipRect;
1033 updateRect.intersect(convertToContainingWindow(IntRect((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) ? verticalScrollbar()->width() : 0, 0, visibleWidth(), visibleHeight())));
1034 window->invalidateContentsForSlowScroll(updateRect);
1038 IntPoint PopupListBox::maximumScrollPosition() const
1040 IntPoint maximumOffset(contentsSize().width() - visibleWidth() - scrollOrigin().x(), contentsSize().height() - visibleHeight() - scrollOrigin().y());
1041 maximumOffset.clampNegativeToZero();
1042 return maximumOffset;
1045 IntPoint PopupListBox::minimumScrollPosition() const
1047 return IntPoint(-scrollOrigin().x(), -scrollOrigin().y());
1050 } // namespace blink