CheckBox.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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/CheckBox.h>
  8. #include <LibGUI/Painter.h>
  9. #include <LibGfx/CharacterBitmap.h>
  10. #include <LibGfx/Font/Font.h>
  11. #include <LibGfx/Palette.h>
  12. #include <LibGfx/StylePainter.h>
  13. REGISTER_WIDGET(GUI, CheckBox)
  14. namespace GUI {
  15. static constexpr int s_box_width = 13;
  16. static constexpr int s_box_height = 13;
  17. static constexpr int s_horizontal_padding = 6;
  18. CheckBox::CheckBox(String text)
  19. : AbstractButton(move(text))
  20. {
  21. REGISTER_BOOL_PROPERTY("autosize", is_autosize, set_autosize);
  22. REGISTER_ENUM_PROPERTY(
  23. "checkbox_position", checkbox_position, set_checkbox_position, CheckBoxPosition,
  24. { CheckBoxPosition::Left, "Left" },
  25. { CheckBoxPosition::Right, "Right" });
  26. set_min_size({ 22, 22 });
  27. set_preferred_size({ SpecialDimension::OpportunisticGrow, 22 });
  28. }
  29. void CheckBox::paint_event(PaintEvent& event)
  30. {
  31. Painter painter(*this);
  32. painter.add_clip_rect(event.rect());
  33. auto text_rect = rect();
  34. if (m_checkbox_position == CheckBoxPosition::Left)
  35. text_rect.set_left(s_box_width + s_horizontal_padding);
  36. text_rect.set_width(font().width(text()));
  37. text_rect.set_top(height() / 2 - font().glyph_height() / 2);
  38. text_rect.set_height(font().glyph_height());
  39. if (fill_with_background_color())
  40. painter.fill_rect(rect(), palette().window());
  41. if (is_enabled() && is_hovered())
  42. painter.fill_rect(rect(), palette().hover_highlight());
  43. Gfx::IntRect box_rect {
  44. 0, height() / 2 - s_box_height / 2 - 1,
  45. s_box_width, s_box_height
  46. };
  47. if (m_checkbox_position == CheckBoxPosition::Right)
  48. box_rect.set_right_without_resize(rect().right());
  49. Gfx::StylePainter::paint_check_box(painter, box_rect, palette(), is_enabled(), is_checked(), is_being_pressed());
  50. paint_text(painter, text_rect, font(), Gfx::TextAlignment::TopLeft);
  51. if (is_focused())
  52. painter.draw_focus_rect(text_rect.inflated(6, 6), palette().focus_outline());
  53. }
  54. void CheckBox::click(unsigned)
  55. {
  56. if (!is_enabled())
  57. return;
  58. set_checked(!is_checked());
  59. }
  60. void CheckBox::set_autosize(bool autosize)
  61. {
  62. if (m_autosize == autosize)
  63. return;
  64. m_autosize = autosize;
  65. if (m_autosize)
  66. size_to_fit();
  67. }
  68. void CheckBox::size_to_fit()
  69. {
  70. set_fixed_width(s_box_width + font().width(text()) + s_horizontal_padding * 2);
  71. }
  72. }