WSButton.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <LibDraw/CharacterBitmap.h>
  2. #include <LibDraw/Painter.h>
  3. #include <LibDraw/StylePainter.h>
  4. #include <WindowServer/WSButton.h>
  5. #include <WindowServer/WSEvent.h>
  6. #include <WindowServer/WSWindowManager.h>
  7. WSButton::WSButton(WSWindowFrame& frame, NonnullRefPtr<CharacterBitmap>&& bitmap, Function<void(WSButton&)>&& on_click_handler)
  8. : on_click(move(on_click_handler))
  9. , m_frame(frame)
  10. , m_bitmap(move(bitmap))
  11. {
  12. }
  13. WSButton::~WSButton()
  14. {
  15. }
  16. void WSButton::paint(Painter& painter)
  17. {
  18. PainterStateSaver saver(painter);
  19. painter.translate(relative_rect().location());
  20. StylePainter::paint_button(painter, rect(), ButtonStyle::Normal, m_pressed, m_hovered);
  21. auto x_location = rect().center();
  22. x_location.move_by(-(m_bitmap->width() / 2), -(m_bitmap->height() / 2));
  23. if (m_pressed)
  24. x_location.move_by(1, 1);
  25. painter.draw_bitmap(x_location, *m_bitmap, SystemColor::ButtonText);
  26. }
  27. void WSButton::on_mouse_event(const WSMouseEvent& event)
  28. {
  29. auto& wm = WSWindowManager::the();
  30. if (event.type() == WSEvent::MouseDown && event.button() == MouseButton::Left) {
  31. m_pressed = true;
  32. wm.set_cursor_tracking_button(this);
  33. wm.invalidate(screen_rect());
  34. return;
  35. }
  36. if (event.type() == WSEvent::MouseUp && event.button() == MouseButton::Left) {
  37. if (wm.cursor_tracking_button() != this)
  38. return;
  39. wm.set_cursor_tracking_button(nullptr);
  40. bool old_pressed = m_pressed;
  41. m_pressed = false;
  42. if (rect().contains(event.position())) {
  43. if (on_click)
  44. on_click(*this);
  45. }
  46. if (old_pressed != m_pressed)
  47. wm.invalidate(screen_rect());
  48. return;
  49. }
  50. if (event.type() == WSEvent::MouseMove) {
  51. bool old_hovered = m_hovered;
  52. m_hovered = rect().contains(event.position());
  53. wm.set_hovered_button(m_hovered ? this : nullptr);
  54. if (old_hovered != m_hovered)
  55. wm.invalidate(screen_rect());
  56. }
  57. if (event.type() == WSEvent::MouseMove && event.buttons() & (unsigned)MouseButton::Left) {
  58. if (wm.cursor_tracking_button() != this)
  59. return;
  60. bool old_pressed = m_pressed;
  61. m_pressed = m_hovered;
  62. if (old_pressed != m_pressed)
  63. wm.invalidate(screen_rect());
  64. }
  65. }
  66. Rect WSButton::screen_rect() const
  67. {
  68. return m_relative_rect.translated(m_frame.rect().location());
  69. }