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/platform/PlatformGestureEvent.h" 39 #include "core/platform/PlatformKeyboardEvent.h" 40 #include "core/platform/PlatformMouseEvent.h" 41 #include "core/platform/PlatformScreen.h" 42 #include "core/platform/PlatformTouchEvent.h" 43 #include "core/platform/PlatformWheelEvent.h" 44 #include "core/platform/PopupMenuClient.h" 45 #include "core/platform/ScrollbarTheme.h" 46 #include "core/platform/chromium/FramelessScrollViewClient.h" 47 #include "core/platform/chromium/KeyboardCodes.h" 48 #include "core/platform/graphics/Font.h" 49 #include "core/platform/graphics/FontCache.h" 50 #include "core/platform/graphics/FontSelector.h" 51 #include "core/platform/graphics/GraphicsContext.h" 52 #include "core/platform/graphics/IntRect.h" 53 #include "core/platform/graphics/StringTruncator.h" 54 #include "core/platform/graphics/TextRun.h" 55 #include "core/rendering/RenderTheme.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, eventNames().mouseupEvent); 147 m_focusedElement->dispatchMouseEvent(event, eventNames().clickEvent); 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 // From HTMLSelectElement.cpp 296 static String stripLeadingWhiteSpace(const String& string) 297 { 298 int length = string.length(); 299 int i; 300 for (i = 0; i < length; ++i) 301 if (string[i] != noBreakSpace 302 && (string[i] <= 0x7F ? !isASCIISpace(string[i]) : (direction(string[i]) != WhiteSpaceNeutral))) 303 break; 304 305 return string.substring(i, length - i); 306 } 307 308 // From HTMLSelectElement.cpp, with modifications 309 void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event) 310 { 311 TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f); 312 TimeStamp delta = now - m_lastCharTime; 313 314 // Reset the time when user types in a character. The time gap between 315 // last character and the current character is used to indicate whether 316 // user typed in a string or just a character as the search prefix. 317 m_lastCharTime = now; 318 319 UChar c = event.windowsVirtualKeyCode(); 320 321 String prefix; 322 int searchStartOffset = 1; 323 if (delta > typeAheadTimeoutMs) { 324 m_typedString = prefix = String(&c, 1); 325 m_repeatingChar = c; 326 } else { 327 m_typedString.append(c); 328 329 if (c == m_repeatingChar) { 330 // The user is likely trying to cycle through all the items starting 331 // with this character, so just search on the character. 332 prefix = String(&c, 1); 333 } else { 334 m_repeatingChar = 0; 335 prefix = m_typedString; 336 searchStartOffset = 0; 337 } 338 } 339 340 // Compute a case-folded copy of the prefix string before beginning the 341 // search for a matching element. This code uses foldCase to work around the 342 // fact that String::startWith does not fold non-ASCII characters. This code 343 // can be changed to use startWith once that is fixed. 344 String prefixWithCaseFolded(prefix.foldCase()); 345 int itemCount = numItems(); 346 int index = (max(0, m_selectedIndex) + searchStartOffset) % itemCount; 347 for (int i = 0; i < itemCount; i++, index = (index + 1) % itemCount) { 348 if (!isSelectableItem(index)) 349 continue; 350 351 if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) { 352 selectIndex(index); 353 return; 354 } 355 } 356 } 357 358 void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect) 359 { 360 // Adjust coords for scrolled frame. 361 IntRect r = intersection(rect, frameRect()); 362 int tx = x() - scrollX(); 363 int ty = y() - scrollY(); 364 365 r.move(-tx, -ty); 366 367 // Set clip rect to match revised damage rect. 368 gc->save(); 369 gc->translate(static_cast<float>(tx), static_cast<float>(ty)); 370 gc->clip(r); 371 372 // FIXME: Can we optimize scrolling to not require repainting the entire 373 // window? Should we? 374 for (int i = 0; i < numItems(); ++i) 375 paintRow(gc, r, i); 376 377 // Special case for an empty popup. 378 if (!numItems()) 379 gc->fillRect(r, Color::white); 380 381 gc->restore(); 382 383 ScrollView::paint(gc, rect); 384 } 385 386 static const int separatorPadding = 4; 387 static const int separatorHeight = 1; 388 389 void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex) 390 { 391 // This code is based largely on RenderListBox::paint* methods. 392 393 IntRect rowRect = getRowBounds(rowIndex); 394 if (!rowRect.intersects(rect)) 395 return; 396 397 PopupMenuStyle style = m_popupClient->itemStyle(rowIndex); 398 399 // Paint background 400 Color backColor, textColor, labelColor; 401 if (rowIndex == m_selectedIndex) { 402 backColor = RenderTheme::defaultTheme()->activeListBoxSelectionBackgroundColor(); 403 textColor = RenderTheme::defaultTheme()->activeListBoxSelectionForegroundColor(); 404 labelColor = textColor; 405 } else { 406 backColor = style.backgroundColor(); 407 textColor = style.foregroundColor(); 408 409 #if OS(LINUX) 410 // On other platforms, the <option> background color is the same as the 411 // <select> background color. On Linux, that makes the <option> 412 // background color very dark, so by default, try to use a lighter 413 // background color for <option>s. 414 if (style.backgroundColorType() == PopupMenuStyle::DefaultBackgroundColor && RenderTheme::defaultTheme()->systemColor(CSSValueButtonface) == backColor) 415 backColor = RenderTheme::defaultTheme()->systemColor(CSSValueMenu); 416 #endif 417 418 // FIXME: for now the label color is hard-coded. It should be added to 419 // the PopupMenuStyle. 420 labelColor = Color(115, 115, 115); 421 } 422 423 // If we have a transparent background, make sure it has a color to blend 424 // against. 425 if (backColor.hasAlpha()) 426 gc->fillRect(rowRect, Color::white); 427 428 gc->fillRect(rowRect, backColor); 429 430 // It doesn't look good but Autofill requires special style for separator. 431 // Autofill doesn't have padding and #dcdcdc color. 432 if (m_popupClient->itemIsSeparator(rowIndex)) { 433 int padding = style.menuType() == PopupMenuStyle::AutofillPopup ? 0 : separatorPadding; 434 IntRect separatorRect( 435 rowRect.x() + padding, 436 rowRect.y() + (rowRect.height() - separatorHeight) / 2, 437 rowRect.width() - 2 * padding, separatorHeight); 438 gc->fillRect(separatorRect, style.menuType() == PopupMenuStyle::AutofillPopup ? Color(0xdc, 0xdc, 0xdc) : textColor); 439 return; 440 } 441 442 if (!style.isVisible()) 443 return; 444 445 gc->setFillColor(textColor); 446 447 FontCachePurgePreventer fontCachePurgePreventer; 448 449 Font itemFont = getRowFont(rowIndex); 450 // FIXME: http://crbug.com/19872 We should get the padding of individual option 451 // elements. This probably implies changes to PopupMenuClient. 452 bool rightAligned = m_popupClient->menuStyle().textDirection() == RTL; 453 int textX = 0; 454 int maxWidth = 0; 455 if (rightAligned) 456 maxWidth = rowRect.width() - max<int>(0, m_popupClient->clientPaddingRight() - m_popupClient->clientInsetRight()); 457 else { 458 textX = max<int>(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft()); 459 maxWidth = rowRect.width() - textX; 460 } 461 // Prepare text to be drawn. 462 String itemText = m_popupClient->itemText(rowIndex); 463 String itemLabel = m_popupClient->itemLabel(rowIndex); 464 String itemIcon = m_popupClient->itemIcon(rowIndex); 465 if (m_settings.restrictWidthOfListBox) { // Truncate strings to fit in. 466 // FIXME: We should leftTruncate for the rtl case. 467 // StringTruncator::leftTruncate would have to be implemented. 468 String str = StringTruncator::rightTruncate(itemText, maxWidth, itemFont); 469 if (str != itemText) { 470 itemText = str; 471 // Don't display the label or icon, we already don't have enough 472 // room for the item text. 473 itemLabel = ""; 474 itemIcon = ""; 475 } else if (!itemLabel.isEmpty()) { 476 int availableWidth = maxWidth - textToLabelPadding - StringTruncator::width(itemText, itemFont); 477 itemLabel = StringTruncator::rightTruncate(itemLabel, availableWidth, itemFont); 478 } 479 } 480 481 // Prepare the directionality to draw text. 482 TextRun textRun(itemText, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride()); 483 // If the text is right-to-left, make it right-aligned by adjusting its 484 // beginning position. 485 if (rightAligned) 486 textX += maxWidth - itemFont.width(textRun); 487 488 // Draw the item text. 489 int textY = rowRect.y() + itemFont.fontMetrics().ascent() + (rowRect.height() - itemFont.fontMetrics().height()) / 2; 490 TextRunPaintInfo textRunPaintInfo(textRun); 491 textRunPaintInfo.bounds = rowRect; 492 gc->drawBidiText(itemFont, textRunPaintInfo, IntPoint(textX, textY)); 493 494 // We are using the left padding as the right padding includes room for the scroll-bar which 495 // does not show in this case. 496 int rightPadding = max<int>(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft()); 497 int remainingWidth = rowRect.width() - rightPadding; 498 499 // Draw the icon if applicable. 500 RefPtr<Image> image(Image::loadPlatformResource(itemIcon.utf8().data())); 501 if (image && !image->isNull()) { 502 IntRect imageRect = image->rect(); 503 remainingWidth -= (imageRect.width() + labelToIconPadding); 504 imageRect.setX(rowRect.width() - rightPadding - imageRect.width()); 505 imageRect.setY(rowRect.y() + (rowRect.height() - imageRect.height()) / 2); 506 gc->drawImage(image.get(), imageRect); 507 } 508 509 // Draw the the label if applicable. 510 if (itemLabel.isEmpty()) 511 return; 512 513 // Autofill label is 0.9 smaller than regular font size. 514 if (style.menuType() == PopupMenuStyle::AutofillPopup) { 515 itemFont = m_popupClient->itemStyle(rowIndex).font(); 516 FontDescription d = itemFont.fontDescription(); 517 d.setComputedSize(d.computedSize() * 0.9); 518 itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing()); 519 itemFont.update(0); 520 } 521 522 TextRun labelTextRun(itemLabel, 0, 0, TextRun::AllowTrailingExpansion, style.textDirection(), style.hasTextDirectionOverride()); 523 if (rightAligned) 524 textX = max<int>(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft()); 525 else 526 textX = remainingWidth - itemFont.width(labelTextRun); 527 TextRunPaintInfo labelTextRunPaintInfo(labelTextRun); 528 labelTextRunPaintInfo.bounds = rowRect; 529 530 gc->setFillColor(labelColor); 531 gc->drawBidiText(itemFont, labelTextRunPaintInfo, IntPoint(textX, textY)); 532 } 533 534 Font PopupListBox::getRowFont(int rowIndex) 535 { 536 Font itemFont = m_popupClient->itemStyle(rowIndex).font(); 537 if (m_popupClient->itemIsLabel(rowIndex)) { 538 // Bold-ify labels (ie, an <optgroup> heading). 539 FontDescription d = itemFont.fontDescription(); 540 d.setWeight(FontWeightBold); 541 Font font(d, itemFont.letterSpacing(), itemFont.wordSpacing()); 542 font.update(0); 543 return font; 544 } 545 546 return itemFont; 547 } 548 549 void PopupListBox::abandon() 550 { 551 RefPtr<PopupListBox> keepAlive(this); 552 553 m_selectedIndex = m_originalIndex; 554 555 hidePopup(); 556 557 if (m_acceptedIndexOnAbandon >= 0) { 558 if (m_popupClient) 559 m_popupClient->valueChanged(m_acceptedIndexOnAbandon); 560 m_acceptedIndexOnAbandon = -1; 561 } 562 } 563 564 int PopupListBox::pointToRowIndex(const IntPoint& point) 565 { 566 int y = scrollY() + point.y(); 567 568 // FIXME: binary search if perf matters. 569 for (int i = 0; i < numItems(); ++i) { 570 if (y < m_items[i]->yOffset) 571 return i-1; 572 } 573 574 // Last item? 575 if (y < contentsHeight()) 576 return m_items.size()-1; 577 578 return -1; 579 } 580 581 bool PopupListBox::acceptIndex(int index) 582 { 583 // Clear m_acceptedIndexOnAbandon once user accepts the selected index. 584 if (m_acceptedIndexOnAbandon >= 0) 585 m_acceptedIndexOnAbandon = -1; 586 587 if (index >= numItems()) 588 return false; 589 590 if (index < 0) { 591 if (m_popupClient) { 592 // Enter pressed with no selection, just close the popup. 593 hidePopup(); 594 } 595 return false; 596 } 597 598 if (isSelectableItem(index)) { 599 RefPtr<PopupListBox> keepAlive(this); 600 601 // Hide ourselves first since valueChanged may have numerous side-effects. 602 hidePopup(); 603 604 // Tell the <select> PopupMenuClient what index was selected. 605 m_popupClient->valueChanged(index); 606 607 return true; 608 } 609 610 return false; 611 } 612 613 void PopupListBox::selectIndex(int index) 614 { 615 if (index < 0 || index >= numItems()) 616 return; 617 618 bool isSelectable = isSelectableItem(index); 619 if (index != m_selectedIndex && isSelectable) { 620 invalidateRow(m_selectedIndex); 621 m_selectedIndex = index; 622 invalidateRow(m_selectedIndex); 623 624 scrollToRevealSelection(); 625 m_popupClient->selectionChanged(m_selectedIndex); 626 } else if (!isSelectable) 627 clearSelection(); 628 } 629 630 void PopupListBox::setOriginalIndex(int index) 631 { 632 m_originalIndex = m_selectedIndex = index; 633 } 634 635 int PopupListBox::getRowHeight(int index) 636 { 637 int minimumHeight = PopupMenuChromium::minimumRowHeight(); 638 if (m_settings.deviceSupportsTouch) 639 minimumHeight = max(minimumHeight, PopupMenuChromium::optionRowHeightForTouch()); 640 641 if (index < 0 || m_popupClient->itemStyle(index).isDisplayNone()) 642 return minimumHeight; 643 644 // Separator row height is the same size as itself. 645 if (m_popupClient->itemIsSeparator(index)) 646 return max(separatorHeight, minimumHeight); 647 648 String icon = m_popupClient->itemIcon(index); 649 RefPtr<Image> image(Image::loadPlatformResource(icon.utf8().data())); 650 651 int fontHeight = getRowFont(index).fontMetrics().height(); 652 int iconHeight = (image && !image->isNull()) ? image->rect().height() : 0; 653 654 int linePaddingHeight = m_popupClient->menuStyle().menuType() == PopupMenuStyle::AutofillPopup ? autofillLinePaddingHeight : 0; 655 int calculatedRowHeight = max(fontHeight, iconHeight) + linePaddingHeight * 2; 656 return max(calculatedRowHeight, minimumHeight); 657 } 658 659 IntRect PopupListBox::getRowBounds(int index) 660 { 661 if (index < 0) 662 return IntRect(0, 0, visibleWidth(), getRowHeight(index)); 663 664 return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index)); 665 } 666 667 void PopupListBox::invalidateRow(int index) 668 { 669 if (index < 0) 670 return; 671 672 // Invalidate in the window contents, as FramelessScrollView::invalidateRect 673 // paints in the window coordinates. 674 invalidateRect(contentsToWindow(getRowBounds(index))); 675 } 676 677 void PopupListBox::scrollToRevealRow(int index) 678 { 679 if (index < 0) 680 return; 681 682 IntRect rowRect = getRowBounds(index); 683 684 if (rowRect.y() < scrollY()) { 685 // Row is above current scroll position, scroll up. 686 ScrollView::setScrollPosition(IntPoint(0, rowRect.y())); 687 } else if (rowRect.maxY() > scrollY() + visibleHeight()) { 688 // Row is below current scroll position, scroll down. 689 ScrollView::setScrollPosition(IntPoint(0, rowRect.maxY() - visibleHeight())); 690 } 691 } 692 693 bool PopupListBox::isSelectableItem(int index) 694 { 695 ASSERT(index >= 0 && index < numItems()); 696 return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index); 697 } 698 699 void PopupListBox::clearSelection() 700 { 701 if (m_selectedIndex != -1) { 702 invalidateRow(m_selectedIndex); 703 m_selectedIndex = -1; 704 m_popupClient->selectionCleared(); 705 } 706 } 707 708 void PopupListBox::selectNextRow() 709 { 710 if (!m_settings.loopSelectionNavigation || m_selectedIndex != numItems() - 1) { 711 adjustSelectedIndex(1); 712 return; 713 } 714 715 // We are moving past the last item, no row should be selected. 716 clearSelection(); 717 } 718 719 void PopupListBox::selectPreviousRow() 720 { 721 if (!m_settings.loopSelectionNavigation || m_selectedIndex > 0) { 722 adjustSelectedIndex(-1); 723 return; 724 } 725 726 if (!m_selectedIndex) { 727 // We are moving past the first item, clear the selection. 728 clearSelection(); 729 return; 730 } 731 732 // No row is selected, jump to the last item. 733 selectIndex(numItems() - 1); 734 scrollToRevealSelection(); 735 } 736 737 void PopupListBox::adjustSelectedIndex(int delta) 738 { 739 int targetIndex = m_selectedIndex + delta; 740 targetIndex = std::min(std::max(targetIndex, 0), numItems() - 1); 741 if (!isSelectableItem(targetIndex)) { 742 // We didn't land on an option. Try to find one. 743 // We try to select the closest index to target, prioritizing any in 744 // the range [current, target]. 745 746 int dir = delta > 0 ? 1 : -1; 747 int testIndex = m_selectedIndex; 748 int bestIndex = m_selectedIndex; 749 bool passedTarget = false; 750 while (testIndex >= 0 && testIndex < numItems()) { 751 if (isSelectableItem(testIndex)) 752 bestIndex = testIndex; 753 if (testIndex == targetIndex) 754 passedTarget = true; 755 if (passedTarget && bestIndex != m_selectedIndex) 756 break; 757 758 testIndex += dir; 759 } 760 761 // Pick the best index, which may mean we don't change. 762 targetIndex = bestIndex; 763 } 764 765 // Select the new index, and ensure its visible. We do this regardless of 766 // whether the selection changed to ensure keyboard events always bring the 767 // selection into view. 768 selectIndex(targetIndex); 769 scrollToRevealSelection(); 770 } 771 772 void PopupListBox::hidePopup() 773 { 774 if (parent()) { 775 PopupContainer* container = static_cast<PopupContainer*>(parent()); 776 if (container->client()) 777 container->client()->popupClosed(container); 778 container->notifyPopupHidden(); 779 } 780 781 if (m_popupClient) 782 m_popupClient->popupDidHide(); 783 } 784 785 void PopupListBox::updateFromElement() 786 { 787 clear(); 788 789 int size = m_popupClient->listSize(); 790 for (int i = 0; i < size; ++i) { 791 PopupItem::Type type; 792 if (m_popupClient->itemIsSeparator(i)) 793 type = PopupItem::TypeSeparator; 794 else if (m_popupClient->itemIsLabel(i)) 795 type = PopupItem::TypeGroup; 796 else 797 type = PopupItem::TypeOption; 798 m_items.append(new PopupItem(m_popupClient->itemText(i), type)); 799 m_items[i]->enabled = isSelectableItem(i); 800 PopupMenuStyle style = m_popupClient->itemStyle(i); 801 m_items[i]->textDirection = style.textDirection(); 802 m_items[i]->hasTextDirectionOverride = style.hasTextDirectionOverride(); 803 } 804 805 m_selectedIndex = m_popupClient->selectedIndex(); 806 setOriginalIndex(m_selectedIndex); 807 808 layout(); 809 } 810 811 void PopupListBox::setMaxWidthAndLayout(int maxWidth) 812 { 813 m_maxWindowWidth = maxWidth; 814 layout(); 815 } 816 817 void PopupListBox::layout() 818 { 819 bool isRightAligned = m_popupClient->menuStyle().textDirection() == RTL; 820 821 // Size our child items. 822 int baseWidth = 0; 823 int paddingWidth = 0; 824 int lineEndPaddingWidth = 0; 825 int y = 0; 826 for (int i = 0; i < numItems(); ++i) { 827 // Place the item vertically. 828 m_items[i]->yOffset = y; 829 if (m_popupClient->itemStyle(i).isDisplayNone()) 830 continue; 831 y += getRowHeight(i); 832 833 // Ensure the popup is wide enough to fit this item. 834 Font itemFont = getRowFont(i); 835 String text = m_popupClient->itemText(i); 836 String label = m_popupClient->itemLabel(i); 837 String icon = m_popupClient->itemIcon(i); 838 RefPtr<Image> iconImage(Image::loadPlatformResource(icon.utf8().data())); 839 int width = 0; 840 if (!text.isEmpty()) 841 width = itemFont.width(TextRun(text)); 842 if (!label.isEmpty()) { 843 if (width > 0) 844 width += textToLabelPadding; 845 width += itemFont.width(TextRun(label)); 846 } 847 if (iconImage && !iconImage->isNull()) { 848 if (width > 0) 849 width += labelToIconPadding; 850 width += iconImage->rect().width(); 851 } 852 853 baseWidth = max(baseWidth, width); 854 // FIXME: http://b/1210481 We should get the padding of individual 855 // option elements. 856 paddingWidth = max<int>(paddingWidth, 857 m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight()); 858 lineEndPaddingWidth = max<int>(lineEndPaddingWidth, 859 isRightAligned ? m_popupClient->clientPaddingLeft() : m_popupClient->clientPaddingRight()); 860 } 861 862 // Calculate scroll bar width. 863 int windowHeight = 0; 864 m_visibleRows = std::min(numItems(), maxVisibleRows); 865 866 for (int i = 0; i < m_visibleRows; ++i) { 867 int rowHeight = getRowHeight(i); 868 869 // Only clip the window height for non-Mac platforms. 870 if (windowHeight + rowHeight > m_maxHeight) { 871 m_visibleRows = i; 872 break; 873 } 874 875 windowHeight += rowHeight; 876 } 877 878 // Set our widget and scrollable contents sizes. 879 int scrollbarWidth = 0; 880 if (m_visibleRows < numItems()) { 881 scrollbarWidth = ScrollbarTheme::theme()->scrollbarThickness(); 882 883 // Use minEndOfLinePadding when there is a scrollbar so that we use 884 // as much as (lineEndPaddingWidth - minEndOfLinePadding) padding 885 // space for scrollbar and allow user to use CSS padding to make the 886 // popup listbox align with the select element. 887 paddingWidth = paddingWidth - lineEndPaddingWidth + minEndOfLinePadding; 888 } 889 890 int windowWidth; 891 int contentWidth; 892 if (m_settings.restrictWidthOfListBox) { 893 windowWidth = m_baseWidth; 894 contentWidth = m_baseWidth - scrollbarWidth; 895 } else { 896 windowWidth = baseWidth + scrollbarWidth + paddingWidth; 897 if (windowWidth > m_maxWindowWidth) { 898 // windowWidth exceeds m_maxWindowWidth, so we have to clip. 899 windowWidth = m_maxWindowWidth; 900 baseWidth = windowWidth - scrollbarWidth - paddingWidth; 901 m_baseWidth = baseWidth; 902 } 903 contentWidth = windowWidth - scrollbarWidth; 904 905 if (windowWidth < m_baseWidth) { 906 windowWidth = m_baseWidth; 907 contentWidth = m_baseWidth - scrollbarWidth; 908 } else 909 m_baseWidth = baseWidth; 910 } 911 912 resize(windowWidth, windowHeight); 913 setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).maxY())); 914 915 if (hostWindow()) 916 scrollToRevealSelection(); 917 918 invalidate(); 919 } 920 921 void PopupListBox::clear() 922 { 923 for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it) 924 delete *it; 925 m_items.clear(); 926 } 927 928 bool PopupListBox::isPointInBounds(const IntPoint& point) 929 { 930 return numItems() && IntRect(0, 0, width(), height()).contains(point); 931 } 932 933 int PopupListBox::popupContentHeight() const 934 { 935 return height(); 936 } 937 938 } // namespace WebCore 939