CheckBox.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. set_min_width(32);
  23. set_fixed_height(22);
  24. }
  25. void CheckBox::paint_event(PaintEvent& event)
  26. {
  27. Painter painter(*this);
  28. painter.add_clip_rect(event.rect());
  29. auto text_rect = rect();
  30. text_rect.set_left(s_box_width + s_horizontal_padding);
  31. text_rect.set_width(font().width(text()));
  32. text_rect.set_top(height() / 2 - font().glyph_height() / 2);
  33. text_rect.set_height(font().glyph_height());
  34. if (fill_with_background_color())
  35. painter.fill_rect(rect(), palette().window());
  36. if (is_enabled() && is_hovered())
  37. painter.fill_rect(rect(), palette().hover_highlight());
  38. Gfx::IntRect box_rect {
  39. 0, height() / 2 - s_box_height / 2 - 1,
  40. s_box_width, s_box_height
  41. };
  42. Gfx::StylePainter::paint_check_box(painter, box_rect, palette(), is_enabled(), is_checked(), is_being_pressed());
  43. paint_text(painter, text_rect, font(), Gfx::TextAlignment::TopLeft);
  44. if (is_focused())
  45. painter.draw_focus_rect(text_rect.inflated(6, 6), palette().focus_outline());
  46. }
  47. void CheckBox::click(unsigned)
  48. {
  49. if (!is_enabled())
  50. return;
  51. set_checked(!is_checked());
  52. }
  53. void CheckBox::set_autosize(bool autosize)
  54. {
  55. if (m_autosize == autosize)
  56. return;
  57. m_autosize = autosize;
  58. if (m_autosize)
  59. size_to_fit();
  60. }
  61. void CheckBox::size_to_fit()
  62. {
  63. set_fixed_width(s_box_width + font().width(text()) + s_horizontal_padding * 2);
  64. }
  65. }