GButton.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "GButton.h"
  2. #include <SharedGraphics/Painter.h>
  3. #include <LibGUI/GStyle.h>
  4. //#define GBUTTON_DEBUG
  5. GButton::GButton(GWidget* parent)
  6. : GWidget(parent)
  7. {
  8. set_fill_with_background_color(false);
  9. }
  10. GButton::~GButton()
  11. {
  12. }
  13. void GButton::set_caption(String&& caption)
  14. {
  15. if (caption == m_caption)
  16. return;
  17. m_caption = move(caption);
  18. update();
  19. }
  20. void GButton::paint_event(GPaintEvent&)
  21. {
  22. Painter painter(*this);
  23. GStyle::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 (m_tracking_cursor) {
  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. m_tracking_cursor = true;
  58. set_global_cursor_tracking(true);
  59. update();
  60. }
  61. GWidget::mousedown_event(event);
  62. }
  63. void GButton::mouseup_event(GMouseEvent& event)
  64. {
  65. #ifdef GBUTTON_DEBUG
  66. dbgprintf("GButton::mouse_up_event: x=%d, y=%d, button=%u\n", event.x(), event.y(), (unsigned)event.button());
  67. #endif
  68. if (event.button() == GMouseButton::Left) {
  69. bool was_being_pressed = m_being_pressed;
  70. m_being_pressed = false;
  71. m_tracking_cursor = false;
  72. set_global_cursor_tracking(false);
  73. update();
  74. if (was_being_pressed) {
  75. if (on_click)
  76. on_click(*this);
  77. }
  78. }
  79. GWidget::mouseup_event(event);
  80. }