ListBox.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "ListBox.h"
  2. #include "Painter.h"
  3. #include "Font.h"
  4. #include "Window.h"
  5. ListBox::ListBox(Widget* parent)
  6. : Widget(parent)
  7. {
  8. }
  9. ListBox::~ListBox()
  10. {
  11. }
  12. Rect ListBox::item_rect(int index) const
  13. {
  14. int item_height = font().glyph_height() + 2;
  15. return Rect { 2, 2 + (index * item_height), width() - 4, item_height };
  16. }
  17. void ListBox::paintEvent(PaintEvent&)
  18. {
  19. Painter painter(*this);
  20. // FIXME: Reduce overdraw.
  21. painter.fill_rect(rect(), Color::White);
  22. painter.draw_rect(rect(), Color::Black);
  23. if (isFocused())
  24. painter.draw_focus_rect(rect());
  25. for (int i = m_scrollOffset; i < static_cast<int>(m_items.size()); ++i) {
  26. auto itemRect = item_rect(i);
  27. Rect textRect(itemRect.x() + 1, itemRect.y() + 1, itemRect.width() - 2, itemRect.height() - 2);
  28. Color itemTextColor = foregroundColor();
  29. if (m_selectedIndex == i) {
  30. if (isFocused())
  31. painter.fill_rect(itemRect, Color(0, 32, 128));
  32. else
  33. painter.fill_rect(itemRect, Color(96, 96, 96));
  34. itemTextColor = Color::White;
  35. }
  36. painter.draw_text(textRect, m_items[i], Painter::TextAlignment::TopLeft, itemTextColor);
  37. }
  38. }
  39. void ListBox::mouseDownEvent(MouseEvent& event)
  40. {
  41. printf("ListBox::mouseDownEvent %d,%d\n", event.x(), event.y());
  42. for (int i = m_scrollOffset; i < static_cast<int>(m_items.size()); ++i) {
  43. auto itemRect = item_rect(i);
  44. if (itemRect.contains(event.position())) {
  45. m_selectedIndex = i;
  46. printf("ListBox: selected item %u (\"%s\")\n", i, m_items[i].characters());
  47. update();
  48. return;
  49. }
  50. }
  51. }
  52. void ListBox::addItem(String&& item)
  53. {
  54. m_items.append(move(item));
  55. if (m_selectedIndex == -1)
  56. m_selectedIndex = 0;
  57. }