PopupMenuChromium.cpp [plain text]
#include "config.h"
#include "PopupMenuChromium.h"
#include "Chrome.h"
#include "ChromeClientChromium.h"
#include "Font.h"
#include "FontSelector.h"
#include "FrameView.h"
#include "Frame.h"
#include "FramelessScrollView.h"
#include "FramelessScrollViewClient.h"
#include "GraphicsContext.h"
#include "IntRect.h"
#include "KeyboardCodes.h"
#include "Page.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformMouseEvent.h"
#include "PlatformScreen.h"
#include "PlatformWheelEvent.h"
#include "PopupMenuClient.h"
#include "RenderTheme.h"
#include "ScrollbarTheme.h"
#include "StringTruncator.h"
#include "SystemTime.h"
#include "TextRun.h"
#include "UserGestureIndicator.h"
#include <wtf/CurrentTime.h>
#include <wtf/unicode/CharacterNames.h>
using namespace WTF;
using namespace Unicode;
using std::min;
using std::max;
namespace WebCore {
typedef unsigned long long TimeStamp;
static const int kMaxVisibleRows = 20;
static const int kMaxHeight = 500;
static const int kBorderSize = 1;
static const int kTextToLabelPadding = 10;
static const int kLabelToIconPadding = 5;
static const int kMinEndOfLinePadding = 2;
static const TimeStamp kTypeAheadTimeoutMs = 1000;
static const int kLinePaddingHeight = 3;
static const PopupContainerSettings dropDownSettings = {
true, true, false, false };
class PopupListBox : public FramelessScrollView {
public:
static PassRefPtr<PopupListBox> create(PopupMenuClient* client, const PopupContainerSettings& settings)
{
return adoptRef(new PopupListBox(client, settings));
}
virtual void paint(GraphicsContext*, const IntRect&);
virtual bool handleMouseDownEvent(const PlatformMouseEvent&);
virtual bool handleMouseMoveEvent(const PlatformMouseEvent&);
virtual bool handleMouseReleaseEvent(const PlatformMouseEvent&);
virtual bool handleWheelEvent(const PlatformWheelEvent&);
virtual bool handleKeyEvent(const PlatformKeyboardEvent&);
virtual HostWindow* hostWindow() const;
void hidePopup();
void updateFromElement();
void clear();
void setOriginalIndex(int index);
int selectedIndex() const { return m_selectedIndex; }
void adjustSelectedIndex(int delta);
int numItems() const { return static_cast<int>(m_items.size()); }
void setBaseWidth(int width) { m_baseWidth = width; }
void layout();
bool isInterestedInEventForKey(int keyCode);
int getRowHeight(int index);
void setMaxHeight(int maxHeight) { m_maxHeight = maxHeight; }
void disconnectClient() { m_popupClient = 0; }
const Vector<PopupItem*>& items() const { return m_items; }
private:
friend class PopupContainer;
friend class RefCounted<PopupListBox>;
PopupListBox(PopupMenuClient* client, const PopupContainerSettings& settings)
: m_settings(settings)
, m_originalIndex(0)
, m_selectedIndex(0)
, m_acceptedIndexOnAbandon(-1)
, m_visibleRows(0)
, m_baseWidth(0)
, m_maxHeight(kMaxHeight)
, m_popupClient(client)
, m_repeatingChar(0)
, m_lastCharTime(0)
{
setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
}
~PopupListBox()
{
clear();
}
void abandon();
bool isSelectableItem(int index);
void selectIndex(int index);
void acceptIndex(int index);
void clearSelection();
void scrollToRevealRow(int index);
void scrollToRevealSelection() { scrollToRevealRow(m_selectedIndex); }
void invalidateRow(int index);
IntRect getRowBounds(int index);
int pointToRowIndex(const IntPoint&);
void paintRow(GraphicsContext*, const IntRect&, int rowIndex);
bool isPointInBounds(const IntPoint&);
void typeAheadFind(const PlatformKeyboardEvent&);
Font getRowFont(int index);
void selectPreviousRow();
void selectNextRow();
PopupContainerSettings m_settings;
int m_originalIndex;
int m_selectedIndex;
int m_acceptedIndexOnAbandon;
int m_visibleRows;
int m_baseWidth;
int m_maxHeight;
Vector<PopupItem*> m_items;
PopupMenuClient* m_popupClient;
RefPtr<Scrollbar> m_capturingScrollbar;
RefPtr<Scrollbar> m_lastScrollbarUnderMouse;
String m_typedString;
UChar m_repeatingChar;
TimeStamp m_lastCharTime;
};
static PlatformMouseEvent constructRelativeMouseEvent(const PlatformMouseEvent& e,
FramelessScrollView* parent,
FramelessScrollView* child)
{
IntPoint pos = parent->convertSelfToChild(child, e.pos());
PlatformMouseEvent relativeEvent = e;
IntPoint& relativePos = const_cast<IntPoint&>(relativeEvent.pos());
relativePos.setX(pos.x());
relativePos.setY(pos.y());
return relativeEvent;
}
static PlatformWheelEvent constructRelativeWheelEvent(const PlatformWheelEvent& e,
FramelessScrollView* parent,
FramelessScrollView* child)
{
IntPoint pos = parent->convertSelfToChild(child, e.pos());
PlatformWheelEvent relativeEvent = e;
IntPoint& relativePos = const_cast<IntPoint&>(relativeEvent.pos());
relativePos.setX(pos.x());
relativePos.setY(pos.y());
return relativeEvent;
}
PassRefPtr<PopupContainer> PopupContainer::create(PopupMenuClient* client,
PopupType popupType,
const PopupContainerSettings& settings)
{
return adoptRef(new PopupContainer(client, popupType, settings));
}
PopupContainer::PopupContainer(PopupMenuClient* client,
PopupType popupType,
const PopupContainerSettings& settings)
: m_listBox(PopupListBox::create(client, settings))
, m_settings(settings)
, m_popupType(popupType)
, m_popupOpen(false)
{
setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
}
PopupContainer::~PopupContainer()
{
if (m_listBox && m_listBox->parent())
removeChild(m_listBox.get());
}
IntRect PopupContainer::layoutAndCalculateWidgetRect(int targetControlHeight, const IntPoint& popupInitialCoordinate)
{
m_listBox->setMaxHeight(kMaxHeight);
int rightOffset = layoutAndGetRightOffset();
IntSize targetSize(m_listBox->width() + kBorderSize * 2,
m_listBox->height() + kBorderSize * 2);
IntRect widgetRect;
ChromeClientChromium* chromeClient = chromeClientChromium();
if (chromeClient) {
FloatRect screen = screenAvailableRect(m_frameView.get());
widgetRect = chromeClient->windowToScreen(IntRect(popupInitialCoordinate.x() + rightOffset, popupInitialCoordinate.y(), targetSize.width(), targetSize.height()));
FloatRect windowRect = chromeClient->windowRect();
if (windowRect.x() >= screen.x() && windowRect.maxX() <= screen.maxX()) {
if (m_listBox->m_popupClient->menuStyle().textDirection() == RTL && widgetRect.x() < screen.x()) {
widgetRect.setWidth(widgetRect.maxX() - screen.x());
widgetRect.setX(screen.x());
} else if (widgetRect.maxX() > screen.maxX())
widgetRect.setWidth(screen.maxX() - widgetRect.x());
}
if (widgetRect.maxY() > static_cast<int>(screen.maxY())) {
if (widgetRect.y() - widgetRect.height() - targetControlHeight > 0) {
widgetRect.move(0, -(widgetRect.height() + targetControlHeight));
} else {
int spaceAbove = widgetRect.y() - targetControlHeight;
int spaceBelow = screen.maxY() - widgetRect.y();
if (spaceAbove > spaceBelow)
m_listBox->setMaxHeight(spaceAbove);
else
m_listBox->setMaxHeight(spaceBelow);
layoutAndGetRightOffset();
IntRect frameInScreen = chromeClient->windowToScreen(frameRect());
widgetRect.setY(frameInScreen.y());
widgetRect.setHeight(frameInScreen.height());
if (spaceAbove > spaceBelow)
widgetRect.move(0, -(widgetRect.height() + targetControlHeight));
}
}
}
return widgetRect;
}
void PopupContainer::showPopup(FrameView* view)
{
m_frameView = view;
ChromeClientChromium* chromeClient = chromeClientChromium();
if (chromeClient) {
IntRect popupRect = frameRect();
chromeClient->popupOpened(this, layoutAndCalculateWidgetRect(popupRect.height(), popupRect.location()), false);
m_popupOpen = true;
}
if (!m_listBox->parent())
addChild(m_listBox.get());
m_listBox->setVerticalScrollbarMode(ScrollbarAuto);
m_listBox->scrollToRevealSelection();
invalidate();
}
void PopupContainer::hidePopup()
{
listBox()->hidePopup();
}
void PopupContainer::notifyPopupHidden()
{
if (!m_popupOpen)
return;
m_popupOpen = false;
chromeClientChromium()->popupClosed(this);
}
int PopupContainer::layoutAndGetRightOffset()
{
m_listBox->layout();
m_listBox->move(kBorderSize, kBorderSize);
int popupWidth = frameRect().width();
int listBoxWidth = m_listBox->width() + kBorderSize * 2;
resize(listBoxWidth, m_listBox->height() + kBorderSize * 2);
PopupMenuClient* popupClient = m_listBox->m_popupClient;
int rightOffset = 0;
if (popupClient) {
bool rightAligned = m_listBox->m_popupClient->menuStyle().textDirection() == RTL;
if (rightAligned)
rightOffset = popupWidth - listBoxWidth;
}
invalidate();
return rightOffset;
}
bool PopupContainer::handleMouseDownEvent(const PlatformMouseEvent& event)
{
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
return m_listBox->handleMouseDownEvent(
constructRelativeMouseEvent(event, this, m_listBox.get()));
}
bool PopupContainer::handleMouseMoveEvent(const PlatformMouseEvent& event)
{
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
return m_listBox->handleMouseMoveEvent(
constructRelativeMouseEvent(event, this, m_listBox.get()));
}
bool PopupContainer::handleMouseReleaseEvent(const PlatformMouseEvent& event)
{
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
return m_listBox->handleMouseReleaseEvent(
constructRelativeMouseEvent(event, this, m_listBox.get()));
}
bool PopupContainer::handleWheelEvent(const PlatformWheelEvent& event)
{
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
return m_listBox->handleWheelEvent(
constructRelativeWheelEvent(event, this, m_listBox.get()));
}
bool PopupContainer::handleKeyEvent(const PlatformKeyboardEvent& event)
{
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
return m_listBox->handleKeyEvent(event);
}
void PopupContainer::hide()
{
m_listBox->abandon();
}
void PopupContainer::paint(GraphicsContext* gc, const IntRect& rect)
{
IntRect r = intersection(rect, frameRect());
int tx = x();
int ty = y();
r.move(-tx, -ty);
gc->translate(static_cast<float>(tx), static_cast<float>(ty));
m_listBox->paint(gc, r);
gc->translate(-static_cast<float>(tx), -static_cast<float>(ty));
paintBorder(gc, rect);
}
void PopupContainer::paintBorder(GraphicsContext* gc, const IntRect& rect)
{
Color borderColor(127, 157, 185);
gc->setStrokeStyle(NoStroke);
gc->setFillColor(borderColor, ColorSpaceDeviceRGB);
int tx = x();
int ty = y();
gc->drawRect(IntRect(tx, ty, width(), kBorderSize));
gc->drawRect(IntRect(tx, ty, kBorderSize, height()));
gc->drawRect(IntRect(tx, ty + height() - kBorderSize, width(), kBorderSize));
gc->drawRect(IntRect(tx + width() - kBorderSize, ty, kBorderSize, height()));
}
bool PopupContainer::isInterestedInEventForKey(int keyCode)
{
return m_listBox->isInterestedInEventForKey(keyCode);
}
ChromeClientChromium* PopupContainer::chromeClientChromium()
{
return static_cast<ChromeClientChromium*>(m_frameView->frame()->page()->chrome()->client());
}
void PopupContainer::showInRect(const IntRect& r, FrameView* v, int index)
{
listBox()->setBaseWidth(max(r.width() - kBorderSize * 2, 0));
listBox()->updateFromElement();
IntPoint location = v->contentsToWindow(r.location());
location.move(0, r.height());
setFrameRect(IntRect(location, r.size()));
showPopup(v);
}
void PopupContainer::refresh(const IntRect& targetControlRect)
{
IntPoint location = m_frameView->contentsToWindow(targetControlRect.location());
location.move(0, targetControlRect.height());
listBox()->updateFromElement();
IntSize originalSize = size();
IntRect widgetRect = layoutAndCalculateWidgetRect(targetControlRect.height(), location);
if (originalSize != widgetRect.size())
setFrameRect(widgetRect);
invalidate();
}
int PopupContainer::selectedIndex() const
{
return m_listBox->selectedIndex();
}
int PopupContainer::menuItemHeight() const
{
return m_listBox->getRowHeight(0);
}
int PopupContainer::menuItemFontSize() const
{
return m_listBox->getRowFont(0).size();
}
PopupMenuStyle PopupContainer::menuStyle() const
{
return m_listBox->m_popupClient->menuStyle();
}
const WTF::Vector<PopupItem*>& PopupContainer:: popupData() const
{
return m_listBox->items();
}
bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
{
Scrollbar* scrollbar = scrollbarAtPoint(event.pos());
if (scrollbar) {
m_capturingScrollbar = scrollbar;
m_capturingScrollbar->mouseDown(event);
return true;
}
if (!isPointInBounds(event.pos()))
abandon();
return true;
}
bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
{
if (m_capturingScrollbar) {
m_capturingScrollbar->mouseMoved(event);
return true;
}
Scrollbar* scrollbar = scrollbarAtPoint(event.pos());
if (m_lastScrollbarUnderMouse != scrollbar) {
if (m_lastScrollbarUnderMouse)
m_lastScrollbarUnderMouse->mouseExited();
m_lastScrollbarUnderMouse = scrollbar;
}
if (scrollbar) {
scrollbar->mouseMoved(event);
return true;
}
if (!isPointInBounds(event.pos()))
return false;
selectIndex(pointToRowIndex(event.pos()));
return true;
}
bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
{
if (m_capturingScrollbar) {
m_capturingScrollbar->mouseUp();
m_capturingScrollbar = 0;
return true;
}
if (!isPointInBounds(event.pos()))
return true;
acceptIndex(pointToRowIndex(event.pos()));
return true;
}
bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
{
if (!isPointInBounds(event.pos())) {
abandon();
return true;
}
wheelEvent(const_cast<PlatformWheelEvent&>(event));
return true;
}
bool PopupListBox::isInterestedInEventForKey(int keyCode)
{
switch (keyCode) {
case VKEY_ESCAPE:
case VKEY_RETURN:
case VKEY_UP:
case VKEY_DOWN:
case VKEY_PRIOR:
case VKEY_NEXT:
case VKEY_HOME:
case VKEY_END:
case VKEY_TAB:
return true;
default:
return false;
}
}
static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
{
return event.type() == PlatformKeyboardEvent::Char;
}
bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
{
if (event.type() == PlatformKeyboardEvent::KeyUp)
return true;
if (numItems() == 0 && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
return true;
switch (event.windowsVirtualKeyCode()) {
case VKEY_ESCAPE:
abandon(); return true;
case VKEY_RETURN:
if (m_selectedIndex == -1) {
hidePopup();
return false;
}
acceptIndex(m_selectedIndex); return true;
case VKEY_UP:
selectPreviousRow();
break;
case VKEY_DOWN:
selectNextRow();
break;
case VKEY_PRIOR:
adjustSelectedIndex(-m_visibleRows);
break;
case VKEY_NEXT:
adjustSelectedIndex(m_visibleRows);
break;
case VKEY_HOME:
adjustSelectedIndex(-m_selectedIndex);
break;
case VKEY_END:
adjustSelectedIndex(m_items.size());
break;
default:
if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
&& isPrintableChar(event.windowsVirtualKeyCode())
&& isCharacterTypeEvent(event))
typeAheadFind(event);
break;
}
if (m_originalIndex != m_selectedIndex) {
if (m_settings.acceptOnAbandon)
m_acceptedIndexOnAbandon = m_selectedIndex;
setOriginalIndex(m_selectedIndex);
if (m_settings.setTextOnIndexChange)
m_popupClient->setTextFromItem(m_selectedIndex);
}
if (event.windowsVirtualKeyCode() == VKEY_TAB) {
if (m_selectedIndex >= 0) {
acceptIndex(m_selectedIndex); return false;
}
abandon();
return false;
}
return true;
}
HostWindow* PopupListBox::hostWindow() const
{
return parent() ? parent()->hostWindow() : 0;
}
static String stripLeadingWhiteSpace(const String& string)
{
int length = string.length();
int i;
for (i = 0; i < length; ++i)
if (string[i] != noBreakSpace
&& (string[i] <= 0x7F ? !isspace(string[i]) : (direction(string[i]) != WhiteSpaceNeutral)))
break;
return string.substring(i, length - i);
}
void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
{
TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
TimeStamp delta = now - m_lastCharTime;
m_lastCharTime = now;
UChar c = event.windowsVirtualKeyCode();
String prefix;
int searchStartOffset = 1;
if (delta > kTypeAheadTimeoutMs) {
m_typedString = prefix = String(&c, 1);
m_repeatingChar = c;
} else {
m_typedString.append(c);
if (c == m_repeatingChar)
prefix = String(&c, 1);
else {
m_repeatingChar = 0;
prefix = m_typedString;
searchStartOffset = 0;
}
}
String prefixWithCaseFolded(prefix.foldCase());
int itemCount = numItems();
int index = (max(0, m_selectedIndex) + searchStartOffset) % itemCount;
for (int i = 0; i < itemCount; i++, index = (index + 1) % itemCount) {
if (!isSelectableItem(index))
continue;
if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
selectIndex(index);
return;
}
}
}
void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
{
IntRect r = intersection(rect, frameRect());
int tx = x() - scrollX();
int ty = y() - scrollY();
r.move(-tx, -ty);
gc->save();
gc->translate(static_cast<float>(tx), static_cast<float>(ty));
gc->clip(r);
for (int i = 0; i < numItems(); ++i)
paintRow(gc, r, i);
if (numItems() == 0)
gc->fillRect(r, Color::white, ColorSpaceDeviceRGB);
gc->restore();
ScrollView::paint(gc, rect);
}
static const int separatorPadding = 4;
static const int separatorHeight = 1;
void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
{
IntRect rowRect = getRowBounds(rowIndex);
if (!rowRect.intersects(rect))
return;
PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
Color backColor, textColor, labelColor;
if (rowIndex == m_selectedIndex) {
backColor = RenderTheme::defaultTheme()->activeListBoxSelectionBackgroundColor();
textColor = RenderTheme::defaultTheme()->activeListBoxSelectionForegroundColor();
labelColor = textColor;
} else {
backColor = style.backgroundColor();
textColor = style.foregroundColor();
labelColor = Color(115, 115, 115);
}
if (backColor.hasAlpha())
gc->fillRect(rowRect, Color::white, ColorSpaceDeviceRGB);
gc->fillRect(rowRect, backColor, ColorSpaceDeviceRGB);
if (m_popupClient->itemIsSeparator(rowIndex)) {
int padding = style.menuType() == PopupMenuStyle::AutofillPopup ? 0 : separatorPadding;
IntRect separatorRect(
rowRect.x() + padding,
rowRect.y() + (rowRect.height() - separatorHeight) / 2,
rowRect.width() - 2 * padding, separatorHeight);
gc->fillRect(separatorRect, style.menuType() == PopupMenuStyle::AutofillPopup ? Color(0xdc, 0xdc, 0xdc) : textColor, ColorSpaceDeviceRGB);
return;
}
if (!style.isVisible())
return;
gc->setFillColor(textColor, ColorSpaceDeviceRGB);
Font itemFont = getRowFont(rowIndex);
bool rightAligned = m_popupClient->menuStyle().textDirection() == RTL;
int textX = 0;
int maxWidth = 0;
if (rightAligned)
maxWidth = rowRect.width() - max(0, m_popupClient->clientPaddingRight() - m_popupClient->clientInsetRight());
else {
textX = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft());
maxWidth = rowRect.width() - textX;
}
String itemText = m_popupClient->itemText(rowIndex);
String itemLabel = m_popupClient->itemLabel(rowIndex);
String itemIcon = m_popupClient->itemIcon(rowIndex);
if (m_settings.restrictWidthOfListBox) { String str = StringTruncator::rightTruncate(itemText, maxWidth, itemFont);
if (str != itemText) {
itemText = str;
itemLabel = "";
itemIcon = "";
} else if (!itemLabel.isEmpty()) {
int availableWidth = maxWidth - kTextToLabelPadding -
StringTruncator::width(itemText, itemFont);
itemLabel = StringTruncator::rightTruncate(itemLabel, availableWidth, itemFont);
}
}
TextRun textRun(itemText.characters(), itemText.length(), false, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
if (rightAligned)
textX += maxWidth - itemFont.width(textRun);
int textY = rowRect.y() + itemFont.fontMetrics().ascent() + (rowRect.height() - itemFont.fontMetrics().height()) / 2;
gc->drawBidiText(itemFont, textRun, IntPoint(textX, textY));
int rightPadding = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft());
int remainingWidth = rowRect.width() - rightPadding;
RefPtr<Image> image(Image::loadPlatformResource(itemIcon.utf8().data()));
if (image && !image->isNull()) {
IntRect imageRect = image->rect();
remainingWidth -= (imageRect.width() + kLabelToIconPadding);
imageRect.setX(rowRect.width() - rightPadding - imageRect.width());
imageRect.setY(rowRect.y() + (rowRect.height() - imageRect.height()) / 2);
gc->drawImage(image.get(), ColorSpaceDeviceRGB, imageRect);
}
if (itemLabel.isEmpty())
return;
if (style.menuType() == PopupMenuStyle::AutofillPopup) {
itemFont = m_popupClient->itemStyle(rowIndex).font();
FontDescription d = itemFont.fontDescription();
d.setComputedSize(d.computedSize() * 0.9);
itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
itemFont.update(0);
}
TextRun labelTextRun(itemLabel.characters(), itemLabel.length(), false, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
if (rightAligned)
textX = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft());
else
textX = remainingWidth - itemFont.width(labelTextRun);
gc->setFillColor(labelColor, ColorSpaceDeviceRGB);
gc->drawBidiText(itemFont, labelTextRun, IntPoint(textX, textY));
}
Font PopupListBox::getRowFont(int rowIndex)
{
Font itemFont = m_popupClient->itemStyle(rowIndex).font();
if (m_popupClient->itemIsLabel(rowIndex)) {
FontDescription d = itemFont.fontDescription();
d.setWeight(FontWeightBold);
Font font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
font.update(0);
return font;
}
return itemFont;
}
void PopupListBox::abandon()
{
RefPtr<PopupListBox> keepAlive(this);
m_selectedIndex = m_originalIndex;
hidePopup();
if (m_acceptedIndexOnAbandon >= 0) {
if (m_popupClient)
m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
m_acceptedIndexOnAbandon = -1;
}
}
int PopupListBox::pointToRowIndex(const IntPoint& point)
{
int y = scrollY() + point.y();
for (int i = 0; i < numItems(); ++i) {
if (y < m_items[i]->yOffset)
return i-1;
}
if (y < contentsHeight())
return m_items.size()-1;
return -1;
}
void PopupListBox::acceptIndex(int index)
{
if (m_acceptedIndexOnAbandon >= 0)
m_acceptedIndexOnAbandon = -1;
if (index >= numItems())
return;
if (index < 0) {
if (m_popupClient) {
hidePopup();
}
return;
}
if (isSelectableItem(index)) {
RefPtr<PopupListBox> keepAlive(this);
hidePopup();
m_popupClient->valueChanged(index);
}
}
void PopupListBox::selectIndex(int index)
{
if (index < 0 || index >= numItems())
return;
bool isSelectable = isSelectableItem(index);
if (index != m_selectedIndex && isSelectable) {
invalidateRow(m_selectedIndex);
m_selectedIndex = index;
invalidateRow(m_selectedIndex);
scrollToRevealSelection();
m_popupClient->selectionChanged(m_selectedIndex);
} else if (!isSelectable) {
clearSelection();
}
}
void PopupListBox::setOriginalIndex(int index)
{
m_originalIndex = m_selectedIndex = index;
}
int PopupListBox::getRowHeight(int index)
{
if (index < 0)
return 0;
if (m_popupClient->itemStyle(index).isDisplayNone())
return 0;
if (m_popupClient->itemIsSeparator(index))
return separatorHeight;
String icon = m_popupClient->itemIcon(index);
RefPtr<Image> image(Image::loadPlatformResource(icon.utf8().data()));
int fontHeight = getRowFont(index).fontMetrics().height();
int iconHeight = (image && !image->isNull()) ? image->rect().height() : 0;
int linePaddingHeight = m_popupClient->menuStyle().menuType() == PopupMenuStyle::AutofillPopup ? kLinePaddingHeight : 0;
return max(fontHeight, iconHeight) + linePaddingHeight * 2;
}
IntRect PopupListBox::getRowBounds(int index)
{
if (index < 0)
return IntRect(0, 0, visibleWidth(), getRowHeight(index));
return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
}
void PopupListBox::invalidateRow(int index)
{
if (index < 0)
return;
invalidateRect(contentsToWindow(getRowBounds(index)));
}
void PopupListBox::scrollToRevealRow(int index)
{
if (index < 0)
return;
IntRect rowRect = getRowBounds(index);
if (rowRect.y() < scrollY()) {
ScrollView::setScrollPosition(IntPoint(0, rowRect.y()));
} else if (rowRect.maxY() > scrollY() + visibleHeight()) {
ScrollView::setScrollPosition(IntPoint(0, rowRect.maxY() - visibleHeight()));
}
}
bool PopupListBox::isSelectableItem(int index)
{
ASSERT(index >= 0 && index < numItems());
return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
}
void PopupListBox::clearSelection()
{
if (m_selectedIndex != -1) {
invalidateRow(m_selectedIndex);
m_selectedIndex = -1;
m_popupClient->selectionCleared();
}
}
void PopupListBox::selectNextRow()
{
if (!m_settings.loopSelectionNavigation || m_selectedIndex != numItems() - 1) {
adjustSelectedIndex(1);
return;
}
clearSelection();
}
void PopupListBox::selectPreviousRow()
{
if (!m_settings.loopSelectionNavigation || m_selectedIndex > 0) {
adjustSelectedIndex(-1);
return;
}
if (m_selectedIndex == 0) {
clearSelection();
return;
}
selectIndex(numItems() - 1);
scrollToRevealSelection();
}
void PopupListBox::adjustSelectedIndex(int delta)
{
int targetIndex = m_selectedIndex + delta;
targetIndex = min(max(targetIndex, 0), numItems() - 1);
if (!isSelectableItem(targetIndex)) {
int dir = delta > 0 ? 1 : -1;
int testIndex = m_selectedIndex;
int bestIndex = m_selectedIndex;
bool passedTarget = false;
while (testIndex >= 0 && testIndex < numItems()) {
if (isSelectableItem(testIndex))
bestIndex = testIndex;
if (testIndex == targetIndex)
passedTarget = true;
if (passedTarget && bestIndex != m_selectedIndex)
break;
testIndex += dir;
}
targetIndex = bestIndex;
}
selectIndex(targetIndex);
scrollToRevealSelection();
}
void PopupListBox::hidePopup()
{
if (parent()) {
PopupContainer* container = static_cast<PopupContainer*>(parent());
if (container->client())
container->client()->popupClosed(container);
container->notifyPopupHidden();
}
if (m_popupClient)
m_popupClient->popupDidHide();
}
void PopupListBox::updateFromElement()
{
clear();
int size = m_popupClient->listSize();
for (int i = 0; i < size; ++i) {
PopupItem::Type type;
if (m_popupClient->itemIsSeparator(i))
type = PopupItem::TypeSeparator;
else if (m_popupClient->itemIsLabel(i))
type = PopupItem::TypeGroup;
else
type = PopupItem::TypeOption;
m_items.append(new PopupItem(m_popupClient->itemText(i), type));
m_items[i]->enabled = isSelectableItem(i);
PopupMenuStyle style = m_popupClient->itemStyle(i);
m_items[i]->textDirection = style.textDirection();
m_items[i]->hasTextDirectionOverride = style.hasTextDirectionOverride();
}
m_selectedIndex = m_popupClient->selectedIndex();
setOriginalIndex(m_selectedIndex);
layout();
}
void PopupListBox::layout()
{
bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
int baseWidth = 0;
int paddingWidth = 0;
int lineEndPaddingWidth = 0;
int y = 0;
for (int i = 0; i < numItems(); ++i) {
m_items[i]->yOffset = y;
if (m_popupClient->itemStyle(i).isDisplayNone())
continue;
y += getRowHeight(i);
Font itemFont = getRowFont(i);
String text = m_popupClient->itemText(i);
String label = m_popupClient->itemLabel(i);
String icon = m_popupClient->itemIcon(i);
RefPtr<Image> iconImage(Image::loadPlatformResource(icon.utf8().data()));
int width = 0;
if (!text.isEmpty())
width = itemFont.width(TextRun(text));
if (!label.isEmpty()) {
if (width > 0)
width += kTextToLabelPadding;
width += itemFont.width(TextRun(label));
}
if (iconImage && !iconImage->isNull()) {
if (width > 0)
width += kLabelToIconPadding;
width += iconImage->rect().width();
}
baseWidth = max(baseWidth, width);
paddingWidth = max(paddingWidth,
m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight());
lineEndPaddingWidth = max(lineEndPaddingWidth,
isRightAligned ? m_popupClient->clientPaddingLeft() : m_popupClient->clientPaddingRight());
}
int windowHeight = 0;
m_visibleRows = min(numItems(), kMaxVisibleRows);
for (int i = 0; i < m_visibleRows; ++i) {
int rowHeight = getRowHeight(i);
if (windowHeight + rowHeight > m_maxHeight) {
m_visibleRows = i;
break;
}
windowHeight += rowHeight;
}
int scrollbarWidth = 0;
if (m_visibleRows < numItems()) {
scrollbarWidth = ScrollbarTheme::nativeTheme()->scrollbarThickness();
paddingWidth = paddingWidth - lineEndPaddingWidth + kMinEndOfLinePadding;
}
int windowWidth;
int contentWidth;
if (m_settings.restrictWidthOfListBox) {
windowWidth = m_baseWidth;
contentWidth = m_baseWidth - scrollbarWidth;
} else {
windowWidth = baseWidth + scrollbarWidth + paddingWidth;
contentWidth = baseWidth + paddingWidth;
if (windowWidth < m_baseWidth) {
windowWidth = m_baseWidth;
contentWidth = m_baseWidth - scrollbarWidth;
} else
m_baseWidth = baseWidth;
}
resize(windowWidth, windowHeight);
setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
if (hostWindow())
scrollToRevealSelection();
invalidate();
}
void PopupListBox::clear()
{
for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it)
delete *it;
m_items.clear();
}
bool PopupListBox::isPointInBounds(const IntPoint& point)
{
return numItems() != 0 && IntRect(0, 0, width(), height()).contains(point);
}
PopupMenuChromium::PopupMenuChromium(PopupMenuClient* client)
: m_popupClient(client)
{
}
PopupMenuChromium::~PopupMenuChromium()
{
if (p.popup)
p.popup->listBox()->disconnectClient();
hide();
}
void PopupMenuChromium::show(const IntRect& r, FrameView* v, int index)
{
if (!p.popup)
p.popup = PopupContainer::create(client(), PopupContainer::Select, dropDownSettings);
p.popup->showInRect(r, v, index);
}
void PopupMenuChromium::hide()
{
if (p.popup)
p.popup->hide();
}
void PopupMenuChromium::updateFromElement()
{
p.popup->listBox()->updateFromElement();
}
void PopupMenuChromium::disconnectClient()
{
m_popupClient = 0;
}
}