GButton.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "GButton.h"
  2. #include <AK/StringBuilder.h>
  3. #include <Kernel/KeyCode.h>
  4. #include <LibGUI/GAction.h>
  5. #include <LibGUI/GPainter.h>
  6. #include <SharedGraphics/StylePainter.h>
  7. GButton::GButton(GWidget* parent)
  8. : GAbstractButton(parent)
  9. {
  10. }
  11. GButton::GButton(const StringView& text, GWidget* parent)
  12. : GAbstractButton(text, parent)
  13. {
  14. }
  15. GButton::~GButton()
  16. {
  17. if (m_action)
  18. m_action->unregister_button({}, *this);
  19. }
  20. void GButton::paint_event(GPaintEvent& event)
  21. {
  22. GPainter painter(*this);
  23. painter.add_clip_rect(event.rect());
  24. StylePainter::paint_button(painter, rect(), m_button_style, is_being_pressed(), is_hovered(), is_checkable() && is_checked(), is_enabled());
  25. if (text().is_empty() && !m_icon)
  26. return;
  27. auto content_rect = rect().shrunken(10, 2);
  28. auto icon_location = m_icon ? content_rect.center().translated(-(m_icon->width() / 2), -(m_icon->height() / 2)) : Point();
  29. if (m_icon && !text().is_empty())
  30. icon_location.set_x(content_rect.x());
  31. if (is_being_pressed())
  32. painter.translate(1, 1);
  33. if (m_icon) {
  34. if (is_enabled())
  35. painter.blit(icon_location, *m_icon, m_icon->rect());
  36. else
  37. painter.blit_dimmed(icon_location, *m_icon, m_icon->rect());
  38. }
  39. auto& font = (is_checkable() && is_checked()) ? Font::default_bold_font() : this->font();
  40. if (m_icon && !text().is_empty()) {
  41. content_rect.move_by(m_icon->width() + 4, 0);
  42. content_rect.set_width(content_rect.width() - m_icon->width() - 4);
  43. }
  44. Rect text_rect { 0, 0, font.width(text()), font.glyph_height() };
  45. if (text_rect.width() > content_rect.width())
  46. text_rect.set_width(content_rect.width());
  47. text_rect.align_within(content_rect, text_alignment());
  48. paint_text(painter, text_rect, font, TextAlignment::Center);
  49. }
  50. void GButton::click()
  51. {
  52. if (!is_enabled())
  53. return;
  54. if (is_checkable())
  55. set_checked(!is_checked());
  56. if (on_click)
  57. on_click(*this);
  58. }
  59. bool GButton::accepts_keyboard_select() const
  60. {
  61. return is_enabled();
  62. }
  63. void GButton::set_action(GAction& action)
  64. {
  65. m_action = action.make_weak_ptr();
  66. action.register_button({}, *this);
  67. set_enabled(action.is_enabled());
  68. set_checkable(action.is_checkable());
  69. if (action.is_checkable())
  70. set_checked(action.is_checked());
  71. }
  72. void GButton::set_icon(RetainPtr<GraphicsBitmap>&& icon)
  73. {
  74. if (m_icon == icon)
  75. return;
  76. m_icon = move(icon);
  77. update();
  78. }