Progressbar.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 <AK/Assertions.h>
  8. #include <AK/StringBuilder.h>
  9. #include <LibGUI/Painter.h>
  10. #include <LibGUI/Progressbar.h>
  11. #include <LibGfx/Palette.h>
  12. REGISTER_WIDGET(GUI, Progressbar)
  13. REGISTER_WIDGET(GUI, VerticalProgressbar)
  14. REGISTER_WIDGET(GUI, HorizontalProgressbar)
  15. namespace GUI {
  16. Progressbar::Progressbar(Orientation orientation)
  17. : m_orientation(orientation)
  18. {
  19. REGISTER_STRING_PROPERTY("text", text, set_text);
  20. REGISTER_ENUM_PROPERTY("format", format, set_format, Format,
  21. { Format::NoText, "NoText" },
  22. { Format::Percentage, "Percentage" },
  23. { Format::ValueSlashMax, "ValueSlashMax" });
  24. REGISTER_INT_PROPERTY("min", min, set_min);
  25. REGISTER_INT_PROPERTY("max", max, set_max);
  26. }
  27. void Progressbar::set_value(int value)
  28. {
  29. if (m_value == value)
  30. return;
  31. m_value = value;
  32. update();
  33. }
  34. void Progressbar::set_range(int min, int max)
  35. {
  36. VERIFY(min <= max);
  37. m_min = min;
  38. m_max = max;
  39. m_value = clamp(m_value, m_min, m_max);
  40. }
  41. void Progressbar::paint_event(PaintEvent& event)
  42. {
  43. Frame::paint_event(event);
  44. Painter painter(*this);
  45. auto rect = frame_inner_rect();
  46. painter.add_clip_rect(rect);
  47. painter.add_clip_rect(event.rect());
  48. String progress_text;
  49. if (m_format != Format::NoText) {
  50. // Then we draw the progress text over the gradient.
  51. // We draw it twice, once offset (1, 1) for a drop shadow look.
  52. StringBuilder builder;
  53. builder.append(m_text);
  54. if (m_format == Format::Percentage) {
  55. float range_size = m_max - m_min;
  56. float progress = (m_value - m_min) / range_size;
  57. builder.appendff("{}%", (int)(progress * 100));
  58. } else if (m_format == Format::ValueSlashMax) {
  59. builder.appendff("{}/{}", m_value, m_max);
  60. }
  61. progress_text = builder.to_string();
  62. }
  63. Gfx::StylePainter::paint_progressbar(painter, rect, palette(), m_min, m_max, m_value, progress_text, m_orientation);
  64. }
  65. void Progressbar::set_orientation(Orientation value)
  66. {
  67. if (m_orientation == value)
  68. return;
  69. m_orientation = value;
  70. update();
  71. }
  72. }