initial import
[vuplus_webkit] / Source / WebCore / platform / chromium / PopupListBox.cpp
1 /*
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  */
30 #include "config.h"
31 #include "PopupListBox.h"
32
33 #include "Font.h"
34 #include "FontSelector.h"
35 #include "FramelessScrollViewClient.h"
36 #include "GraphicsContext.h"
37 #include "IntRect.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"
49 #include "TextRun.h"
50 #include <limits>
51 #include <wtf/CurrentTime.h>
52
53 #if ENABLE(GESTURE_EVENTS)
54 #include "PlatformGestureEvent.h"
55 #endif
56
57 #if ENABLE(TOUCH_EVENTS)
58 #include "PlatformTouchEvent.h"
59 #endif
60
61 namespace WebCore {
62
63 using namespace std;
64 using namespace WTF;
65 using namespace Unicode;
66
67 PopupListBox::PopupListBox(PopupMenuClient* client, const PopupContainerSettings& settings)
68     : m_settings(settings)
69     , m_originalIndex(0)
70     , m_selectedIndex(0)
71     , m_acceptedIndexOnAbandon(-1)
72     , m_visibleRows(0)
73     , m_baseWidth(0)
74     , m_maxHeight(kMaxHeight)
75     , m_popupClient(client)
76     , m_repeatingChar(0)
77     , m_lastCharTime(0)
78     , m_maxWindowWidth(std::numeric_limits<int>::max())
79 {
80     setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
81 }
82
83 bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event)
84 {
85     Scrollbar* scrollbar = scrollbarAtPoint(event.pos());
86     if (scrollbar) {
87         m_capturingScrollbar = scrollbar;
88         m_capturingScrollbar->mouseDown(event);
89         return true;
90     }
91
92     if (!isPointInBounds(event.pos()))
93         abandon();
94
95     return true;
96 }
97
98 bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event)
99 {
100     if (m_capturingScrollbar) {
101         m_capturingScrollbar->mouseMoved(event);
102         return true;
103     }
104
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;
111     }
112
113     if (scrollbar) {
114         scrollbar->mouseMoved(event);
115         return true;
116     }
117
118     if (!isPointInBounds(event.pos()))
119         return false;
120
121     selectIndex(pointToRowIndex(event.pos()));
122     return true;
123 }
124
125 bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event)
126 {
127     if (m_capturingScrollbar) {
128         m_capturingScrollbar->mouseUp();
129         m_capturingScrollbar = 0;
130         return true;
131     }
132
133     if (!isPointInBounds(event.pos()))
134         return true;
135
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);
141
142         // Clear m_focusedNode here, because we cannot clear in hidePopup() which is called before dispatchMouseEvent() is called.
143         m_focusedNode = 0;
144     }
145
146     return true;
147 }
148
149 bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event)
150 {
151     if (!isPointInBounds(event.pos())) {
152         abandon();
153         return true;
154     }
155
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));
159     return true;
160 }
161
162 // Should be kept in sync with handleKeyEvent().
163 bool 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
181 #if ENABLE(TOUCH_EVENTS)
182 bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&)
183 {
184     return false;
185 }
186 #endif
187
188 #if ENABLE(GESTURE_RECOGNIZER)
189 bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&)
190 {
191     return false;
192 }
193 #endif
194
195 static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event)
196 {
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;
202 }
203
204 bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event)
205 {
206     if (event.type() == PlatformKeyboardEvent::KeyUp)
207         return true;
208
209     if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE)
210         return true;
211
212     switch (event.windowsVirtualKeyCode()) {
213     case VKEY_ESCAPE:
214         abandon(); // may delete this
215         return true;
216     case VKEY_RETURN:
217         if (m_selectedIndex == -1)  {
218             hidePopup();
219             // Don't eat the enter if nothing is selected.
220             return false;
221         }
222         acceptIndex(m_selectedIndex); // may delete this
223         return true;
224     case VKEY_UP:
225     case VKEY_DOWN:
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)
232             selectPreviousRow();
233         else
234             selectNextRow();
235         break;
236     case VKEY_PRIOR:
237         adjustSelectedIndex(-m_visibleRows);
238         break;
239     case VKEY_NEXT:
240         adjustSelectedIndex(m_visibleRows);
241         break;
242     case VKEY_HOME:
243         adjustSelectedIndex(-m_selectedIndex);
244         break;
245     case VKEY_END:
246         adjustSelectedIndex(m_items.size());
247         break;
248     default:
249         if (!event.ctrlKey() && !event.altKey() && !event.metaKey()
250             && isPrintableChar(event.windowsVirtualKeyCode())
251             && isCharacterTypeEvent(event))
252             typeAheadFind(event);
253         break;
254     }
255
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
260         // popup is closed.
261         if (m_settings.acceptOnAbandon)
262             m_acceptedIndexOnAbandon = m_selectedIndex;
263
264         setOriginalIndex(m_selectedIndex);
265         if (m_settings.setTextOnIndexChange)
266             m_popupClient->setTextFromItem(m_selectedIndex);
267     }
268     if (event.windowsVirtualKeyCode() == VKEY_TAB) {
269         // TAB is a special case as it should select the current item if any and
270         // advance focus.
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.
274             return false;
275         }
276         // Call abandon() so we honor m_acceptedIndexOnAbandon if set.
277         abandon();
278         // Return false so the TAB key event is propagated to the page.
279         return false;
280     }
281
282     return true;
283 }
284
285 HostWindow* PopupListBox::hostWindow() const
286 {
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;
290 }
291
292 // From HTMLSelectElement.cpp
293 static String stripLeadingWhiteSpace(const String& string)
294 {
295     int length = string.length();
296     int i;
297     for (i = 0; i < length; ++i)
298         if (string[i] != noBreakSpace
299             && (string[i] <= 0x7F ? !isspace(string[i]) : (direction(string[i]) != WhiteSpaceNeutral)))
300             break;
301
302     return string.substring(i, length - i);
303 }
304
305 // From HTMLSelectElement.cpp, with modifications
306 void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event)
307 {
308     TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f);
309     TimeStamp delta = now - m_lastCharTime;
310
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;
315
316     UChar c = event.windowsVirtualKeyCode();
317
318     String prefix;
319     int searchStartOffset = 1;
320     if (delta > kTypeAheadTimeoutMs) {
321         m_typedString = prefix = String(&c, 1);
322         m_repeatingChar = c;
323     } else {
324         m_typedString.append(c);
325
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);
329         else {
330             m_repeatingChar = 0;
331             prefix = m_typedString;
332             searchStartOffset = 0;
333         }
334     }
335
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))
345             continue;
346
347         if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) {
348             selectIndex(index);
349             return;
350         }
351     }
352 }
353
354 void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect)
355 {
356     // adjust coords for scrolled frame
357     IntRect r = intersection(rect, frameRect());
358     int tx = x() - scrollX();
359     int ty = y() - scrollY();
360
361     r.move(-tx, -ty);
362
363     // set clip rect to match revised damage rect
364     gc->save();
365     gc->translate(static_cast<float>(tx), static_cast<float>(ty));
366     gc->clip(r);
367
368     // FIXME: Can we optimize scrolling to not require repainting the entire
369     // window? Should we?
370     for (int i = 0; i < numItems(); ++i)
371         paintRow(gc, r, i);
372
373     // Special case for an empty popup.
374     if (!numItems())
375         gc->fillRect(r, Color::white, ColorSpaceDeviceRGB);
376
377     gc->restore();
378
379     ScrollView::paint(gc, rect);
380 }
381
382 static const int separatorPadding = 4;
383 static const int separatorHeight = 1;
384
385 void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex)
386 {
387     // This code is based largely on RenderListBox::paint* methods.
388
389     IntRect rowRect = getRowBounds(rowIndex);
390     if (!rowRect.intersects(rect))
391         return;
392
393     PopupMenuStyle style = m_popupClient->itemStyle(rowIndex);
394
395     // Paint background
396     Color backColor, textColor, labelColor;
397     if (rowIndex == m_selectedIndex) {
398         backColor = RenderTheme::defaultTheme()->activeListBoxSelectionBackgroundColor();
399         textColor = RenderTheme::defaultTheme()->activeListBoxSelectionForegroundColor();
400         labelColor = textColor;
401     } else {
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);
407     }
408
409     // If we have a transparent background, make sure it has a color to blend
410     // against.
411     if (backColor.hasAlpha())
412         gc->fillRect(rowRect, Color::white, ColorSpaceDeviceRGB);
413
414     gc->fillRect(rowRect, backColor, ColorSpaceDeviceRGB);
415
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);
425         return;
426     }
427
428     if (!style.isVisible())
429         return;
430
431     gc->setFillColor(textColor, ColorSpaceDeviceRGB);
432
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;
437     int textX = 0;
438     int maxWidth = 0;
439     if (rightAligned)
440         maxWidth = rowRect.width() - max(0, m_popupClient->clientPaddingRight() - m_popupClient->clientInsetRight());
441     else {
442         textX = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft());
443         maxWidth = rowRect.width() - textX;
444     }
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) {
454             itemText = str;
455             // Don't display the label or icon, we already don't have enough room for the item text.
456             itemLabel = "";
457             itemIcon = "";
458         } else if (!itemLabel.isEmpty()) {
459             int availableWidth = maxWidth - kTextToLabelPadding -
460                 StringTruncator::width(itemText, itemFont);
461             itemLabel = StringTruncator::rightTruncate(itemLabel, availableWidth, itemFont);
462         }
463     }
464
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.
469     if (rightAligned)
470         textX += maxWidth - itemFont.width(textRun);
471
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));
475
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;
480
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);
489     }
490
491     // Draw the the label if applicable.
492     if (itemLabel.isEmpty())
493         return;
494
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());
501         itemFont.update(0);
502     }
503
504     TextRun labelTextRun(itemLabel.characters(), itemLabel.length(), false, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride());
505     if (rightAligned)
506         textX = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft());
507     else
508         textX = remainingWidth - itemFont.width(labelTextRun);
509
510     gc->setFillColor(labelColor, ColorSpaceDeviceRGB);
511     gc->drawBidiText(itemFont, labelTextRun, IntPoint(textX, textY));
512 }
513
514 Font PopupListBox::getRowFont(int rowIndex)
515 {
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());
522         font.update(0);
523         return font;
524     }
525
526     return itemFont;
527 }
528
529 void PopupListBox::abandon()
530 {
531     RefPtr<PopupListBox> keepAlive(this);
532
533     m_selectedIndex = m_originalIndex;
534
535     hidePopup();
536
537     if (m_acceptedIndexOnAbandon >= 0) {
538         if (m_popupClient)
539             m_popupClient->valueChanged(m_acceptedIndexOnAbandon);
540         m_acceptedIndexOnAbandon = -1;
541     }
542 }
543
544 int PopupListBox::pointToRowIndex(const IntPoint& point)
545 {
546     int y = scrollY() + point.y();
547
548     // FIXME: binary search if perf matters.
549     for (int i = 0; i < numItems(); ++i) {
550         if (y < m_items[i]->yOffset)
551             return i-1;
552     }
553
554     // Last item?
555     if (y < contentsHeight())
556         return m_items.size()-1;
557
558     return -1;
559 }
560
561 bool PopupListBox::acceptIndex(int index)
562 {
563     // Clear m_acceptedIndexOnAbandon once user accepts the selected index.
564     if (m_acceptedIndexOnAbandon >= 0)
565         m_acceptedIndexOnAbandon = -1;
566
567     if (index >= numItems())
568         return false;
569
570     if (index < 0) {
571         if (m_popupClient) {
572             // Enter pressed with no selection, just close the popup.
573             hidePopup();
574         }
575         return false;
576     }
577
578     if (isSelectableItem(index)) {
579         RefPtr<PopupListBox> keepAlive(this);
580
581         // Hide ourselves first since valueChanged may have numerous side-effects.
582         hidePopup();
583
584         // Tell the <select> PopupMenuClient what index was selected.
585         m_popupClient->valueChanged(index);
586
587         return true;
588     }
589
590     return false;
591 }
592
593 void PopupListBox::selectIndex(int index)
594 {
595     if (index < 0 || index >= numItems())
596         return;
597
598     bool isSelectable = isSelectableItem(index);
599     if (index != m_selectedIndex && isSelectable) {
600         invalidateRow(m_selectedIndex);
601         m_selectedIndex = index;
602         invalidateRow(m_selectedIndex);
603
604         scrollToRevealSelection();
605         m_popupClient->selectionChanged(m_selectedIndex);
606     } else if (!isSelectable)
607         clearSelection();
608 }
609
610 void PopupListBox::setOriginalIndex(int index)
611 {
612     m_originalIndex = m_selectedIndex = index;
613 }
614
615 int PopupListBox::getRowHeight(int index)
616 {
617     if (index < 0)
618         return PopupMenuChromium::minimumRowHeight();
619
620     if (m_popupClient->itemStyle(index).isDisplayNone())
621         return PopupMenuChromium::minimumRowHeight();
622
623     // Separator row height is the same size as itself.
624     if (m_popupClient->itemIsSeparator(index))
625         return max(separatorHeight, PopupMenuChromium::minimumRowHeight());
626
627     String icon = m_popupClient->itemIcon(index);
628     RefPtr<Image> image(Image::loadPlatformResource(icon.utf8().data()));
629
630     int fontHeight = getRowFont(index).fontMetrics().height();
631     int iconHeight = (image && !image->isNull()) ? image->rect().height() : 0;
632
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());
636 }
637
638 IntRect PopupListBox::getRowBounds(int index)
639 {
640     if (index < 0)
641         return IntRect(0, 0, visibleWidth(), getRowHeight(index));
642
643     return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index));
644 }
645
646 void PopupListBox::invalidateRow(int index)
647 {
648     if (index < 0)
649         return;
650
651     // Invalidate in the window contents, as FramelessScrollView::invalidateRect
652     // paints in the window coordinates.
653     invalidateRect(contentsToWindow(getRowBounds(index)));
654 }
655
656 void PopupListBox::scrollToRevealRow(int index)
657 {
658     if (index < 0)
659         return;
660
661     IntRect rowRect = getRowBounds(index);
662
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()));
669     }
670 }
671
672 bool PopupListBox::isSelectableItem(int index)
673 {
674     ASSERT(index >= 0 && index < numItems());
675     return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index);
676 }
677
678 void PopupListBox::clearSelection()
679 {
680     if (m_selectedIndex != -1) {
681         invalidateRow(m_selectedIndex);
682         m_selectedIndex = -1;
683         m_popupClient->selectionCleared();
684     }
685 }
686
687 void PopupListBox::selectNextRow()
688 {
689     if (!m_settings.loopSelectionNavigation || m_selectedIndex != numItems() - 1) {
690         adjustSelectedIndex(1);
691         return;
692     }
693
694     // We are moving past the last item, no row should be selected.
695     clearSelection();
696 }
697
698 void PopupListBox::selectPreviousRow()
699 {
700     if (!m_settings.loopSelectionNavigation || m_selectedIndex > 0) {
701         adjustSelectedIndex(-1);
702         return;
703     }
704
705     if (!m_selectedIndex) {
706         // We are moving past the first item, clear the selection.
707         clearSelection();
708         return;
709     }
710
711     // No row is selected, jump to the last item.
712     selectIndex(numItems() - 1);
713     scrollToRevealSelection();
714 }
715
716 void PopupListBox::adjustSelectedIndex(int delta)
717 {
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].
724
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)
733                 passedTarget = true;
734             if (passedTarget && bestIndex != m_selectedIndex)
735                 break;
736
737             testIndex += dir;
738         }
739
740         // Pick the best index, which may mean we don't change.
741         targetIndex = bestIndex;
742     }
743
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();
749 }
750
751 void PopupListBox::hidePopup()
752 {
753     if (parent()) {
754         PopupContainer* container = static_cast<PopupContainer*>(parent());
755         if (container->client())
756             container->client()->popupClosed(container);
757         container->notifyPopupHidden();
758     }
759
760     if (m_popupClient)
761         m_popupClient->popupDidHide();
762 }
763
764 void PopupListBox::updateFromElement()
765 {
766     clear();
767
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;
775         else
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();
782     }
783
784     m_selectedIndex = m_popupClient->selectedIndex();
785     setOriginalIndex(m_selectedIndex);
786
787     layout();
788 }
789
790 void PopupListBox::setMaxWidthAndLayout(int maxWidth)
791 {
792     m_maxWindowWidth = maxWidth;
793     layout();
794 }
795
796 void PopupListBox::layout()
797 {
798     bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL;
799
800     // Size our child items.
801     int baseWidth = 0;
802     int paddingWidth = 0;
803     int lineEndPaddingWidth = 0;
804     int y = 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())
809             continue;
810         y += getRowHeight(i);
811
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()));
818         int width = 0;
819         if (!text.isEmpty())
820             width = itemFont.width(TextRun(text));
821         if (!label.isEmpty()) {
822             if (width > 0)
823                 width += kTextToLabelPadding;
824             width += itemFont.width(TextRun(label));
825         }
826         if (iconImage && !iconImage->isNull()) {
827             if (width > 0)
828                 width += kLabelToIconPadding;
829             width += iconImage->rect().width();
830         }
831
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());
838     }
839
840     // Calculate scroll bar width.
841     int windowHeight = 0;
842     m_visibleRows = min(numItems(), kMaxVisibleRows);
843
844     for (int i = 0; i < m_visibleRows; ++i) {
845         int rowHeight = getRowHeight(i);
846
847         // Only clip the window height for non-Mac platforms.
848         if (windowHeight + rowHeight > m_maxHeight) {
849             m_visibleRows = i;
850             break;
851         }
852
853         windowHeight += rowHeight;
854     }
855
856     // Set our widget and scrollable contents sizes.
857     int scrollbarWidth = 0;
858     if (m_visibleRows < numItems()) {
859         scrollbarWidth = ScrollbarTheme::nativeTheme()->scrollbarThickness();
860
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;
866     }
867
868     int windowWidth;
869     int contentWidth;
870     if (m_settings.restrictWidthOfListBox) {
871         windowWidth = m_baseWidth;
872         contentWidth = m_baseWidth - scrollbarWidth;
873     } else {
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;
880         }
881         contentWidth = windowWidth - scrollbarWidth;
882
883         if (windowWidth < m_baseWidth) {
884             windowWidth = m_baseWidth;
885             contentWidth = m_baseWidth - scrollbarWidth;
886         } else
887             m_baseWidth = baseWidth;
888     }
889
890     resize(windowWidth, windowHeight);
891     setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY()));
892
893     if (hostWindow())
894         scrollToRevealSelection();
895
896     invalidate();
897 }
898
899 void PopupListBox::clear()
900 {
901     for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it)
902         delete *it;
903     m_items.clear();
904 }
905
906 bool PopupListBox::isPointInBounds(const IntPoint& point)
907 {
908     return numItems() && IntRect(0, 0, width(), height()).contains(point);
909 }
910
911 } // namespace WebCore