RadioButton.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibGUI/Painter.h>
  8. #include <LibGUI/RadioButton.h>
  9. #include <LibGfx/Bitmap.h>
  10. #include <LibGfx/Font/Font.h>
  11. #include <LibGfx/Palette.h>
  12. #include <LibGfx/StylePainter.h>
  13. REGISTER_WIDGET(GUI, RadioButton)
  14. namespace GUI {
  15. RadioButton::RadioButton(String text)
  16. : AbstractButton(move(text))
  17. {
  18. set_exclusive(true);
  19. set_checkable(true);
  20. set_min_size(SpecialDimension::Shrink, SpecialDimension::Shrink);
  21. set_preferred_size(SpecialDimension::OpportunisticGrow, SpecialDimension::Shrink);
  22. }
  23. int RadioButton::horizontal_padding()
  24. {
  25. return 2;
  26. }
  27. Gfx::IntSize RadioButton::circle_size()
  28. {
  29. return { 12, 12 };
  30. }
  31. void RadioButton::paint_event(PaintEvent& event)
  32. {
  33. Painter painter(*this);
  34. painter.add_clip_rect(event.rect());
  35. if (fill_with_background_color())
  36. painter.fill_rect(rect(), palette().window());
  37. if (is_enabled() && is_hovered())
  38. painter.fill_rect(rect(), palette().hover_highlight());
  39. Gfx::IntRect circle_rect { { horizontal_padding(), 0 }, circle_size() };
  40. circle_rect.center_vertically_within(rect());
  41. Gfx::StylePainter::paint_radio_button(painter, circle_rect, palette(), is_checked(), is_being_pressed());
  42. Gfx::IntRect text_rect { circle_rect.right() + 4 + horizontal_padding(), 0, font().width_rounded_up(text()), font().pixel_size_rounded_up() };
  43. text_rect.center_vertically_within(rect());
  44. paint_text(painter, text_rect, font(), Gfx::TextAlignment::TopLeft);
  45. if (is_focused())
  46. painter.draw_focus_rect(text_rect.inflated(6, 6), palette().focus_outline());
  47. }
  48. void RadioButton::click(unsigned)
  49. {
  50. if (!is_enabled())
  51. return;
  52. set_checked(true);
  53. }
  54. Optional<UISize> RadioButton::calculated_min_size() const
  55. {
  56. auto const& font = this->font();
  57. int width = horizontal_padding() * 2 + circle_size().width() + font.width_rounded_up(text());
  58. int height = max(22, max(font.pixel_size_rounded_up() + 8, circle_size().height()));
  59. return UISize(width, height);
  60. }
  61. }