Progressbar.cpp 2.2 KB

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