blob: 523701127534d858143546ed3a7ee994bb2b1e5a [file] [log] [blame]
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001/*
2 * Copyright (c) 2011, Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
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
13 * distribution.
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.
17 *
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.
29 */
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010030
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010031#include "config.h"
32#include "PopupListBox.h"
33
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010034#include "CSSValueKeywords.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010035#include "PopupContainer.h"
36#include "PopupMenuChromium.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010037#include "RuntimeEnabledFeatures.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010038#include "core/rendering/RenderTheme.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000039#include "platform/KeyboardCodes.h"
Torne (Richard Coles)1e202182013-10-18 15:46:42 +010040#include "platform/PlatformGestureEvent.h"
41#include "platform/PlatformKeyboardEvent.h"
42#include "platform/PlatformMouseEvent.h"
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +010043#include "platform/PlatformScreen.h"
Torne (Richard Coles)1e202182013-10-18 15:46:42 +010044#include "platform/PlatformTouchEvent.h"
45#include "platform/PlatformWheelEvent.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000046#include "platform/PopupMenuClient.h"
Torne (Richard Coles)a854de02013-12-18 16:25:25 +000047#include "platform/fonts/Font.h"
48#include "platform/fonts/FontCache.h"
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +000049#include "platform/fonts/FontSelector.h"
Torne (Richard Coles)1e202182013-10-18 15:46:42 +010050#include "platform/geometry/IntRect.h"
Torne (Richard Coles)a854de02013-12-18 16:25:25 +000051#include "platform/graphics/GraphicsContext.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000052#include "platform/scroll/FramelessScrollViewClient.h"
Torne (Richard Coles)a854de02013-12-18 16:25:25 +000053#include "platform/scroll/ScrollbarTheme.h"
54#include "platform/text/StringTruncator.h"
55#include "platform/text/TextRun.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010056#include "wtf/ASCIICType.h"
57#include "wtf/CurrentTime.h"
58#include <limits>
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010059
Torne (Richard Coles)09380292014-02-21 12:17:33 +000060namespace blink {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010061
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010062using namespace WTF::Unicode;
Torne (Richard Coles)09380292014-02-21 12:17:33 +000063using namespace WebCore;
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010064
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010065const int PopupListBox::defaultMaxHeight = 500;
66static const int maxVisibleRows = 20;
67static const int minEndOfLinePadding = 2;
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010068static const TimeStamp typeAheadTimeoutMs = 1000;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010069
Torne (Richard Coles)09380292014-02-21 12:17:33 +000070PopupListBox::PopupListBox(PopupMenuClient* client, bool deviceSupportsTouch)
71 : m_deviceSupportsTouch(deviceSupportsTouch)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010072 , m_originalIndex(0)
73 , m_selectedIndex(0)
74 , m_acceptedIndexOnAbandon(-1)
75 , m_visibleRows(0)
76 , m_baseWidth(0)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010077 , m_maxHeight(defaultMaxHeight)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010078 , m_popupClient(client)
79 , m_repeatingChar(0)
80 , m_lastCharTime(0)
81 , m_maxWindowWidth(std::numeric_limits<int>::max())
82{
83 setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
84}
85
86bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
87{
88 Scrollbar* scrollbar = scrollbarAtPoint(event.position());
89 if (scrollbar) {
90 m_capturingScrollbar = scrollbar;
91 m_capturingScrollbar->mouseDown(event);
92 return true;
93 }
94
95 if (!isPointInBounds(event.position()))
96 abandon();
97
98 return true;
99}
100
101bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
102{
103 if (m_capturingScrollbar) {
104 m_capturingScrollbar->mouseMoved(event);
105 return true;
106 }
107
108 Scrollbar* scrollbar = scrollbarAtPoint(event.position());
109 if (m_lastScrollbarUnderMouse != scrollbar) {
110 // Send mouse exited to the old scrollbar.
111 if (m_lastScrollbarUnderMouse)
112 m_lastScrollbarUnderMouse->mouseExited();
113 m_lastScrollbarUnderMouse = scrollbar;
114 }
115
116 if (scrollbar) {
117 scrollbar->mouseMoved(event);
118 return true;
119 }
120
121 if (!isPointInBounds(event.position()))
122 return false;
123
124 selectIndex(pointToRowIndex(event.position()));
125 return true;
126}
127
128bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
129{
130 if (m_capturingScrollbar) {
131 m_capturingScrollbar->mouseUp(event);
Torne (Richard Coles)d5428f32014-03-18 10:21:16 +0000132 m_capturingScrollbar = nullptr;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100133 return true;
134 }
135
136 if (!isPointInBounds(event.position()))
137 return true;
138
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000139 if (acceptIndex(pointToRowIndex(event.position())) && m_focusedElement) {
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100140 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::mouseup);
141 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::click);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100142
Ben Murdoch7757ec22013-07-23 11:17:36 +0100143 // Clear m_focusedElement here, because we cannot clear in hidePopup()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100144 // which is called before dispatchMouseEvent() is called.
Torne (Richard Coles)d5428f32014-03-18 10:21:16 +0000145 m_focusedElement = nullptr;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100146 }
147
148 return true;
149}
150
151bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
152{
153 if (!isPointInBounds(event.position())) {
154 abandon();
155 return true;
156 }
157
158 ScrollableArea::handleWheelEvent(event);
159 return true;
160}
161
162// Should be kept in sync with handleKeyEvent().
163bool PopupListBox::isInterestedInEventForKey(int keyCode)
164{
165 switch (keyCode) {
166 case VKEY_ESCAPE:
167 case VKEY_RETURN:
168 case VKEY_UP:
169 case VKEY_DOWN:
170 case VKEY_PRIOR:
171 case VKEY_NEXT:
172 case VKEY_HOME:
173 case VKEY_END:
174 case VKEY_TAB:
175 return true;
176 default:
177 return false;
178 }
179}
180
181bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&)
182{
183 return false;
184}
185
186bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&)
187{
188 return false;
189}
190
191static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
192{
193 // Check whether the event is a character-typed event or not.
194 // We use RawKeyDown/Char/KeyUp event scheme on all platforms,
195 // so PlatformKeyboardEvent::Char (not RawKeyDown) type event
196 // is considered as character type event.
197 return event.type() == PlatformEvent::Char;
198}
199
200bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
201{
202 if (event.type() == PlatformEvent::KeyUp)
203 return true;
204
205 if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
206 return true;
207
208 switch (event.windowsVirtualKeyCode()) {
209 case VKEY_ESCAPE:
210 abandon(); // may delete this
211 return true;
212 case VKEY_RETURN:
213 if (m_selectedIndex == -1) {
214 hidePopup();
215 // Don't eat the enter if nothing is selected.
216 return false;
217 }
218 acceptIndex(m_selectedIndex); // may delete this
219 return true;
220 case VKEY_UP:
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000221 selectPreviousRow();
222 break;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100223 case VKEY_DOWN:
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000224 selectNextRow();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100225 break;
226 case VKEY_PRIOR:
227 adjustSelectedIndex(-m_visibleRows);
228 break;
229 case VKEY_NEXT:
230 adjustSelectedIndex(m_visibleRows);
231 break;
232 case VKEY_HOME:
233 adjustSelectedIndex(-m_selectedIndex);
234 break;
235 case VKEY_END:
236 adjustSelectedIndex(m_items.size());
237 break;
238 default:
239 if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
240 && isPrintableChar(event.windowsVirtualKeyCode())
241 && isCharacterTypeEvent(event))
242 typeAheadFind(event);
243 break;
244 }
245
246 if (m_originalIndex != m_selectedIndex) {
247 // Keyboard events should update the selection immediately (but we don't
248 // want to fire the onchange event until the popup is closed, to match
249 // IE). We change the original index so we revert to that when the
250 // popup is closed.
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000251 m_acceptedIndexOnAbandon = m_selectedIndex;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100252
253 setOriginalIndex(m_selectedIndex);
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000254 m_popupClient->setTextFromItem(m_selectedIndex);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100255 }
256 if (event.windowsVirtualKeyCode() == VKEY_TAB) {
257 // TAB is a special case as it should select the current item if any and
258 // advance focus.
259 if (m_selectedIndex >= 0) {
260 acceptIndex(m_selectedIndex); // May delete us.
261 // Return false so the TAB key event is propagated to the page.
262 return false;
263 }
264 // Call abandon() so we honor m_acceptedIndexOnAbandon if set.
265 abandon();
266 // Return false so the TAB key event is propagated to the page.
267 return false;
268 }
269
270 return true;
271}
272
273HostWindow* PopupListBox::hostWindow() const
274{
275 // Our parent is the root ScrollView, so it is the one that has a
276 // HostWindow. FrameView::hostWindow() works similarly.
277 return parent() ? parent()->hostWindow() : 0;
278}
279
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000280bool PopupListBox::shouldPlaceVerticalScrollbarOnLeft() const
281{
282 return m_popupClient->menuStyle().textDirection() == RTL;
283}
284
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100285// From HTMLSelectElement.cpp
286static String stripLeadingWhiteSpace(const String& string)
287{
288 int length = string.length();
289 int i;
290 for (i = 0; i < length; ++i)
291 if (string[i] != noBreakSpace
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000292 && !isSpaceOrNewline(string[i]))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100293 break;
294
295 return string.substring(i, length - i);
296}
297
298// From HTMLSelectElement.cpp, with modifications
299void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
300{
301 TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
302 TimeStamp delta = now - m_lastCharTime;
303
304 // Reset the time when user types in a character. The time gap between
305 // last character and the current character is used to indicate whether
306 // user typed in a string or just a character as the search prefix.
307 m_lastCharTime = now;
308
309 UChar c = event.windowsVirtualKeyCode();
310
311 String prefix;
312 int searchStartOffset = 1;
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100313 if (delta > typeAheadTimeoutMs) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100314 m_typedString = prefix = String(&c, 1);
315 m_repeatingChar = c;
316 } else {
317 m_typedString.append(c);
318
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100319 if (c == m_repeatingChar) {
320 // The user is likely trying to cycle through all the items starting
321 // with this character, so just search on the character.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100322 prefix = String(&c, 1);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100323 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100324 m_repeatingChar = 0;
325 prefix = m_typedString;
326 searchStartOffset = 0;
327 }
328 }
329
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100330 // Compute a case-folded copy of the prefix string before beginning the
331 // search for a matching element. This code uses foldCase to work around the
332 // fact that String::startWith does not fold non-ASCII characters. This code
333 // can be changed to use startWith once that is fixed.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100334 String prefixWithCaseFolded(prefix.foldCase());
335 int itemCount = numItems();
336 int index = (max(0, m_selectedIndex) + searchStartOffset) % itemCount;
337 for (int i = 0; i < itemCount; i++, index = (index + 1) % itemCount) {
338 if (!isSelectableItem(index))
339 continue;
340
341 if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
342 selectIndex(index);
343 return;
344 }
345 }
346}
347
348void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
349{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100350 // Adjust coords for scrolled frame.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100351 IntRect r = intersection(rect, frameRect());
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000352 int tx = x() - scrollX() + ((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) ? verticalScrollbar()->width() : 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100353 int ty = y() - scrollY();
354
355 r.move(-tx, -ty);
356
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100357 // Set clip rect to match revised damage rect.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100358 gc->save();
359 gc->translate(static_cast<float>(tx), static_cast<float>(ty));
360 gc->clip(r);
361
362 // FIXME: Can we optimize scrolling to not require repainting the entire
363 // window? Should we?
364 for (int i = 0; i < numItems(); ++i)
365 paintRow(gc, r, i);
366
367 // Special case for an empty popup.
368 if (!numItems())
Torne (Richard Coles)5267f702013-06-11 10:57:24 +0100369 gc->fillRect(r, Color::white);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100370
371 gc->restore();
372
373 ScrollView::paint(gc, rect);
374}
375
376static const int separatorPadding = 4;
377static const int separatorHeight = 1;
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000378static const int minRowHeight = 0;
379static const int optionRowHeightForTouch = 28;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100380
381void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
382{
383 // This code is based largely on RenderListBox::paint* methods.
384
385 IntRect rowRect = getRowBounds(rowIndex);
386 if (!rowRect.intersects(rect))
387 return;
388
389 PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
390
391 // Paint background
392 Color backColor, textColor, labelColor;
393 if (rowIndex == m_selectedIndex) {
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +0100394 backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor();
395 textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100396 labelColor = textColor;
397 } else {
398 backColor = style.backgroundColor();
399 textColor = style.foregroundColor();
400
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100401#if OS(LINUX) || OS(ANDROID)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100402 // On other platforms, the <option> background color is the same as the
403 // <select> background color. On Linux, that makes the <option>
404 // background color very dark, so by default, try to use a lighter
405 // background color for <option>s.
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +0100406 if (style.backgroundColorType() == PopupMenuStyle::DefaultBackgroundColor && RenderTheme::theme().systemColor(CSSValueButtonface) == backColor)
407 backColor = RenderTheme::theme().systemColor(CSSValueMenu);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100408#endif
409
410 // FIXME: for now the label color is hard-coded. It should be added to
411 // the PopupMenuStyle.
412 labelColor = Color(115, 115, 115);
413 }
414
415 // If we have a transparent background, make sure it has a color to blend
416 // against.
417 if (backColor.hasAlpha())
Torne (Richard Coles)5267f702013-06-11 10:57:24 +0100418 gc->fillRect(rowRect, Color::white);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100419
Torne (Richard Coles)5267f702013-06-11 10:57:24 +0100420 gc->fillRect(rowRect, backColor);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100421
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100422 if (m_popupClient->itemIsSeparator(rowIndex)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100423 IntRect separatorRect(
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000424 rowRect.x() + separatorPadding,
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100425 rowRect.y() + (rowRect.height() - separatorHeight) / 2,
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000426 rowRect.width() - 2 * separatorPadding, separatorHeight);
427 gc->fillRect(separatorRect, textColor);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100428 return;
429 }
430
431 if (!style.isVisible())
432 return;
433
Torne (Richard Coles)5267f702013-06-11 10:57:24 +0100434 gc->setFillColor(textColor);
435
436 FontCachePurgePreventer fontCachePurgePreventer;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100437
438 Font itemFont = getRowFont(rowIndex);
439 // FIXME: http://crbug.com/19872 We should get the padding of individual option
440 // elements. This probably implies changes to PopupMenuClient.
441 bool rightAligned = m_popupClient->menuStyle().textDirection() == RTL;
442 int textX = 0;
443 int maxWidth = 0;
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000444 if (rightAligned) {
445 maxWidth = rowRect.width() - max<int>(0, m_popupClient->clientPaddingRight());
446 } else {
447 textX = max<int>(0, m_popupClient->clientPaddingLeft());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100448 maxWidth = rowRect.width() - textX;
449 }
450 // Prepare text to be drawn.
451 String itemText = m_popupClient->itemText(rowIndex);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100452
453 // Prepare the directionality to draw text.
454 TextRun textRun(itemText, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
455 // If the text is right-to-left, make it right-aligned by adjusting its
456 // beginning position.
457 if (rightAligned)
458 textX += maxWidth - itemFont.width(textRun);
459
460 // Draw the item text.
461 int textY = rowRect.y() + itemFont.fontMetrics().ascent() + (rowRect.height() - itemFont.fontMetrics().height()) / 2;
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100462 TextRunPaintInfo textRunPaintInfo(textRun);
463 textRunPaintInfo.bounds = rowRect;
464 gc->drawBidiText(itemFont, textRunPaintInfo, IntPoint(textX, textY));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100465}
466
467Font PopupListBox::getRowFont(int rowIndex)
468{
469 Font itemFont = m_popupClient->itemStyle(rowIndex).font();
470 if (m_popupClient->itemIsLabel(rowIndex)) {
471 // Bold-ify labels (ie, an <optgroup> heading).
472 FontDescription d = itemFont.fontDescription();
473 d.setWeight(FontWeightBold);
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000474 Font font(d);
Torne (Richard Coles)d5428f32014-03-18 10:21:16 +0000475 font.update(nullptr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100476 return font;
477 }
478
479 return itemFont;
480}
481
482void PopupListBox::abandon()
483{
484 RefPtr<PopupListBox> keepAlive(this);
485
486 m_selectedIndex = m_originalIndex;
487
488 hidePopup();
489
490 if (m_acceptedIndexOnAbandon >= 0) {
491 if (m_popupClient)
492 m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
493 m_acceptedIndexOnAbandon = -1;
494 }
495}
496
497int PopupListBox::pointToRowIndex(const IntPoint& point)
498{
499 int y = scrollY() + point.y();
500
501 // FIXME: binary search if perf matters.
502 for (int i = 0; i < numItems(); ++i) {
503 if (y < m_items[i]->yOffset)
504 return i-1;
505 }
506
507 // Last item?
508 if (y < contentsHeight())
509 return m_items.size()-1;
510
511 return -1;
512}
513
514bool PopupListBox::acceptIndex(int index)
515{
516 // Clear m_acceptedIndexOnAbandon once user accepts the selected index.
517 if (m_acceptedIndexOnAbandon >= 0)
518 m_acceptedIndexOnAbandon = -1;
519
520 if (index >= numItems())
521 return false;
522
523 if (index < 0) {
524 if (m_popupClient) {
525 // Enter pressed with no selection, just close the popup.
526 hidePopup();
527 }
528 return false;
529 }
530
531 if (isSelectableItem(index)) {
532 RefPtr<PopupListBox> keepAlive(this);
533
534 // Hide ourselves first since valueChanged may have numerous side-effects.
535 hidePopup();
536
537 // Tell the <select> PopupMenuClient what index was selected.
538 m_popupClient->valueChanged(index);
539
540 return true;
541 }
542
543 return false;
544}
545
546void PopupListBox::selectIndex(int index)
547{
548 if (index < 0 || index >= numItems())
549 return;
550
551 bool isSelectable = isSelectableItem(index);
552 if (index != m_selectedIndex && isSelectable) {
553 invalidateRow(m_selectedIndex);
554 m_selectedIndex = index;
555 invalidateRow(m_selectedIndex);
556
557 scrollToRevealSelection();
558 m_popupClient->selectionChanged(m_selectedIndex);
559 } else if (!isSelectable)
560 clearSelection();
561}
562
563void PopupListBox::setOriginalIndex(int index)
564{
565 m_originalIndex = m_selectedIndex = index;
566}
567
568int PopupListBox::getRowHeight(int index)
569{
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000570 int minimumHeight = m_deviceSupportsTouch ? optionRowHeightForTouch : minRowHeight;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100571
572 if (index < 0 || m_popupClient->itemStyle(index).isDisplayNone())
573 return minimumHeight;
574
575 // Separator row height is the same size as itself.
576 if (m_popupClient->itemIsSeparator(index))
577 return max(separatorHeight, minimumHeight);
578
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100579 int fontHeight = getRowFont(index).fontMetrics().height();
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000580 return max(fontHeight, minimumHeight);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100581}
582
583IntRect PopupListBox::getRowBounds(int index)
584{
585 if (index < 0)
586 return IntRect(0, 0, visibleWidth(), getRowHeight(index));
587
588 return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
589}
590
591void PopupListBox::invalidateRow(int index)
592{
593 if (index < 0)
594 return;
595
596 // Invalidate in the window contents, as FramelessScrollView::invalidateRect
597 // paints in the window coordinates.
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000598 IntRect clipRect = contentsToWindow(getRowBounds(index));
599 if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar())
600 clipRect.move(verticalScrollbar()->width(), 0);
601 invalidateRect(clipRect);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100602}
603
604void PopupListBox::scrollToRevealRow(int index)
605{
606 if (index < 0)
607 return;
608
609 IntRect rowRect = getRowBounds(index);
610
611 if (rowRect.y() < scrollY()) {
612 // Row is above current scroll position, scroll up.
613 ScrollView::setScrollPosition(IntPoint(0, rowRect.y()));
614 } else if (rowRect.maxY() > scrollY() + visibleHeight()) {
615 // Row is below current scroll position, scroll down.
616 ScrollView::setScrollPosition(IntPoint(0, rowRect.maxY() - visibleHeight()));
617 }
618}
619
620bool PopupListBox::isSelectableItem(int index)
621{
622 ASSERT(index >= 0 && index < numItems());
623 return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
624}
625
626void PopupListBox::clearSelection()
627{
628 if (m_selectedIndex != -1) {
629 invalidateRow(m_selectedIndex);
630 m_selectedIndex = -1;
631 m_popupClient->selectionCleared();
632 }
633}
634
635void PopupListBox::selectNextRow()
636{
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000637 adjustSelectedIndex(1);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100638}
639
640void PopupListBox::selectPreviousRow()
641{
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000642 adjustSelectedIndex(-1);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100643}
644
645void PopupListBox::adjustSelectedIndex(int delta)
646{
647 int targetIndex = m_selectedIndex + delta;
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100648 targetIndex = std::min(std::max(targetIndex, 0), numItems() - 1);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100649 if (!isSelectableItem(targetIndex)) {
650 // We didn't land on an option. Try to find one.
651 // We try to select the closest index to target, prioritizing any in
652 // the range [current, target].
653
654 int dir = delta > 0 ? 1 : -1;
655 int testIndex = m_selectedIndex;
656 int bestIndex = m_selectedIndex;
657 bool passedTarget = false;
658 while (testIndex >= 0 && testIndex < numItems()) {
659 if (isSelectableItem(testIndex))
660 bestIndex = testIndex;
661 if (testIndex == targetIndex)
662 passedTarget = true;
663 if (passedTarget && bestIndex != m_selectedIndex)
664 break;
665
666 testIndex += dir;
667 }
668
669 // Pick the best index, which may mean we don't change.
670 targetIndex = bestIndex;
671 }
672
673 // Select the new index, and ensure its visible. We do this regardless of
674 // whether the selection changed to ensure keyboard events always bring the
675 // selection into view.
676 selectIndex(targetIndex);
677 scrollToRevealSelection();
678}
679
680void PopupListBox::hidePopup()
681{
682 if (parent()) {
683 PopupContainer* container = static_cast<PopupContainer*>(parent());
684 if (container->client())
685 container->client()->popupClosed(container);
686 container->notifyPopupHidden();
687 }
688
689 if (m_popupClient)
690 m_popupClient->popupDidHide();
691}
692
693void PopupListBox::updateFromElement()
694{
695 clear();
696
697 int size = m_popupClient->listSize();
698 for (int i = 0; i < size; ++i) {
699 PopupItem::Type type;
700 if (m_popupClient->itemIsSeparator(i))
701 type = PopupItem::TypeSeparator;
702 else if (m_popupClient->itemIsLabel(i))
703 type = PopupItem::TypeGroup;
704 else
705 type = PopupItem::TypeOption;
706 m_items.append(new PopupItem(m_popupClient->itemText(i), type));
707 m_items[i]->enabled = isSelectableItem(i);
708 PopupMenuStyle style = m_popupClient->itemStyle(i);
709 m_items[i]->textDirection = style.textDirection();
710 m_items[i]->hasTextDirectionOverride = style.hasTextDirectionOverride();
711 }
712
713 m_selectedIndex = m_popupClient->selectedIndex();
714 setOriginalIndex(m_selectedIndex);
715
716 layout();
717}
718
719void PopupListBox::setMaxWidthAndLayout(int maxWidth)
720{
721 m_maxWindowWidth = maxWidth;
722 layout();
723}
724
725void PopupListBox::layout()
726{
727 bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
728
729 // Size our child items.
730 int baseWidth = 0;
731 int paddingWidth = 0;
732 int lineEndPaddingWidth = 0;
733 int y = 0;
734 for (int i = 0; i < numItems(); ++i) {
735 // Place the item vertically.
736 m_items[i]->yOffset = y;
737 if (m_popupClient->itemStyle(i).isDisplayNone())
738 continue;
739 y += getRowHeight(i);
740
741 // Ensure the popup is wide enough to fit this item.
742 Font itemFont = getRowFont(i);
743 String text = m_popupClient->itemText(i);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100744 int width = 0;
745 if (!text.isEmpty())
746 width = itemFont.width(TextRun(text));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100747
748 baseWidth = max(baseWidth, width);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100749 // FIXME: http://b/1210481 We should get the padding of individual
750 // option elements.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100751 paddingWidth = max<int>(paddingWidth,
752 m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight());
753 lineEndPaddingWidth = max<int>(lineEndPaddingWidth,
754 isRightAligned ? m_popupClient->clientPaddingLeft() : m_popupClient->clientPaddingRight());
755 }
756
757 // Calculate scroll bar width.
758 int windowHeight = 0;
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100759 m_visibleRows = std::min(numItems(), maxVisibleRows);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100760
761 for (int i = 0; i < m_visibleRows; ++i) {
762 int rowHeight = getRowHeight(i);
763
764 // Only clip the window height for non-Mac platforms.
765 if (windowHeight + rowHeight > m_maxHeight) {
766 m_visibleRows = i;
767 break;
768 }
769
770 windowHeight += rowHeight;
771 }
772
773 // Set our widget and scrollable contents sizes.
774 int scrollbarWidth = 0;
775 if (m_visibleRows < numItems()) {
776 scrollbarWidth = ScrollbarTheme::theme()->scrollbarThickness();
777
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100778 // Use minEndOfLinePadding when there is a scrollbar so that we use
779 // as much as (lineEndPaddingWidth - minEndOfLinePadding) padding
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100780 // space for scrollbar and allow user to use CSS padding to make the
781 // popup listbox align with the select element.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100782 paddingWidth = paddingWidth - lineEndPaddingWidth + minEndOfLinePadding;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100783 }
784
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000785 int windowWidth = baseWidth + scrollbarWidth + paddingWidth;
786 if (windowWidth > m_maxWindowWidth) {
787 // windowWidth exceeds m_maxWindowWidth, so we have to clip.
788 windowWidth = m_maxWindowWidth;
789 baseWidth = windowWidth - scrollbarWidth - paddingWidth;
790 m_baseWidth = baseWidth;
791 }
792 int contentWidth = windowWidth - scrollbarWidth;
793
794 if (windowWidth < m_baseWidth) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100795 windowWidth = m_baseWidth;
796 contentWidth = m_baseWidth - scrollbarWidth;
797 } else {
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000798 m_baseWidth = baseWidth;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100799 }
800
801 resize(windowWidth, windowHeight);
802 setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
803
804 if (hostWindow())
805 scrollToRevealSelection();
806
807 invalidate();
808}
809
810void PopupListBox::clear()
811{
812 for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it)
813 delete *it;
814 m_items.clear();
815}
816
817bool PopupListBox::isPointInBounds(const IntPoint& point)
818{
819 return numItems() && IntRect(0, 0, width(), height()).contains(point);
820}
821
822int PopupListBox::popupContentHeight() const
823{
824 return height();
825}
826
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000827} // namespace blink