RadioButton.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2018-2020, 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(DeprecatedString text)
  16. : RadioButton(String::from_deprecated_string(text).release_value_but_fixme_should_propagate_errors())
  17. {
  18. }
  19. RadioButton::RadioButton(String text)
  20. : AbstractButton(move(text))
  21. {
  22. set_exclusive(true);
  23. set_checkable(true);
  24. set_min_size({ 22, 22 });
  25. set_preferred_size({ SpecialDimension::OpportunisticGrow, 22 });
  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 { { 2, 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() + 7, 0, static_cast<int>(ceilf(font().width(text_deprecated()))), font().glyph_height() };
  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. int horizontal = 2 + 7, vertical = 0;
  57. auto& font = this->font();
  58. vertical = max(font.glyph_height(), circle_size().height());
  59. horizontal += font.width(text_deprecated());
  60. return UISize(horizontal, vertical);
  61. }
  62. }