ladybird/LibGUI/ListBox.cpp

69 lines
1.8 KiB
C++
Raw Normal View History

2018-10-13 01:20:44 +03:00
#include "ListBox.h"
#include "Window.h"
2019-01-20 01:49:56 +03:00
#include <SharedGraphics/Font.h>
#include <SharedGraphics/Painter.h>
2018-10-13 01:20:44 +03:00
ListBox::ListBox(Widget* parent)
: Widget(parent)
{
}
ListBox::~ListBox()
{
}
Rect ListBox::item_rect(int index) const
2018-10-13 01:20:44 +03:00
{
int item_height = font().glyph_height() + 2;
return Rect { 2, 2 + (index * item_height), width() - 4, item_height };
2018-10-13 01:20:44 +03:00
}
void ListBox::paintEvent(PaintEvent&)
2018-10-13 01:20:44 +03:00
{
Painter painter(*this);
// FIXME: Reduce overdraw.
painter.fill_rect(rect(), Color::White);
painter.draw_rect(rect(), Color::Black);
2018-10-13 01:20:44 +03:00
if (isFocused())
painter.draw_focus_rect(rect());
for (int i = m_scrollOffset; i < static_cast<int>(m_items.size()); ++i) {
auto itemRect = item_rect(i);
2018-10-13 01:20:44 +03:00
Rect textRect(itemRect.x() + 1, itemRect.y() + 1, itemRect.width() - 2, itemRect.height() - 2);
Color itemTextColor = foregroundColor();
if (m_selectedIndex == i) {
if (isFocused())
painter.fill_rect(itemRect, Color(0, 32, 128));
else
painter.fill_rect(itemRect, Color(96, 96, 96));
2018-10-13 01:20:44 +03:00
itemTextColor = Color::White;
}
painter.draw_text(textRect, m_items[i], Painter::TextAlignment::TopLeft, itemTextColor);
2018-10-13 01:20:44 +03:00
}
}
void ListBox::mouseDownEvent(MouseEvent& event)
2018-10-13 01:20:44 +03:00
{
2019-01-20 01:49:56 +03:00
dbgprintf("ListBox::mouseDownEvent %d,%d\n", event.x(), event.y());
for (int i = m_scrollOffset; i < static_cast<int>(m_items.size()); ++i) {
auto itemRect = item_rect(i);
2018-10-13 01:20:44 +03:00
if (itemRect.contains(event.position())) {
m_selectedIndex = i;
2019-01-20 01:49:56 +03:00
dbgprintf("ListBox: selected item %u (\"%s\")\n", i, m_items[i].characters());
2018-10-13 01:20:44 +03:00
update();
return;
}
}
}
void ListBox::addItem(String&& item)
{
m_items.append(move(item));
2018-10-13 01:20:44 +03:00
if (m_selectedIndex == -1)
m_selectedIndex = 0;
}