GRadioButton.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <LibGUI/GRadioButton.h>
  2. #include <LibGUI/GPainter.h>
  3. #include <SharedGraphics/GraphicsBitmap.h>
  4. static RetainPtr<GraphicsBitmap> s_unfilled_circle_bitmap;
  5. static RetainPtr<GraphicsBitmap> s_filled_circle_bitmap;
  6. static RetainPtr<GraphicsBitmap> s_changing_filled_circle_bitmap;
  7. static RetainPtr<GraphicsBitmap> s_changing_unfilled_circle_bitmap;
  8. GRadioButton::GRadioButton(const String& text, GWidget* parent)
  9. : GAbstractButton(text, parent)
  10. {
  11. if (!s_unfilled_circle_bitmap) {
  12. s_unfilled_circle_bitmap = GraphicsBitmap::load_from_file("/res/icons/unfilled-radio-circle.png");
  13. s_filled_circle_bitmap = GraphicsBitmap::load_from_file("/res/icons/filled-radio-circle.png");
  14. s_changing_filled_circle_bitmap = GraphicsBitmap::load_from_file("/res/icons/changing-filled-radio-circle.png");
  15. s_changing_unfilled_circle_bitmap = GraphicsBitmap::load_from_file("/res/icons/changing-unfilled-radio-circle.png");
  16. }
  17. }
  18. GRadioButton::~GRadioButton()
  19. {
  20. }
  21. Size GRadioButton::circle_size()
  22. {
  23. return s_unfilled_circle_bitmap->size();
  24. }
  25. static const GraphicsBitmap& circle_bitmap(bool checked, bool changing)
  26. {
  27. if (changing)
  28. return checked ? *s_changing_filled_circle_bitmap : *s_changing_unfilled_circle_bitmap;
  29. return checked ? *s_filled_circle_bitmap : *s_unfilled_circle_bitmap;
  30. }
  31. void GRadioButton::paint_event(GPaintEvent& event)
  32. {
  33. GPainter painter(*this);
  34. painter.add_clip_rect(event.rect());
  35. Rect circle_rect { { 2, 0 }, circle_size() };
  36. circle_rect.center_vertically_within(rect());
  37. auto& bitmap = circle_bitmap(is_checked(), is_being_pressed());
  38. painter.blit(circle_rect.location(), bitmap, bitmap.rect());
  39. Rect text_rect { circle_rect.right() + 4, 0, font().width(text()), font().glyph_height() };
  40. text_rect.center_vertically_within(rect());
  41. paint_text(painter, text_rect, font(), TextAlignment::TopLeft);
  42. }
  43. template<typename Callback>
  44. void GRadioButton::for_each_in_group(Callback callback)
  45. {
  46. if (!parent())
  47. return;
  48. for_each_child_widget([&] (auto& child) {
  49. if (!child.is_radio_button())
  50. return IterationDecision::Continue;
  51. return callback(static_cast<GRadioButton&>(child));
  52. });
  53. }
  54. void GRadioButton::click()
  55. {
  56. if (!is_enabled())
  57. return;
  58. for_each_in_group([this] (auto& button) {
  59. if (&button != this)
  60. button.set_checked(false);
  61. return IterationDecision::Continue;
  62. });
  63. set_checked(true);
  64. }