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.
31 #include "PopupListBox.h"
34 #include "FontSelector.h"
35 #include "FramelessScrollViewClient.h"
36 #include "GraphicsContext.h"
38 #include "KeyboardCodes.h"
39 #include "PlatformKeyboardEvent.h"
40 #include "PlatformMouseEvent.h"
41 #include "PlatformScreen.h"
42 #include "PlatformWheelEvent.h"
43 #include "PopupContainer.h"
44 #include "PopupMenuChromium.h"
45 #include "PopupMenuClient.h"
46 #include "RenderTheme.h"
47 #include "ScrollbarTheme.h"
48 #include "StringTruncator.h"
51 #include <wtf/CurrentTime.h>
53 #if ENABLE(GESTURE_EVENTS)
54 #include "PlatformGestureEvent.h"
57 #if ENABLE(TOUCH_EVENTS)
58 #include "PlatformTouchEvent.h"
65 using namespace Unicode;
67 PopupListBox::PopupListBox(PopupMenuClient* client, const PopupContainerSettings& settings)
68 : m_settings(settings)
71 , m_acceptedIndexOnAbandon(-1)
74 , m_maxHeight(kMaxHeight)
75 , m_popupClient(client)
78 , m_maxWindowWidth(std::numeric_limits<int>::max())
80 setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
83 bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
85 Scrollbar* scrollbar = scrollbarAtPoint(event.pos());
87 m_capturingScrollbar = scrollbar;
88 m_capturingScrollbar->mouseDown(event);
92 if (!isPointInBounds(event.pos()))
98 bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
100 if (m_capturingScrollbar) {
101 m_capturingScrollbar->mouseMoved(event);
105 Scrollbar* scrollbar = scrollbarAtPoint(event.pos());
106 if (m_lastScrollbarUnderMouse != scrollbar) {
107 // Send mouse exited to the old scrollbar.
108 if (m_lastScrollbarUnderMouse)
109 m_lastScrollbarUnderMouse->mouseExited();
110 m_lastScrollbarUnderMouse = scrollbar;
114 scrollbar->mouseMoved(event);
118 if (!isPointInBounds(event.pos()))
121 selectIndex(pointToRowIndex(event.pos()));
125 bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
127 if (m_capturingScrollbar) {
128 m_capturingScrollbar->mouseUp();
129 m_capturingScrollbar = 0;
133 if (!isPointInBounds(event.pos()))
136 // Need to check before calling acceptIndex(), because m_popupClient might be removed in acceptIndex() calling because of event handler.
137 bool isSelectPopup = m_popupClient->menuStyle().menuType() == PopupMenuStyle::SelectPopup;
138 if (acceptIndex(pointToRowIndex(event.pos())) && m_focusedNode && isSelectPopup) {
139 m_focusedNode->dispatchMouseEvent(event, eventNames().mouseupEvent);
140 m_focusedNode->dispatchMouseEvent(event, eventNames().clickEvent);
142 // Clear m_focusedNode here, because we cannot clear in hidePopup() which is called before dispatchMouseEvent() is called.
149 bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
151 if (!isPointInBounds(event.pos())) {
156 // Pass it off to the scroll view.
157 // Sadly, WebCore devs don't understand the whole "const" thing.
158 wheelEvent(const_cast<PlatformWheelEvent&>(event));
162 // Should be kept in sync with handleKeyEvent().
163 bool PopupListBox::isInterestedInEventForKey(int keyCode)
181 #if ENABLE(TOUCH_EVENTS)
182 bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&)
188 #if ENABLE(GESTURE_RECOGNIZER)
189 bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&)
195 static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
197 // Check whether the event is a character-typed event or not.
198 // We use RawKeyDown/Char/KeyUp event scheme on all platforms,
199 // so PlatformKeyboardEvent::Char (not RawKeyDown) type event
200 // is considered as character type event.
201 return event.type() == PlatformKeyboardEvent::Char;
204 bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
206 if (event.type() == PlatformKeyboardEvent::KeyUp)
209 if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
212 switch (event.windowsVirtualKeyCode()) {
214 abandon(); // may delete this
217 if (m_selectedIndex == -1) {
219 // Don't eat the enter if nothing is selected.
222 acceptIndex(m_selectedIndex); // may delete this
226 // We have to forward only shift + up combination to focused node when autofill popup.
227 // Because all characters from the cursor to the start of the text area should selected when you press shift + up arrow.
228 // shift + down should be the similar way to shift + up.
229 if (event.modifiers() && m_popupClient->menuStyle().menuType() == PopupMenuStyle::AutofillPopup)
230 m_focusedNode->dispatchKeyEvent(event);
231 else if (event.windowsVirtualKeyCode() == VKEY_UP)
237 adjustSelectedIndex(-m_visibleRows);
240 adjustSelectedIndex(m_visibleRows);
243 adjustSelectedIndex(-m_selectedIndex);
246 adjustSelectedIndex(m_items.size());
249 if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
250 && isPrintableChar(event.windowsVirtualKeyCode())
251 && isCharacterTypeEvent(event))
252 typeAheadFind(event);
256 if (m_originalIndex != m_selectedIndex) {
257 // Keyboard events should update the selection immediately (but we don't
258 // want to fire the onchange event until the popup is closed, to match
259 // IE). We change the original index so we revert to that when the
261 if (m_settings.acceptOnAbandon)
262 m_acceptedIndexOnAbandon = m_selectedIndex;
264 setOriginalIndex(m_selectedIndex);
265 if (m_settings.setTextOnIndexChange)
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 // From HTMLSelectElement.cpp
293 static String stripLeadingWhiteSpace(const String& string)
295 int length = string.length();
297 for (i = 0; i < length; ++i)
298 if (string[i] != noBreakSpace
299 && (string[i] <= 0x7F ? !isspace(string[i]) : (direction(string[i]) != WhiteSpaceNeutral)))
302 return string.substring(i, length - i);
305 // From HTMLSelectElement.cpp, with modifications
306 void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
308 TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
309 TimeStamp delta = now - m_lastCharTime;
311 // Reset the time when user types in a character. The time gap between
312 // last character and the current character is used to indicate whether
313 // user typed in a string or just a character as the search prefix.
314 m_lastCharTime = now;
316 UChar c = event.windowsVirtualKeyCode();
319 int searchStartOffset = 1;
320 if (delta > kTypeAheadTimeoutMs) {
321 m_typedString = prefix = String(&c, 1);
324 m_typedString.append(c);
326 if (c == m_repeatingChar)
327 // The user is likely trying to cycle through all the items starting with this character, so just search on the character
328 prefix = String(&c, 1);
331 prefix = m_typedString;
332 searchStartOffset = 0;
336 // Compute a case-folded copy of the prefix string before beginning the search for
337 // a matching element. This code uses foldCase to work around the fact that
338 // String::startWith does not fold non-ASCII characters. This code can be changed
339 // to use startWith once that is fixed.
340 String prefixWithCaseFolded(prefix.foldCase());
341 int itemCount = numItems();
342 int index = (max(0, m_selectedIndex) + searchStartOffset) % itemCount;
343 for (int i = 0; i < itemCount; i++, index = (index + 1) % itemCount) {
344 if (!isSelectableItem(index))
347 if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
354 void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
356 // adjust coords for scrolled frame
357 IntRect r = intersection(rect, frameRect());
358 int tx = x() - scrollX();
359 int ty = y() - scrollY();
363 // set clip rect to match revised damage rect
365 gc->translate(static_cast<float>(tx), static_cast<float>(ty));
368 // FIXME: Can we optimize scrolling to not require repainting the entire
369 // window? Should we?
370 for (int i = 0; i < numItems(); ++i)
373 // Special case for an empty popup.
375 gc->fillRect(r, Color::white, ColorSpaceDeviceRGB);
379 ScrollView::paint(gc, rect);
382 static const int separatorPadding = 4;
383 static const int separatorHeight = 1;
385 void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
387 // This code is based largely on RenderListBox::paint* methods.
389 IntRect rowRect = getRowBounds(rowIndex);
390 if (!rowRect.intersects(rect))
393 PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
396 Color backColor, textColor, labelColor;
397 if (rowIndex == m_selectedIndex) {
398 backColor = RenderTheme::defaultTheme()->activeListBoxSelectionBackgroundColor();
399 textColor = RenderTheme::defaultTheme()->activeListBoxSelectionForegroundColor();
400 labelColor = textColor;
402 backColor = style.backgroundColor();
403 textColor = style.foregroundColor();
404 // FIXME: for now the label color is hard-coded. It should be added to
405 // the PopupMenuStyle.
406 labelColor = Color(115, 115, 115);
409 // If we have a transparent background, make sure it has a color to blend
411 if (backColor.hasAlpha())
412 gc->fillRect(rowRect, Color::white, ColorSpaceDeviceRGB);
414 gc->fillRect(rowRect, backColor, ColorSpaceDeviceRGB);
416 // It doesn't look good but Autofill requires special style for separator.
417 // Autofill doesn't have padding and #dcdcdc color.
418 if (m_popupClient->itemIsSeparator(rowIndex)) {
419 int padding = style.menuType() == PopupMenuStyle::AutofillPopup ? 0 : separatorPadding;
420 IntRect separatorRect(
421 rowRect.x() + padding,
422 rowRect.y() + (rowRect.height() - separatorHeight) / 2,
423 rowRect.width() - 2 * padding, separatorHeight);
424 gc->fillRect(separatorRect, style.menuType() == PopupMenuStyle::AutofillPopup ? Color(0xdc, 0xdc, 0xdc) : textColor, ColorSpaceDeviceRGB);
428 if (!style.isVisible())
431 gc->setFillColor(textColor, ColorSpaceDeviceRGB);
433 Font itemFont = getRowFont(rowIndex);
434 // FIXME: http://crbug.com/19872 We should get the padding of individual option
435 // elements. This probably implies changes to PopupMenuClient.
436 bool rightAligned = m_popupClient->menuStyle().textDirection() == RTL;
440 maxWidth = rowRect.width() - max(0, m_popupClient->clientPaddingRight() - m_popupClient->clientInsetRight());
442 textX = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft());
443 maxWidth = rowRect.width() - textX;
445 // Prepare text to be drawn.
446 String itemText = m_popupClient->itemText(rowIndex);
447 String itemLabel = m_popupClient->itemLabel(rowIndex);
448 String itemIcon = m_popupClient->itemIcon(rowIndex);
449 if (m_settings.restrictWidthOfListBox) { // Truncate strings to fit in.
450 // FIXME: We should leftTruncate for the rtl case.
451 // StringTruncator::leftTruncate would have to be implemented.
452 String str = StringTruncator::rightTruncate(itemText, maxWidth, itemFont);
453 if (str != itemText) {
455 // Don't display the label or icon, we already don't have enough room for the item text.
458 } else if (!itemLabel.isEmpty()) {
459 int availableWidth = maxWidth - kTextToLabelPadding -
460 StringTruncator::width(itemText, itemFont);
461 itemLabel = StringTruncator::rightTruncate(itemLabel, availableWidth, itemFont);
465 // Prepare the directionality to draw text.
466 TextRun textRun(itemText.characters(), itemText.length(), false, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
467 // If the text is right-to-left, make it right-aligned by adjusting its
468 // beginning position.
470 textX += maxWidth - itemFont.width(textRun);
472 // Draw the item text.
473 int textY = rowRect.y() + itemFont.fontMetrics().ascent() + (rowRect.height() - itemFont.fontMetrics().height()) / 2;
474 gc->drawBidiText(itemFont, textRun, IntPoint(textX, textY));
476 // We are using the left padding as the right padding includes room for the scroll-bar which
477 // does not show in this case.
478 int rightPadding = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft());
479 int remainingWidth = rowRect.width() - rightPadding;
481 // Draw the icon if applicable.
482 RefPtr<Image> image(Image::loadPlatformResource(itemIcon.utf8().data()));
483 if (image && !image->isNull()) {
484 IntRect imageRect = image->rect();
485 remainingWidth -= (imageRect.width() + kLabelToIconPadding);
486 imageRect.setX(rowRect.width() - rightPadding - imageRect.width());
487 imageRect.setY(rowRect.y() + (rowRect.height() - imageRect.height()) / 2);
488 gc->drawImage(image.get(), ColorSpaceDeviceRGB, imageRect);
491 // Draw the the label if applicable.
492 if (itemLabel.isEmpty())
495 // Autofill label is 0.9 smaller than regular font size.
496 if (style.menuType() == PopupMenuStyle::AutofillPopup) {
497 itemFont = m_popupClient->itemStyle(rowIndex).font();
498 FontDescription d = itemFont.fontDescription();
499 d.setComputedSize(d.computedSize() * 0.9);
500 itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
504 TextRun labelTextRun(itemLabel.characters(), itemLabel.length(), false, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
506 textX = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft());
508 textX = remainingWidth - itemFont.width(labelTextRun);
510 gc->setFillColor(labelColor, ColorSpaceDeviceRGB);
511 gc->drawBidiText(itemFont, labelTextRun, IntPoint(textX, textY));
514 Font PopupListBox::getRowFont(int rowIndex)
516 Font itemFont = m_popupClient->itemStyle(rowIndex).font();
517 if (m_popupClient->itemIsLabel(rowIndex)) {
518 // Bold-ify labels (ie, an <optgroup> heading).
519 FontDescription d = itemFont.fontDescription();
520 d.setWeight(FontWeightBold);
521 Font font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
529 void PopupListBox::abandon()
531 RefPtr<PopupListBox> keepAlive(this);
533 m_selectedIndex = m_originalIndex;
537 if (m_acceptedIndexOnAbandon >= 0) {
539 m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
540 m_acceptedIndexOnAbandon = -1;
544 int PopupListBox::pointToRowIndex(const IntPoint& point)
546 int y = scrollY() + point.y();
548 // FIXME: binary search if perf matters.
549 for (int i = 0; i < numItems(); ++i) {
550 if (y < m_items[i]->yOffset)
555 if (y < contentsHeight())
556 return m_items.size()-1;
561 bool PopupListBox::acceptIndex(int index)
563 // Clear m_acceptedIndexOnAbandon once user accepts the selected index.
564 if (m_acceptedIndexOnAbandon >= 0)
565 m_acceptedIndexOnAbandon = -1;
567 if (index >= numItems())
572 // Enter pressed with no selection, just close the popup.
578 if (isSelectableItem(index)) {
579 RefPtr<PopupListBox> keepAlive(this);
581 // Hide ourselves first since valueChanged may have numerous side-effects.
584 // Tell the <select> PopupMenuClient what index was selected.
585 m_popupClient->valueChanged(index);
593 void PopupListBox::selectIndex(int index)
595 if (index < 0 || index >= numItems())
598 bool isSelectable = isSelectableItem(index);
599 if (index != m_selectedIndex && isSelectable) {
600 invalidateRow(m_selectedIndex);
601 m_selectedIndex = index;
602 invalidateRow(m_selectedIndex);
604 scrollToRevealSelection();
605 m_popupClient->selectionChanged(m_selectedIndex);
606 } else if (!isSelectable)
610 void PopupListBox::setOriginalIndex(int index)
612 m_originalIndex = m_selectedIndex = index;
615 int PopupListBox::getRowHeight(int index)
618 return PopupMenuChromium::minimumRowHeight();
620 if (m_popupClient->itemStyle(index).isDisplayNone())
621 return PopupMenuChromium::minimumRowHeight();
623 // Separator row height is the same size as itself.
624 if (m_popupClient->itemIsSeparator(index))
625 return max(separatorHeight, PopupMenuChromium::minimumRowHeight());
627 String icon = m_popupClient->itemIcon(index);
628 RefPtr<Image> image(Image::loadPlatformResource(icon.utf8().data()));
630 int fontHeight = getRowFont(index).fontMetrics().height();
631 int iconHeight = (image && !image->isNull()) ? image->rect().height() : 0;
633 int linePaddingHeight = m_popupClient->menuStyle().menuType() == PopupMenuStyle::AutofillPopup ? kLinePaddingHeight : 0;
634 int calculatedRowHeight = max(fontHeight, iconHeight) + linePaddingHeight * 2;
635 return max(calculatedRowHeight, PopupMenuChromium::minimumRowHeight());
638 IntRect PopupListBox::getRowBounds(int index)
641 return IntRect(0, 0, visibleWidth(), getRowHeight(index));
643 return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
646 void PopupListBox::invalidateRow(int index)
651 // Invalidate in the window contents, as FramelessScrollView::invalidateRect
652 // paints in the window coordinates.
653 invalidateRect(contentsToWindow(getRowBounds(index)));
656 void PopupListBox::scrollToRevealRow(int index)
661 IntRect rowRect = getRowBounds(index);
663 if (rowRect.y() < scrollY()) {
664 // Row is above current scroll position, scroll up.
665 ScrollView::setScrollPosition(IntPoint(0, rowRect.y()));
666 } else if (rowRect.maxY() > scrollY() + visibleHeight()) {
667 // Row is below current scroll position, scroll down.
668 ScrollView::setScrollPosition(IntPoint(0, rowRect.maxY() - visibleHeight()));
672 bool PopupListBox::isSelectableItem(int index)
674 ASSERT(index >= 0 && index < numItems());
675 return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
678 void PopupListBox::clearSelection()
680 if (m_selectedIndex != -1) {
681 invalidateRow(m_selectedIndex);
682 m_selectedIndex = -1;
683 m_popupClient->selectionCleared();
687 void PopupListBox::selectNextRow()
689 if (!m_settings.loopSelectionNavigation || m_selectedIndex != numItems() - 1) {
690 adjustSelectedIndex(1);
694 // We are moving past the last item, no row should be selected.
698 void PopupListBox::selectPreviousRow()
700 if (!m_settings.loopSelectionNavigation || m_selectedIndex > 0) {
701 adjustSelectedIndex(-1);
705 if (!m_selectedIndex) {
706 // We are moving past the first item, clear the selection.
711 // No row is selected, jump to the last item.
712 selectIndex(numItems() - 1);
713 scrollToRevealSelection();
716 void PopupListBox::adjustSelectedIndex(int delta)
718 int targetIndex = m_selectedIndex + delta;
719 targetIndex = min(max(targetIndex, 0), numItems() - 1);
720 if (!isSelectableItem(targetIndex)) {
721 // We didn't land on an option. Try to find one.
722 // We try to select the closest index to target, prioritizing any in
723 // the range [current, target].
725 int dir = delta > 0 ? 1 : -1;
726 int testIndex = m_selectedIndex;
727 int bestIndex = m_selectedIndex;
728 bool passedTarget = false;
729 while (testIndex >= 0 && testIndex < numItems()) {
730 if (isSelectableItem(testIndex))
731 bestIndex = testIndex;
732 if (testIndex == targetIndex)
734 if (passedTarget && bestIndex != m_selectedIndex)
740 // Pick the best index, which may mean we don't change.
741 targetIndex = bestIndex;
744 // Select the new index, and ensure its visible. We do this regardless of
745 // whether the selection changed to ensure keyboard events always bring the
746 // selection into view.
747 selectIndex(targetIndex);
748 scrollToRevealSelection();
751 void PopupListBox::hidePopup()
754 PopupContainer* container = static_cast<PopupContainer*>(parent());
755 if (container->client())
756 container->client()->popupClosed(container);
757 container->notifyPopupHidden();
761 m_popupClient->popupDidHide();
764 void PopupListBox::updateFromElement()
768 int size = m_popupClient->listSize();
769 for (int i = 0; i < size; ++i) {
770 PopupItem::Type type;
771 if (m_popupClient->itemIsSeparator(i))
772 type = PopupItem::TypeSeparator;
773 else if (m_popupClient->itemIsLabel(i))
774 type = PopupItem::TypeGroup;
776 type = PopupItem::TypeOption;
777 m_items.append(new PopupItem(m_popupClient->itemText(i), type));
778 m_items[i]->enabled = isSelectableItem(i);
779 PopupMenuStyle style = m_popupClient->itemStyle(i);
780 m_items[i]->textDirection = style.textDirection();
781 m_items[i]->hasTextDirectionOverride = style.hasTextDirectionOverride();
784 m_selectedIndex = m_popupClient->selectedIndex();
785 setOriginalIndex(m_selectedIndex);
790 void PopupListBox::setMaxWidthAndLayout(int maxWidth)
792 m_maxWindowWidth = maxWidth;
796 void PopupListBox::layout()
798 bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
800 // Size our child items.
802 int paddingWidth = 0;
803 int lineEndPaddingWidth = 0;
805 for (int i = 0; i < numItems(); ++i) {
806 // Place the item vertically.
807 m_items[i]->yOffset = y;
808 if (m_popupClient->itemStyle(i).isDisplayNone())
810 y += getRowHeight(i);
812 // Ensure the popup is wide enough to fit this item.
813 Font itemFont = getRowFont(i);
814 String text = m_popupClient->itemText(i);
815 String label = m_popupClient->itemLabel(i);
816 String icon = m_popupClient->itemIcon(i);
817 RefPtr<Image> iconImage(Image::loadPlatformResource(icon.utf8().data()));
820 width = itemFont.width(TextRun(text));
821 if (!label.isEmpty()) {
823 width += kTextToLabelPadding;
824 width += itemFont.width(TextRun(label));
826 if (iconImage && !iconImage->isNull()) {
828 width += kLabelToIconPadding;
829 width += iconImage->rect().width();
832 baseWidth = max(baseWidth, width);
833 // FIXME: http://b/1210481 We should get the padding of individual option elements.
834 paddingWidth = max(paddingWidth,
835 m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight());
836 lineEndPaddingWidth = max(lineEndPaddingWidth,
837 isRightAligned ? m_popupClient->clientPaddingLeft() : m_popupClient->clientPaddingRight());
840 // Calculate scroll bar width.
841 int windowHeight = 0;
842 m_visibleRows = min(numItems(), kMaxVisibleRows);
844 for (int i = 0; i < m_visibleRows; ++i) {
845 int rowHeight = getRowHeight(i);
847 // Only clip the window height for non-Mac platforms.
848 if (windowHeight + rowHeight > m_maxHeight) {
853 windowHeight += rowHeight;
856 // Set our widget and scrollable contents sizes.
857 int scrollbarWidth = 0;
858 if (m_visibleRows < numItems()) {
859 scrollbarWidth = ScrollbarTheme::nativeTheme()->scrollbarThickness();
861 // Use kMinEndOfLinePadding when there is a scrollbar so that we use
862 // as much as (lineEndPaddingWidth - kMinEndOfLinePadding) padding
863 // space for scrollbar and allow user to use CSS padding to make the
864 // popup listbox align with the select element.
865 paddingWidth = paddingWidth - lineEndPaddingWidth + kMinEndOfLinePadding;
870 if (m_settings.restrictWidthOfListBox) {
871 windowWidth = m_baseWidth;
872 contentWidth = m_baseWidth - scrollbarWidth;
874 windowWidth = baseWidth + scrollbarWidth + paddingWidth;
875 if (windowWidth > m_maxWindowWidth) {
876 // windowWidth exceeds m_maxWindowWidth, so we have to clip.
877 windowWidth = m_maxWindowWidth;
878 baseWidth = windowWidth - scrollbarWidth - paddingWidth;
879 m_baseWidth = baseWidth;
881 contentWidth = windowWidth - scrollbarWidth;
883 if (windowWidth < m_baseWidth) {
884 windowWidth = m_baseWidth;
885 contentWidth = m_baseWidth - scrollbarWidth;
887 m_baseWidth = baseWidth;
890 resize(windowWidth, windowHeight);
891 setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
894 scrollToRevealSelection();
899 void PopupListBox::clear()
901 for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it)
906 bool PopupListBox::isPointInBounds(const IntPoint& point)
908 return numItems() && IntRect(0, 0, width(), height()).contains(point);
911 } // namespace WebCore