toast.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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/toast/toast.h"
  8. #include "ui/toast/toast_manager.h"
  9. #include "ui/toast/toast_widget.h"
  10. #include "styles/style_widgets.h"
  11. namespace Ui {
  12. namespace Toast {
  13. namespace {
  14. QPointer<QWidget> DefaultParent;
  15. } // namespace
  16. Instance::Instance(
  17. not_null<QWidget*> widgetParent,
  18. Config &&config,
  19. const Private &)
  20. : _st(config.st)
  21. , _hideAt(config.infinite
  22. ? 0
  23. : (crl::now() + (config.duration ? config.duration : kDefaultDuration)))
  24. , _sliding(config.attach != RectPart::None)
  25. , _widget(
  26. std::make_unique<internal::Widget>(
  27. widgetParent,
  28. std::move(config))) {
  29. _shownAnimation.start(
  30. [=] { shownAnimationCallback(); },
  31. 0.,
  32. 1.,
  33. _sliding ? _st->durationSlide : _st->durationFadeIn);
  34. }
  35. void SetDefaultParent(not_null<QWidget*> parent) {
  36. DefaultParent = parent;
  37. }
  38. base::weak_ptr<Instance> Show(
  39. not_null<QWidget*> parent,
  40. Config &&config) {
  41. const auto manager = internal::Manager::instance(parent);
  42. return manager->addToast(std::make_unique<Instance>(
  43. parent,
  44. std::move(config),
  45. Instance::Private()));
  46. }
  47. base::weak_ptr<Instance> Show(Config &&config) {
  48. if (const auto parent = DefaultParent.data()) {
  49. return Show(parent, std::move(config));
  50. }
  51. return nullptr;
  52. }
  53. base::weak_ptr<Instance> Show(
  54. not_null<QWidget*> parent,
  55. const QString &text) {
  56. return Show(parent, { .text = { text }, .st = &st::defaultToast });
  57. }
  58. base::weak_ptr<Instance> Show(const QString &text) {
  59. return Show({ .text = { text }, .st = &st::defaultToast });
  60. }
  61. void Instance::shownAnimationCallback() {
  62. _widget->setShownLevel(_shownAnimation.value(_hiding ? 0. : 1.));
  63. if (!_shownAnimation.animating()) {
  64. if (_hiding) {
  65. hide();
  66. }
  67. }
  68. }
  69. void Instance::hideAnimated() {
  70. _hiding = true;
  71. _shownAnimation.start(
  72. [=] { shownAnimationCallback(); },
  73. 1.,
  74. 0.,
  75. _sliding ? _st->durationSlide : _st->durationFadeOut);
  76. }
  77. void Instance::hide() {
  78. _widget->hide();
  79. _widget->deleteLater();
  80. }
  81. not_null<RpWidget*> Instance::widget() const {
  82. return _widget.get();
  83. }
  84. } // namespace Toast
  85. } // namespace Ui