GButton.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include "GButton.h"
  2. #include <LibGUI/GPainter.h>
  3. #include <SharedGraphics/StylePainter.h>
  4. //#define GBUTTON_DEBUG
  5. GButton::GButton(GWidget* parent)
  6. : GWidget(parent)
  7. {
  8. }
  9. GButton::~GButton()
  10. {
  11. }
  12. void GButton::set_caption(const String& caption)
  13. {
  14. if (caption == m_caption)
  15. return;
  16. m_caption = caption;
  17. update();
  18. }
  19. void GButton::paint_event(GPaintEvent& event)
  20. {
  21. GPainter painter(*this);
  22. painter.add_clip_rect(event.rect());
  23. StylePainter::the().paint_button(painter, rect(), m_button_style, m_being_pressed, m_hovered);
  24. if (!caption().is_empty() || m_icon) {
  25. auto content_rect = rect();
  26. auto icon_location = m_icon ? content_rect.center().translated(-(m_icon->width() / 2), -(m_icon->height() / 2)) : Point();
  27. if (m_being_pressed) {
  28. content_rect.move_by(1, 1);
  29. icon_location.move_by(1, 1);
  30. }
  31. if (m_icon) {
  32. painter.blit(icon_location, *m_icon, m_icon->rect());
  33. painter.draw_text(content_rect, caption(), TextAlignment::Center, Color::Black);
  34. } else {
  35. painter.draw_text(content_rect, caption(), TextAlignment::Center, Color::Black);
  36. }
  37. }
  38. }
  39. void GButton::mousemove_event(GMouseEvent& event)
  40. {
  41. if (event.buttons() == GMouseButton::Left) {
  42. bool being_pressed = rect().contains(event.position());
  43. if (being_pressed != m_being_pressed) {
  44. m_being_pressed = being_pressed;
  45. update();
  46. }
  47. }
  48. GWidget::mousemove_event(event);
  49. }
  50. void GButton::mousedown_event(GMouseEvent& event)
  51. {
  52. #ifdef GBUTTON_DEBUG
  53. dbgprintf("GButton::mouse_down_event: x=%d, y=%d, button=%u\n", event.x(), event.y(), (unsigned)event.button());
  54. #endif
  55. if (event.button() == GMouseButton::Left) {
  56. m_being_pressed = true;
  57. update();
  58. }
  59. GWidget::mousedown_event(event);
  60. }
  61. void GButton::click()
  62. {
  63. if (on_click)
  64. on_click(*this);
  65. }
  66. void GButton::mouseup_event(GMouseEvent& event)
  67. {
  68. #ifdef GBUTTON_DEBUG
  69. dbgprintf("GButton::mouse_up_event: x=%d, y=%d, button=%u\n", event.x(), event.y(), (unsigned)event.button());
  70. #endif
  71. if (event.button() == GMouseButton::Left) {
  72. bool was_being_pressed = m_being_pressed;
  73. m_being_pressed = false;
  74. update();
  75. if (was_being_pressed)
  76. click();
  77. }
  78. GWidget::mouseup_event(event);
  79. }
  80. void GButton::enter_event(GEvent&)
  81. {
  82. m_hovered = true;
  83. update();
  84. }
  85. void GButton::leave_event(GEvent&)
  86. {
  87. m_hovered = false;
  88. update();
  89. }