menu_toggle.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #include "ui/widgets/menu/menu_toggle.h"
  8. #include "ui/widgets/checkbox.h"
  9. namespace Ui::Menu {
  10. Toggle::Toggle(
  11. not_null<RpWidget*> parent,
  12. const style::Menu &st,
  13. const QString &text,
  14. Fn<void()> &&callback,
  15. const style::icon *icon,
  16. const style::icon *iconOver)
  17. : Action(
  18. parent,
  19. st,
  20. CreateAction(parent, text, std::move(callback)),
  21. icon,
  22. iconOver)
  23. , _padding(st.itemPadding)
  24. , _toggleShift(st.itemToggleShift)
  25. , _itemToggle(st.itemToggle)
  26. , _itemToggleOver(st.itemToggleOver) {
  27. const auto processAction = [=] {
  28. if (!action()->isCheckable()) {
  29. _toggle.reset();
  30. return;
  31. }
  32. if (_toggle) {
  33. _toggle->setChecked(action()->isChecked(), anim::type::normal);
  34. } else {
  35. _toggle = std::make_unique<ToggleView>(
  36. st.itemToggle,
  37. action()->isChecked(),
  38. [=] { update(); });
  39. }
  40. };
  41. processAction();
  42. connect(action(), &QAction::changed, [=] { processAction(); });
  43. selects(
  44. ) | rpl::start_with_next([=](const CallbackData &data) {
  45. if (!_toggle) {
  46. return;
  47. }
  48. _toggle->setStyle(data.selected ? _itemToggleOver : _itemToggle);
  49. }, lifetime());
  50. }
  51. Toggle::~Toggle() = default;
  52. void Toggle::paintEvent(QPaintEvent *e) {
  53. Action::paintEvent(e);
  54. if (_toggle) {
  55. auto p = QPainter(this);
  56. const auto toggleSize = _toggle->getSize();
  57. _toggle->paint(
  58. p,
  59. width() - _padding.right() - toggleSize.width() + _toggleShift,
  60. (contentHeight() - toggleSize.height()) / 2, width());
  61. }
  62. }
  63. void Toggle::finishAnimating() {
  64. ItemBase::finishAnimating();
  65. if (_toggle) {
  66. _toggle->finishAnimating();
  67. }
  68. }
  69. } // namespace Ui::Menu