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 31 #include "config.h" 32 #include "PopupListBox.h" 33 34 #include "CSSValueKeywords.h" 35 #include "PopupContainer.h" 36 #include "PopupMenuChromium.h" 37 #include "RuntimeEnabledFeatures.h" 38 #include "core/rendering/RenderTheme.h" 39 #include "platform/KeyboardCodes.h" 40 #include "platform/PlatformGestureEvent.h" 41 #include "platform/PlatformKeyboardEvent.h" 42 #include "platform/PlatformMouseEvent.h" 43 #include "platform/PlatformScreen.h" 44 #include "platform/PlatformTouchEvent.h" 45 #include "platform/PlatformWheelEvent.h" 46 #include "platform/PopupMenuClient.h" 47 #include "platform/fonts/Font.h" 48 #include "platform/fonts/FontCache.h" 49 #include "platform/fonts/FontSelector.h" 50 #include "platform/geometry/IntRect.h" 51 #include "platform/graphics/GraphicsContext.h" 52 #include "platform/scroll/FramelessScrollViewClient.h" 53 #include "platform/scroll/ScrollbarTheme.h" 54 #include "platform/text/StringTruncator.h" 55 #include "platform/text/TextRun.h" 56 #include "wtf/ASCIICType.h" 57 #include "wtf/CurrentTime.h" 58 #include <limits> 59 60 namespace WebCore { 61 62 using namespace WTF::Unicode; 63 64 static const int labelToIconPadding = 5; 65 // Padding height put at the top and bottom of each line. 66 static const int autofillLinePaddingHeight = 3; 67 const int PopupListBox::defaultMaxHeight = 500; 68 static const int maxVisibleRows = 20; 69 static const int minEndOfLinePadding = 2; 70 static const int textToLabelPadding = 10; 71 static const TimeStamp typeAheadTimeoutMs = 1000; 72 73 PopupListBox::PopupListBox(PopupMenuClient* client, const PopupContainerSettings& settings) 74 : m_settings(settings) 75 , m_originalIndex(0) 76 , m_selectedIndex(0) 77 , m_acceptedIndexOnAbandon(-1) 78 , m_visibleRows(0) 79 , m_baseWidth(0) 80 , m_maxHeight(defaultMaxHeight) 81 , m_popupClient(client) 82 , m_repeatingChar(0) 83 , m_lastCharTime(0) 84 , m_maxWindowWidth(std::numeric_limits<int>::max()) 85 { 86 setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff); 87 } 88 89 bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event) 90 { 91 Scrollbar* scrollbar = scrollbarAtPoint(event.position()); 92 if (scrollbar) { 93 m_capturingScrollbar = scrollbar; 94 m_capturingScrollbar->mouseDown(event); 95 return true; 96 } 97 98 if (!isPointInBounds(event.position())) 99 abandon(); 100 101 return true; 102 } 103 104 bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event) 105 { 106 if (m_capturingScrollbar) { 107 m_capturingScrollbar->mouseMoved(event); 108 return true; 109 } 110 111 Scrollbar* scrollbar = scrollbarAtPoint(event.position()); 112 if (m_lastScrollbarUnderMouse != scrollbar) { 113 // Send mouse exited to the old scrollbar. 114 if (m_lastScrollbarUnderMouse) 115 m_lastScrollbarUnderMouse->mouseExited(); 116 m_lastScrollbarUnderMouse = scrollbar; 117 } 118 119 if (scrollbar) { 120 scrollbar->mouseMoved(event); 121 return true; 122 } 123 124 if (!isPointInBounds(event.position())) 125 return false; 126 127 selectIndex(pointToRowIndex(event.position())); 128 return true; 129 } 130 131 bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event) 132 { 133 if (m_capturingScrollbar) { 134 m_capturingScrollbar->mouseUp(event); 135 m_capturingScrollbar = 0; 136 return true; 137 } 138 139 if (!isPointInBounds(event.position())) 140 return true; 141 142 // Need to check before calling acceptIndex(), because m_popupClient might 143 // be removed in acceptIndex() calling because of event handler. 144 bool isSelectPopup = m_popupClient->menuStyle().menuType() == PopupMenuStyle::SelectPopup; 145 if (acceptIndex(pointToRowIndex(event.position())) && m_focusedElement && isSelectPopup) { 146 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::mouseup); 147 m_focusedElement->dispatchMouseEvent(event, EventTypeNames::click); 148 149 // Clear m_focusedElement here, because we cannot clear in hidePopup() 150 // which is called before dispatchMouseEvent() is called. 151 m_focusedElement = 0; 152 } 153 154 return true; 155 } 156 157 bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event) 158 { 159 if (!isPointInBounds(event.position())) { 160 abandon(); 161 return true; 162 } 163 164 ScrollableArea::handleWheelEvent(event); 165 return true; 166 } 167 168 // Should be kept in sync with handleKeyEvent(). 169 bool PopupListBox::isInterestedInEventForKey(int keyCode) 170 { 171 switch (keyCode) { 172 case VKEY_ESCAPE: 173 case VKEY_RETURN: 174 case VKEY_UP: 175 case VKEY_DOWN: 176 case VKEY_PRIOR: 177 case VKEY_NEXT: 178 case VKEY_HOME: 179 case VKEY_END: 180 case VKEY_TAB: 181 return true; 182 default: 183 return false; 184 } 185 } 186 187 bool PopupListBox::handleTouchEvent(const PlatformTouchEvent&) 188 { 189 return false; 190 } 191 192 bool PopupListBox::handleGestureEvent(const PlatformGestureEvent&) 193 { 194 return false; 195 } 196 197 static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event) 198 { 199 // Check whether the event is a character-typed event or not. 200 // We use RawKeyDown/Char/KeyUp event scheme on all platforms, 201 // so PlatformKeyboardEvent::Char (not RawKeyDown) type event 202 // is considered as character type event. 203 return event.type() == PlatformEvent::Char; 204 } 205 206 bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event) 207 { 208 if (event.type() == PlatformEvent::KeyUp) 209 return true; 210 211 if (!numItems() && event.windowsVirtualKeyCode() != VKEY_ESCAPE) 212 return true; 213 214 switch (event.windowsVirtualKeyCode()) { 215 case VKEY_ESCAPE: 216 abandon(); // may delete this 217 return true; 218 case VKEY_RETURN: 219 if (m_selectedIndex == -1) { 220 hidePopup(); 221 // Don't eat the enter if nothing is selected. 222 return false; 223 } 224 acceptIndex(m_selectedIndex); // may delete this 225 return true; 226 case VKEY_UP: 227 case VKEY_DOWN: 228 // We have to forward only shift + up combination to focused node when 229 // autofill popup. Because all characters from the cursor to the start 230 // of the text area should selected when you press shift + up arrow. 231 // shift + down should be the similar way to shift + up. 232 if (event.modifiers() && m_popupClient->menuStyle().menuType() == PopupMenuStyle::AutofillPopup) 233 m_focusedElement->dispatchKeyEvent(event); 234 else if (event.windowsVirtualKeyCode() == VKEY_UP) 235 selectPreviousRow(); 236 else 237 selectNextRow(); 238 break; 239 case VKEY_PRIOR: 240 adjustSelectedIndex(-m_visibleRows); 241 break; 242 case VKEY_NEXT: 243 adjustSelectedIndex(m_visibleRows); 244 break; 245 case VKEY_HOME: 246 adjustSelectedIndex(-m_selectedIndex); 247 break; 248 case VKEY_END: 249 adjustSelectedIndex(m_items.size()); 250 break; 251 default: 252 if (!event.ctrlKey() && !event.altKey() && !event.metaKey() 253 && isPrintableChar(event.windowsVirtualKeyCode()) 254 && isCharacterTypeEvent(event)) 255 typeAheadFind(event); 256 break; 257 } 258 259 if (m_originalIndex != m_selectedIndex) { 260 // Keyboard events should update the selection immediately (but we don't 261 // want to fire the onchange event until the popup is closed, to match 262 // IE). We change the original index so we revert to that when the 263 // popup is closed. 264 if (m_settings.acceptOnAbandon) 265 m_acceptedIndexOnAbandon = m_selectedIndex; 266 267 setOriginalIndex(m_selectedIndex); 268 if (m_settings.setTextOnIndexChange) 269 m_popupClient->setTextFromItem(m_selectedIndex); 270 } 271 if (event.windowsVirtualKeyCode() == VKEY_TAB) { 272 // TAB is a special case as it should select the current item if any and 273 // advance focus. 274 if (m_selectedIndex >= 0) { 275 acceptIndex(m_selectedIndex); // May delete us. 276 // Return false so the TAB key event is propagated to the page. 277 return false; 278 } 279 // Call abandon() so we honor m_acceptedIndexOnAbandon if set. 280 abandon(); 281 // Return false so the TAB key event is propagated to the page. 282 return false; 283 } 284 285 return true; 286 } 287 288 HostWindow* PopupListBox::hostWindow() const 289 { 290 // Our parent is the root ScrollView, so it is the one that has a 291 // HostWindow. FrameView::hostWindow() works similarly. 292 return parent() ? parent()->hostWindow() : 0; 293 } 294 295 bool PopupListBox::shouldPlaceVerticalScrollbarOnLeft() const 296 { 297 return m_popupClient->menuStyle().textDirection() == RTL; 298 } 299 300 // From HTMLSelectElement.cpp 301 static String stripLeadingWhiteSpace(const String& string) 302 { 303 int length = string.length(); 304 int i; 305 for (i = 0; i < length; ++i) 306 if (string[i] != noBreakSpace 307 && (string[i] <= 0x7F ? !isASCIISpace(string[i]) : (direction(string[i]) != WhiteSpaceNeutral))) 308 break; 309 310 return string.substring(i, length - i); 311 } 312 313 // From HTMLSelectElement.cpp, with modifications 314 void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event) 315 { 316 TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f); 317 TimeStamp delta = now - m_lastCharTime; 318 319 // Reset the time when user types in a character. The time gap between 320 // last character and the current character is used to indicate whether 321 // user typed in a string or just a character as the search prefix. 322 m_lastCharTime = now; 323 324 UChar c = event.windowsVirtualKeyCode(); 325 326 String prefix; 327 int searchStartOffset = 1; 328 if (delta > typeAheadTimeoutMs) { 329 m_typedString = prefix = String(&c, 1); 330 m_repeatingChar = c; 331 } else { 332 m_typedString.append(c); 333 334 if (c == m_repeatingChar) { 335 // The user is likely trying to cycle through all the items starting 336 // with this character, so just search on the character. 337 prefix = String(&c, 1); 338 } else { 339 m_repeatingChar = 0; 340 prefix = m_typedString; 341 searchStartOffset = 0; 342 } 343 } 344 345 // Compute a case-folded copy of the prefix string before beginning the 346 // search for a matching element. This code uses foldCase to work around the 347 // fact that String::startWith does not fold non-ASCII characters. This code 348 // can be changed to use startWith once that is fixed. 349 String prefixWithCaseFolded(prefix.foldCase()); 350 int itemCount = numItems(); 351 int index = (max(0, m_selectedIndex) + searchStartOffset) % itemCount; 352 for (int i = 0; i < itemCount; i++, index = (index + 1) % itemCount) { 353 if (!isSelectableItem(index)) 354 continue; 355 356 if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) { 357 selectIndex(index); 358 return; 359 } 360 } 361 } 362 363 void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect) 364 { 365 // Adjust coords for scrolled frame. 366 IntRect r = intersection(rect, frameRect()); 367 int tx = x() - scrollX() + ((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) ? verticalScrollbar()->width() : 0); 368 int ty = y() - scrollY(); 369 370 r.move(-tx, -ty); 371 372 // Set clip rect to match revised damage rect. 373 gc->save(); 374 gc->translate(static_cast<float>(tx), static_cast<float>(ty)); 375 gc->clip(r); 376 377 // FIXME: Can we optimize scrolling to not require repainting the entire 378 // window? Should we? 379 for (int i = 0; i < numItems(); ++i) 380 paintRow(gc, r, i); 381 382 // Special case for an empty popup. 383 if (!numItems()) 384 gc->fillRect(r, Color::white); 385 386 gc->restore(); 387 388 ScrollView::paint(gc, rect); 389 } 390 391 static const int separatorPadding = 4; 392 static const int separatorHeight = 1; 393 394 void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex) 395 { 396 // This code is based largely on RenderListBox::paint* methods. 397 398 IntRect rowRect = getRowBounds(rowIndex); 399 if (!rowRect.intersects(rect)) 400 return; 401 402 PopupMenuStyle style = m_popupClient->itemStyle(rowIndex); 403 404 // Paint background 405 Color backColor, textColor, labelColor; 406 if (rowIndex == m_selectedIndex) { 407 backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor(); 408 textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor(); 409 labelColor = textColor; 410 } else { 411 backColor = style.backgroundColor(); 412 textColor = style.foregroundColor(); 413 414 #if OS(LINUX) || OS(ANDROID) 415 // On other platforms, the <option> background color is the same as the 416 // <select> background color. On Linux, that makes the <option> 417 // background color very dark, so by default, try to use a lighter 418 // background color for <option>s. 419 if (style.backgroundColorType() == PopupMenuStyle::DefaultBackgroundColor && RenderTheme::theme().systemColor(CSSValueButtonface) == backColor) 420 backColor = RenderTheme::theme().systemColor(CSSValueMenu); 421 #endif 422 423 // FIXME: for now the label color is hard-coded. It should be added to 424 // the PopupMenuStyle. 425 labelColor = Color(115, 115, 115); 426 } 427 428 // If we have a transparent background, make sure it has a color to blend 429 // against. 430 if (backColor.hasAlpha()) 431 gc->fillRect(rowRect, Color::white); 432 433 gc->fillRect(rowRect, backColor); 434 435 // It doesn't look good but Autofill requires special style for separator. 436 // Autofill doesn't have padding and #dcdcdc color. 437 if (m_popupClient->itemIsSeparator(rowIndex)) { 438 int padding = style.menuType() == PopupMenuStyle::AutofillPopup ? 0 : separatorPadding; 439 IntRect separatorRect( 440 rowRect.x() + padding, 441 rowRect.y() + (rowRect.height() - separatorHeight) / 2, 442 rowRect.width() - 2 * padding, separatorHeight); 443 gc->fillRect(separatorRect, style.menuType() == PopupMenuStyle::AutofillPopup ? Color(0xdc, 0xdc, 0xdc) : textColor); 444 return; 445 } 446 447 if (!style.isVisible()) 448 return; 449 450 gc->setFillColor(textColor); 451 452 FontCachePurgePreventer fontCachePurgePreventer; 453 454 Font itemFont = getRowFont(rowIndex); 455 // FIXME: http://crbug.com/19872 We should get the padding of individual option 456 // elements. This probably implies changes to PopupMenuClient. 457 bool rightAligned = m_popupClient->menuStyle().textDirection() == RTL; 458 int textX = 0; 459 int maxWidth = 0; 460 if (rightAligned) 461 maxWidth = rowRect.width() - max<int>(0, m_popupClient->clientPaddingRight() - m_popupClient->clientInsetRight()); 462 else { 463 textX = max<int>(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft()); 464 maxWidth = rowRect.width() - textX; 465 } 466 // Prepare text to be drawn. 467 String itemText = m_popupClient->itemText(rowIndex); 468 String itemLabel = m_popupClient->itemLabel(rowIndex); 469 String itemIcon = m_popupClient->itemIcon(rowIndex); 470 if (m_settings.restrictWidthOfListBox) { // Truncate strings to fit in. 471 // FIXME: We should leftTruncate for the rtl case. 472 // StringTruncator::leftTruncate would have to be implemented. 473 String str = StringTruncator::rightTruncate(itemText, maxWidth, itemFont); 474 if (str != itemText) { 475 itemText = str; 476 // Don't display the label or icon, we already don't have enough 477 // room for the item text. 478 itemLabel = ""; 479 itemIcon = ""; 480 } else if (!itemLabel.isEmpty()) { 481 int availableWidth = maxWidth - textToLabelPadding - StringTruncator::width(itemText, itemFont); 482 itemLabel = StringTruncator::rightTruncate(itemLabel, availableWidth, itemFont); 483 } 484 } 485 486 // Prepare the directionality to draw text. 487 TextRun textRun(itemText, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride()); 488 // If the text is right-to-left, make it right-aligned by adjusting its 489 // beginning position. 490 if (rightAligned) 491 textX += maxWidth - itemFont.width(textRun); 492 493 // Draw the item text. 494 int textY = rowRect.y() + itemFont.fontMetrics().ascent() + (rowRect.height() - itemFont.fontMetrics().height()) / 2; 495 TextRunPaintInfo textRunPaintInfo(textRun); 496 textRunPaintInfo.bounds = rowRect; 497 gc->drawBidiText(itemFont, textRunPaintInfo, IntPoint(textX, textY)); 498 499 // We are using the left padding as the right padding includes room for the scroll-bar which 500 // does not show in this case. 501 int rightPadding = max<int>(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft()); 502 int remainingWidth = rowRect.width() - rightPadding; 503 504 // Draw the icon if applicable. 505 RefPtr<Image> image(Image::loadPlatformResource(itemIcon.utf8().data())); 506 if (image && !image->isNull()) { 507 IntRect imageRect = image->rect(); 508 remainingWidth -= (imageRect.width() + labelToIconPadding); 509 imageRect.setX(rowRect.width() - rightPadding - imageRect.width()); 510 imageRect.setY(rowRect.y() + (rowRect.height() - imageRect.height()) / 2); 511 gc->drawImage(image.get(), imageRect); 512 } 513 514 // Draw the the label if applicable. 515 if (itemLabel.isEmpty()) 516 return; 517 518 // Autofill label is 0.9 smaller than regular font size. 519 if (style.menuType() == PopupMenuStyle::AutofillPopup) { 520 itemFont = m_popupClient->itemStyle(rowIndex).font(); 521 FontDescription d = itemFont.fontDescription(); 522 d.setComputedSize(d.computedSize() * 0.9); 523 itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing()); 524 itemFont.update(0); 525 } 526 527 TextRun labelTextRun(itemLabel, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride()); 528 if (rightAligned) 529 textX = max<int>(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft()); 530 else 531 textX = remainingWidth - itemFont.width(labelTextRun); 532 TextRunPaintInfo labelTextRunPaintInfo(labelTextRun); 533 labelTextRunPaintInfo.bounds = rowRect; 534 535 gc->setFillColor(labelColor); 536 gc->drawBidiText(itemFont, labelTextRunPaintInfo, IntPoint(textX, textY)); 537 } 538 539 Font PopupListBox::getRowFont(int rowIndex) 540 { 541 Font itemFont = m_popupClient->itemStyle(rowIndex).font(); 542 if (m_popupClient->itemIsLabel(rowIndex)) { 543 // Bold-ify labels (ie, an <optgroup> heading). 544 FontDescription d = itemFont.fontDescription(); 545 d.setWeight(FontWeightBold); 546 Font font(d, itemFont.letterSpacing(), itemFont.wordSpacing()); 547 font.update(0); 548 return font; 549 } 550 551 return itemFont; 552 } 553 554 void PopupListBox::abandon() 555 { 556 RefPtr<PopupListBox> keepAlive(this); 557 558 m_selectedIndex = m_originalIndex; 559 560 hidePopup(); 561 562 if (m_acceptedIndexOnAbandon >= 0) { 563 if (m_popupClient) 564 m_popupClient->valueChanged(m_acceptedIndexOnAbandon); 565 m_acceptedIndexOnAbandon = -1; 566 } 567 } 568 569 int PopupListBox::pointToRowIndex(const IntPoint& point) 570 { 571 int y = scrollY() + point.y(); 572 573 // FIXME: binary search if perf matters. 574 for (int i = 0; i < numItems(); ++i) { 575 if (y < m_items[i]->yOffset) 576 return i-1; 577 } 578 579 // Last item? 580 if (y < contentsHeight()) 581 return m_items.size()-1; 582 583 return -1; 584 } 585 586 bool PopupListBox::acceptIndex(int index) 587 { 588 // Clear m_acceptedIndexOnAbandon once user accepts the selected index. 589 if (m_acceptedIndexOnAbandon >= 0) 590 m_acceptedIndexOnAbandon = -1; 591 592 if (index >= numItems()) 593 return false; 594 595 if (index < 0) { 596 if (m_popupClient) { 597 // Enter pressed with no selection, just close the popup. 598 hidePopup(); 599 } 600 return false; 601 } 602 603 if (isSelectableItem(index)) { 604 RefPtr<PopupListBox> keepAlive(this); 605 606 // Hide ourselves first since valueChanged may have numerous side-effects. 607 hidePopup(); 608 609 // Tell the <select> PopupMenuClient what index was selected. 610 m_popupClient->valueChanged(index); 611 612 return true; 613 } 614 615 return false; 616 } 617 618 void PopupListBox::selectIndex(int index) 619 { 620 if (index < 0 || index >= numItems()) 621 return; 622 623 bool isSelectable = isSelectableItem(index); 624 if (index != m_selectedIndex && isSelectable) { 625 invalidateRow(m_selectedIndex); 626 m_selectedIndex = index; 627 invalidateRow(m_selectedIndex); 628 629 scrollToRevealSelection(); 630 m_popupClient->selectionChanged(m_selectedIndex); 631 } else if (!isSelectable) 632 clearSelection(); 633 } 634 635 void PopupListBox::setOriginalIndex(int index) 636 { 637 m_originalIndex = m_selectedIndex = index; 638 } 639 640 int PopupListBox::getRowHeight(int index) 641 { 642 int minimumHeight = PopupMenuChromium::minimumRowHeight(); 643 if (m_settings.deviceSupportsTouch) 644 minimumHeight = max(minimumHeight, PopupMenuChromium::optionRowHeightForTouch()); 645 646 if (index < 0 || m_popupClient->itemStyle(index).isDisplayNone()) 647 return minimumHeight; 648 649 // Separator row height is the same size as itself. 650 if (m_popupClient->itemIsSeparator(index)) 651 return max(separatorHeight, minimumHeight); 652 653 String icon = m_popupClient->itemIcon(index); 654 RefPtr<Image> image(Image::loadPlatformResource(icon.utf8().data())); 655 656 int fontHeight = getRowFont(index).fontMetrics().height(); 657 int iconHeight = (image && !image->isNull()) ? image->rect().height() : 0; 658 659 int linePaddingHeight = m_popupClient->menuStyle().menuType() == PopupMenuStyle::AutofillPopup ? autofillLinePaddingHeight : 0; 660 int calculatedRowHeight = max(fontHeight, iconHeight) + linePaddingHeight * 2; 661 return max(calculatedRowHeight, minimumHeight); 662 } 663 664 IntRect PopupListBox::getRowBounds(int index) 665 { 666 if (index < 0) 667 return IntRect(0, 0, visibleWidth(), getRowHeight(index)); 668 669 return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index)); 670 } 671 672 void PopupListBox::invalidateRow(int index) 673 { 674 if (index < 0) 675 return; 676 677 // Invalidate in the window contents, as FramelessScrollView::invalidateRect 678 // paints in the window coordinates. 679 IntRect clipRect = contentsToWindow(getRowBounds(index)); 680 if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) 681 clipRect.move(verticalScrollbar()->width(), 0); 682 invalidateRect(clipRect); 683 } 684 685 void PopupListBox::scrollToRevealRow(int index) 686 { 687 if (index < 0) 688 return; 689 690 IntRect rowRect = getRowBounds(index); 691 692 if (rowRect.y() < scrollY()) { 693 // Row is above current scroll position, scroll up. 694 ScrollView::setScrollPosition(IntPoint(0, rowRect.y())); 695 } else if (rowRect.maxY() > scrollY() + visibleHeight()) { 696 // Row is below current scroll position, scroll down. 697 ScrollView::setScrollPosition(IntPoint(0, rowRect.maxY() - visibleHeight())); 698 } 699 } 700 701 bool PopupListBox::isSelectableItem(int index) 702 { 703 ASSERT(index >= 0 && index < numItems()); 704 return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index); 705 } 706 707 void PopupListBox::clearSelection() 708 { 709 if (m_selectedIndex != -1) { 710 invalidateRow(m_selectedIndex); 711 m_selectedIndex = -1; 712 m_popupClient->selectionCleared(); 713 } 714 } 715 716 void PopupListBox::selectNextRow() 717 { 718 if (!m_settings.loopSelectionNavigation || m_selectedIndex != numItems() - 1) { 719 adjustSelectedIndex(1); 720 return; 721 } 722 723 // We are moving past the last item, no row should be selected. 724 clearSelection(); 725 } 726 727 void PopupListBox::selectPreviousRow() 728 { 729 if (!m_settings.loopSelectionNavigation || m_selectedIndex > 0) { 730 adjustSelectedIndex(-1); 731 return; 732 } 733 734 if (!m_selectedIndex) { 735 // We are moving past the first item, clear the selection. 736 clearSelection(); 737 return; 738 } 739 740 // No row is selected, jump to the last item. 741 selectIndex(numItems() - 1); 742 scrollToRevealSelection(); 743 } 744 745 void PopupListBox::adjustSelectedIndex(int delta) 746 { 747 int targetIndex = m_selectedIndex + delta; 748 targetIndex = std::min(std::max(targetIndex, 0), numItems() - 1); 749 if (!isSelectableItem(targetIndex)) { 750 // We didn't land on an option. Try to find one. 751 // We try to select the closest index to target, prioritizing any in 752 // the range [current, target]. 753 754 int dir = delta > 0 ? 1 : -1; 755 int testIndex = m_selectedIndex; 756 int bestIndex = m_selectedIndex; 757 bool passedTarget = false; 758 while (testIndex >= 0 && testIndex < numItems()) { 759 if (isSelectableItem(testIndex)) 760 bestIndex = testIndex; 761 if (testIndex == targetIndex) 762 passedTarget = true; 763 if (passedTarget && bestIndex != m_selectedIndex) 764 break; 765 766 testIndex += dir; 767 } 768 769 // Pick the best index, which may mean we don't change. 770 targetIndex = bestIndex; 771 } 772 773 // Select the new index, and ensure its visible. We do this regardless of 774 // whether the selection changed to ensure keyboard events always bring the 775 // selection into view. 776 selectIndex(targetIndex); 777 scrollToRevealSelection(); 778 } 779 780 void PopupListBox::hidePopup() 781 { 782 if (parent()) { 783 PopupContainer* container = static_cast<PopupContainer*>(parent()); 784 if (container->client()) 785 container->client()->popupClosed(container); 786 container->notifyPopupHidden(); 787 } 788 789 if (m_popupClient) 790 m_popupClient->popupDidHide(); 791 } 792 793 void PopupListBox::updateFromElement() 794 { 795 clear(); 796 797 int size = m_popupClient->listSize(); 798 for (int i = 0; i < size; ++i) { 799 PopupItem::Type type; 800 if (m_popupClient->itemIsSeparator(i)) 801 type = PopupItem::TypeSeparator; 802 else if (m_popupClient->itemIsLabel(i)) 803 type = PopupItem::TypeGroup; 804 else 805 type = PopupItem::TypeOption; 806 m_items.append(new PopupItem(m_popupClient->itemText(i), type)); 807 m_items[i]->enabled = isSelectableItem(i); 808 PopupMenuStyle style = m_popupClient->itemStyle(i); 809 m_items[i]->textDirection = style.textDirection(); 810 m_items[i]->hasTextDirectionOverride = style.hasTextDirectionOverride(); 811 } 812 813 m_selectedIndex = m_popupClient->selectedIndex(); 814 setOriginalIndex(m_selectedIndex); 815 816 layout(); 817 } 818 819 void PopupListBox::setMaxWidthAndLayout(int maxWidth) 820 { 821 m_maxWindowWidth = maxWidth; 822 layout(); 823 } 824 825 void PopupListBox::layout() 826 { 827 bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL; 828 829 // Size our child items. 830 int baseWidth = 0; 831 int paddingWidth = 0; 832 int lineEndPaddingWidth = 0; 833 int y = 0; 834 for (int i = 0; i < numItems(); ++i) { 835 // Place the item vertically. 836 m_items[i]->yOffset = y; 837 if (m_popupClient->itemStyle(i).isDisplayNone()) 838 continue; 839 y += getRowHeight(i); 840 841 // Ensure the popup is wide enough to fit this item. 842 Font itemFont = getRowFont(i); 843 String text = m_popupClient->itemText(i); 844 String label = m_popupClient->itemLabel(i); 845 String icon = m_popupClient->itemIcon(i); 846 RefPtr<Image> iconImage(Image::loadPlatformResource(icon.utf8().data())); 847 int width = 0; 848 if (!text.isEmpty()) 849 width = itemFont.width(TextRun(text)); 850 if (!label.isEmpty()) { 851 if (width > 0) 852 width += textToLabelPadding; 853 width += itemFont.width(TextRun(label)); 854 } 855 if (iconImage && !iconImage->isNull()) { 856 if (width > 0) 857 width += labelToIconPadding; 858 width += iconImage->rect().width(); 859 } 860 861 baseWidth = max(baseWidth, width); 862 // FIXME: http://b/1210481 We should get the padding of individual 863 // option elements. 864 paddingWidth = max<int>(paddingWidth, 865 m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight()); 866 lineEndPaddingWidth = max<int>(lineEndPaddingWidth, 867 isRightAligned ? m_popupClient->clientPaddingLeft() : m_popupClient->clientPaddingRight()); 868 } 869 870 // Calculate scroll bar width. 871 int windowHeight = 0; 872 m_visibleRows = std::min(numItems(), maxVisibleRows); 873 874 for (int i = 0; i < m_visibleRows; ++i) { 875 int rowHeight = getRowHeight(i); 876 877 // Only clip the window height for non-Mac platforms. 878 if (windowHeight + rowHeight > m_maxHeight) { 879 m_visibleRows = i; 880 break; 881 } 882 883 windowHeight += rowHeight; 884 } 885 886 // Set our widget and scrollable contents sizes. 887 int scrollbarWidth = 0; 888 if (m_visibleRows < numItems()) { 889 scrollbarWidth = ScrollbarTheme::theme()->scrollbarThickness(); 890 891 // Use minEndOfLinePadding when there is a scrollbar so that we use 892 // as much as (lineEndPaddingWidth - minEndOfLinePadding) padding 893 // space for scrollbar and allow user to use CSS padding to make the 894 // popup listbox align with the select element. 895 paddingWidth = paddingWidth - lineEndPaddingWidth + minEndOfLinePadding; 896 } 897 898 int windowWidth; 899 int contentWidth; 900 if (m_settings.restrictWidthOfListBox) { 901 windowWidth = m_baseWidth; 902 contentWidth = m_baseWidth - scrollbarWidth; 903 } else { 904 windowWidth = baseWidth + scrollbarWidth + paddingWidth; 905 if (windowWidth > m_maxWindowWidth) { 906 // windowWidth exceeds m_maxWindowWidth, so we have to clip. 907 windowWidth = m_maxWindowWidth; 908 baseWidth = windowWidth - scrollbarWidth - paddingWidth; 909 m_baseWidth = baseWidth; 910 } 911 contentWidth = windowWidth - scrollbarWidth; 912 913 if (windowWidth < m_baseWidth) { 914 windowWidth = m_baseWidth; 915 contentWidth = m_baseWidth - scrollbarWidth; 916 } else 917 m_baseWidth = baseWidth; 918 } 919 920 resize(windowWidth, windowHeight); 921 setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY())); 922 923 if (hostWindow()) 924 scrollToRevealSelection(); 925 926 invalidate(); 927 } 928 929 void PopupListBox::clear() 930 { 931 for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it) 932 delete *it; 933 m_items.clear(); 934 } 935 936 bool PopupListBox::isPointInBounds(const IntPoint& point) 937 { 938 return numItems() && IntRect(0, 0, width(), height()).contains(point); 939 } 940 941 int PopupListBox::popupContentHeight() const 942 { 943 return height(); 944 } 945 946 } // namespace WebCore 947