/* * Copyright (c) 2008, 2009, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "PopupMenuChromium.h" #include "CharacterNames.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 "PopupMenu.h" #include "RenderTheme.h" #include "ScrollbarTheme.h" #include "SystemTime.h" #include 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 TimeStamp kTypeAheadTimeoutMs = 1000; // The settings used for the drop down menu. // This is the delegate used if none is provided. static const PopupContainerSettings dropDownSettings = { true, // focusOnShow true, // setTextOnIndexChange true, // acceptOnAbandon false // loopSelectionNavigation }; // This class uses WebCore code to paint and handle events for a drop-down list // box ("combobox" on Windows). class PopupListBox : public FramelessScrollView { public: static PassRefPtr create(PopupMenuClient* client, const PopupContainerSettings& settings) { return adoptRef(new PopupListBox(client, settings)); } // FramelessScrollView 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&); // ScrollView virtual HostWindow* hostWindow() const; // PopupListBox methods // Shows the popup void showPopup(); // Hides the popup. Do not call this directly: use client->hidePopup(). void hidePopup(); // Updates our internal list to match the client. void updateFromElement(); // Frees any allocated resources used in a particular popup session. void clear(); // Sets the index of the option that is displayed in the widget on // the web page, and closes the popup. void acceptIndex(int index); // Clears the selection (so no row appears selected). void clearSelection(); // Scrolls to reveal the given index. void scrollToRevealRow(int index); void scrollToRevealSelection() { scrollToRevealRow(m_selectedIndex); } // Invalidates the row at the given index. void invalidateRow(int index); // Get the bounds of a row. IntRect getRowBounds(int index); // Converts a point to an index of the row the point is over int pointToRowIndex(const IntPoint&); // Paint an individual row void paintRow(GraphicsContext*, const IntRect&, int rowIndex); // Test if the given point is within the bounds of the popup window. bool isPointInBounds(const IntPoint&); // Called when the user presses a text key. Does a prefix-search of the items. void typeAheadFind(const PlatformKeyboardEvent&); // Returns the font to use for the given row Font getRowFont(int index); // Moves the selection down/up one item, taking care of looping back to the // first/last element if m_loopSelectionNavigation is true. void selectPreviousRow(); void selectNextRow(); // The settings that specify the behavior for this Popup window. PopupContainerSettings m_settings; // This is the index of the item marked as "selected" - i.e. displayed in the widget on the // page. int m_originalIndex; // This is the index of the item that the user is hovered over or has selected using the // keyboard in the list. They have not confirmed this selection by clicking or pressing // enter yet however. int m_selectedIndex; // If >= 0, this is the index we should accept if the popup is "abandoned". // This is used for keyboard navigation, where we want the // selection to change immediately, and is only used if the settings // acceptOnAbandon field is true. int m_acceptedIndexOnAbandon; // This is the number of rows visible in the popup. The maximum number visible at a time is // defined as being kMaxVisibleRows. For a scrolled popup, this can be thought of as the // page size in data units. int m_visibleRows; // Our suggested width, not including scrollbar. int m_baseWidth; // A list of the options contained within the PopupMenuClient that opened us. PopupMenuClient* m_popupClient; // The scrollbar which has mouse capture. Mouse events go straight to this // if non-NULL. RefPtr m_capturingScrollbar; // The last scrollbar that the mouse was over. Used for mouseover highlights. RefPtr m_lastScrollbarUnderMouse; // The string the user has typed so far into the popup. Used for typeAheadFind. String m_typedString; // The char the user has hit repeatedly. Used for typeAheadFind. UChar m_repeatingChar; // The last time the user hit a key. Used for typeAheadFind. TimeStamp m_lastCharTime; }; static PlatformMouseEvent constructRelativeMouseEvent(const PlatformMouseEvent& e, FramelessScrollView* parent, FramelessScrollView* child) { IntPoint pos = parent->convertSelfToChild(child, e.pos()); // FIXME: This is a horrible hack since PlatformMouseEvent has no setters for x/y. PlatformMouseEvent relativeEvent = e; IntPoint& relativePos = const_cast(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()); // FIXME: This is a horrible hack since PlatformWheelEvent has no setters for x/y. PlatformWheelEvent relativeEvent = e; IntPoint& relativePos = const_cast(relativeEvent.pos()); relativePos.setX(pos.x()); relativePos.setY(pos.y()); return relativeEvent; } /////////////////////////////////////////////////////////////////////////////// // PopupContainer implementation // static PassRefPtr PopupContainer::create(PopupMenuClient* client, const PopupContainerSettings& settings) { return adoptRef(new PopupContainer(client, settings)); } PopupContainer::PopupContainer(PopupMenuClient* client, const PopupContainerSettings& settings) : m_listBox(PopupListBox::create(client, settings)) , m_settings(settings) { setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff); } PopupContainer::~PopupContainer() { if (m_listBox && m_listBox->parent()) removeChild(m_listBox.get()); } void PopupContainer::showPopup(FrameView* view) { // Pre-layout, our size matches the PopupMenuClient what index was selected. m_popupClient->valueChanged(index); } } void PopupListBox::selectIndex(int index) { if (index < 0 || index >= numItems()) return; if (index != m_selectedIndex && isSelectableItem(index)) { invalidateRow(m_selectedIndex); m_selectedIndex = index; invalidateRow(m_selectedIndex); scrollToRevealSelection(); } } void PopupListBox::setOriginalIndex(int index) { m_originalIndex = m_selectedIndex = index; } int PopupListBox::getRowHeight(int index) { if (index < 0) return 0; return getRowFont(index).height(); } 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; // Invalidate in the window contents, as FramelessScrollView::invalidateRect // paints in the window coordinates. invalidateRect(contentsToWindow(getRowBounds(index))); } void PopupListBox::scrollToRevealRow(int index) { if (index < 0) return; IntRect rowRect = getRowBounds(index); if (rowRect.y() < scrollY()) { // Row is above current scroll position, scroll up. ScrollView::setScrollPosition(IntPoint(0, rowRect.y())); } else if (rowRect.bottom() > scrollY() + visibleHeight()) { // Row is below current scroll position, scroll down. ScrollView::setScrollPosition(IntPoint(0, rowRect.bottom() - 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; } } void PopupListBox::selectNextRow() { if (!m_settings.loopSelectionNavigation || m_selectedIndex != numItems() - 1) { adjustSelectedIndex(1); return; } // We are moving past the last item, no row should be selected. clearSelection(); } void PopupListBox::selectPreviousRow() { if (!m_settings.loopSelectionNavigation || m_selectedIndex > 0) { adjustSelectedIndex(-1); return; } if (m_selectedIndex == 0) { // We are moving past the first item, clear the selection. clearSelection(); return; } // No row is selected, jump to the last item. selectIndex(numItems() - 1); scrollToRevealSelection(); } void PopupListBox::adjustSelectedIndex(int delta) { int targetIndex = m_selectedIndex + delta; targetIndex = min(max(targetIndex, 0), numItems() - 1); if (!isSelectableItem(targetIndex)) { // We didn't land on an option. Try to find one. // We try to select the closest index to target, prioritizing any in // the range [current, target]. 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; } // Pick the best index, which may mean we don't change. targetIndex = bestIndex; } // Select the new index, and ensure its visible. We do this regardless of // whether the selection changed to ensure keyboard events always bring the // selection into view. selectIndex(targetIndex); scrollToRevealSelection(); } 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); } m_selectedIndex = m_popupClient->selectedIndex(); setOriginalIndex(m_selectedIndex); layout(); } void PopupListBox::layout() { // Size our child items. int baseWidth = 0; int paddingWidth = 0; int y = 0; for (int i = 0; i < numItems(); ++i) { Font itemFont = getRowFont(i); // Place the item vertically. m_items[i]->yOffset = y; y += itemFont.height(); // Ensure the popup is wide enough to fit this item. String text = m_popupClient->itemText(i); if (!text.isEmpty()) { int width = itemFont.width(TextRun(text)); baseWidth = max(baseWidth, width); } // FIXME: http://b/1210481 We should get the padding of individual option elements. paddingWidth = max(paddingWidth, m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight()); } int windowHeight = 0; #if PLATFORM(DARWIN) // Set the popup's window to contain all available items on Mac only, which // uses native controls that manage their own scrolling. This allows hit // testing to work when selecting items in popups that have more menu entries // than the maximum window size. m_visibleRows = numItems(); #else m_visibleRows = min(numItems(), kMaxVisibleRows); #endif for (int i = 0; i < m_visibleRows; ++i) { int rowHeight = getRowHeight(i); #if !PLATFORM(DARWIN) // Only clip the window height for non-Mac platforms. if (windowHeight + rowHeight > kMaxHeight) { m_visibleRows = i; break; } #endif windowHeight += rowHeight; } // Set our widget and scrollable contents sizes. int scrollbarWidth = 0; if (m_visibleRows < numItems()) scrollbarWidth = ScrollbarTheme::nativeTheme()->scrollbarThickness(); int windowWidth = baseWidth + scrollbarWidth + paddingWidth; int contentWidth = baseWidth; if (windowWidth < m_baseWidth) { windowWidth = m_baseWidth; contentWidth = m_baseWidth - scrollbarWidth - paddingWidth; } else { m_baseWidth = baseWidth; } resize(windowWidth, windowHeight); setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).bottom())); if (hostWindow()) scrollToRevealSelection(); invalidate(); } void PopupListBox::clear() { for (Vector::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); } /////////////////////////////////////////////////////////////////////////////// // PopupMenu implementation // // Note: you cannot add methods to this class, since it is defined above the // portability layer. To access methods and properties on the // popup widgets, use |popupWindow| above. PopupMenu::PopupMenu(PopupMenuClient* client) : m_popupClient(client) { } PopupMenu::~PopupMenu() { hide(); } // The Mac Chromium implementation relies on external control (a Cocoa control) // to display, handle the input tracking and menu item selection for the popup. // Windows and Linux Chromium let our WebKit port handle the display, while // another process manages the popup window and input handling. void PopupMenu::show(const IntRect& r, FrameView* v, int index) { if (!p.popup) p.popup = PopupContainer::create(client(), dropDownSettings); #if PLATFORM(DARWIN) p.popup->showExternal(r, v, index); #else p.popup->show(r, v, index); #endif } void PopupMenu::hide() { if (p.popup) p.popup->hidePopup(); } void PopupMenu::updateFromElement() { p.popup->listBox()->updateFromElement(); } bool PopupMenu::itemWritingDirectionIsNatural() { return false; } } // namespace WebCore