payments_panel.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "payments/ui/payments_panel.h"
  8. #include "payments/ui/payments_form_summary.h"
  9. #include "payments/ui/payments_edit_information.h"
  10. #include "payments/ui/payments_edit_card.h"
  11. #include "payments/ui/payments_panel_delegate.h"
  12. #include "payments/ui/payments_field.h"
  13. #include "ui/widgets/separate_panel.h"
  14. #include "ui/widgets/checkbox.h"
  15. #include "ui/wrap/fade_wrap.h"
  16. #include "ui/boxes/single_choice_box.h"
  17. #include "ui/chat/attach/attach_bot_webview.h"
  18. #include "ui/text/format_values.h"
  19. #include "ui/text/text_utilities.h"
  20. #include "ui/effects/radial_animation.h"
  21. #include "ui/click_handler.h"
  22. #include "lang/lang_keys.h"
  23. #include "webview/webview_embed.h"
  24. #include "webview/webview_interface.h"
  25. #include "styles/style_payments.h"
  26. #include "styles/style_layers.h"
  27. namespace Payments::Ui {
  28. namespace {
  29. constexpr auto kProgressDuration = crl::time(200);
  30. constexpr auto kProgressOpacity = 0.3;
  31. } // namespace
  32. struct Panel::Progress {
  33. Progress(QWidget *parent, Fn<QRect()> rect);
  34. RpWidget widget;
  35. InfiniteRadialAnimation animation;
  36. Animations::Simple shownAnimation;
  37. bool shown = true;
  38. rpl::lifetime geometryLifetime;
  39. };
  40. struct Panel::WebviewWithLifetime {
  41. WebviewWithLifetime(
  42. QWidget *parent = nullptr,
  43. Webview::WindowConfig config = Webview::WindowConfig());
  44. Webview::Window window;
  45. QPointer<RpWidget> lastHidingBox;
  46. rpl::lifetime lifetime;
  47. };
  48. Panel::WebviewWithLifetime::WebviewWithLifetime(
  49. QWidget *parent,
  50. Webview::WindowConfig config)
  51. : window(parent, std::move(config)) {
  52. }
  53. Panel::Progress::Progress(QWidget *parent, Fn<QRect()> rect)
  54. : widget(parent)
  55. , animation(
  56. [=] { if (!anim::Disabled()) widget.update(rect()); },
  57. st::paymentsLoading) {
  58. }
  59. Panel::Panel(not_null<PanelDelegate*> delegate)
  60. : _delegate(delegate)
  61. , _widget(std::make_unique<SeparatePanel>()) {
  62. _widget->setWindowFlag(Qt::WindowStaysOnTopHint, false);
  63. _widget->setInnerSize(st::paymentsPanelSize);
  64. _widget->closeRequests(
  65. ) | rpl::start_with_next([=] {
  66. _delegate->panelRequestClose();
  67. }, _widget->lifetime());
  68. _widget->closeEvents(
  69. ) | rpl::start_with_next([=] {
  70. _delegate->panelCloseSure();
  71. }, _widget->lifetime());
  72. style::PaletteChanged(
  73. ) | rpl::filter([=] {
  74. return !_themeUpdateScheduled;
  75. }) | rpl::start_with_next([=] {
  76. _themeUpdateScheduled = true;
  77. crl::on_main(_widget.get(), [=] {
  78. _themeUpdateScheduled = false;
  79. updateThemeParams(_delegate->panelWebviewThemeParams());
  80. });
  81. }, lifetime());
  82. }
  83. Panel::~Panel() {
  84. base::take(_webview);
  85. _progress = nullptr;
  86. _widget = nullptr;
  87. }
  88. void Panel::requestActivate() {
  89. _widget->showAndActivate();
  90. }
  91. void Panel::toggleProgress(bool shown) {
  92. if (!_progress) {
  93. if (!shown) {
  94. return;
  95. }
  96. _progress = std::make_unique<Progress>(
  97. _widget.get(),
  98. [=] { return progressRect(); });
  99. _progress->widget.paintRequest(
  100. ) | rpl::start_with_next([=](QRect clip) {
  101. auto p = QPainter(&_progress->widget);
  102. p.setOpacity(
  103. _progress->shownAnimation.value(_progress->shown ? 1. : 0.));
  104. auto thickness = st::paymentsLoading.thickness;
  105. if (progressWithBackground()) {
  106. auto color = st::windowBg->c;
  107. color.setAlphaF(kProgressOpacity);
  108. p.fillRect(clip, color);
  109. }
  110. const auto rect = progressRect().marginsRemoved(
  111. { thickness, thickness, thickness, thickness });
  112. InfiniteRadialAnimation::Draw(
  113. p,
  114. _progress->animation.computeState(),
  115. rect.topLeft(),
  116. rect.size() - QSize(),
  117. _progress->widget.width(),
  118. st::paymentsLoading.color,
  119. thickness);
  120. }, _progress->widget.lifetime());
  121. _progress->widget.show();
  122. _progress->animation.start();
  123. } else if (_progress->shown == shown) {
  124. return;
  125. }
  126. const auto callback = [=] {
  127. if (!_progress->shownAnimation.animating() && !_progress->shown) {
  128. _progress = nullptr;
  129. } else {
  130. _progress->widget.update();
  131. }
  132. };
  133. _progress->shown = shown;
  134. _progress->shownAnimation.start(
  135. callback,
  136. shown ? 0. : 1.,
  137. shown ? 1. : 0.,
  138. kProgressDuration);
  139. if (shown) {
  140. setupProgressGeometry();
  141. }
  142. }
  143. bool Panel::progressWithBackground() const {
  144. return (_progress->widget.width() == _widget->innerGeometry().width());
  145. }
  146. QRect Panel::progressRect() const {
  147. const auto rect = _progress->widget.rect();
  148. if (!progressWithBackground()) {
  149. return rect;
  150. }
  151. const auto size = st::defaultBoxButton.height;
  152. return QRect(
  153. rect.x() + (rect.width() - size) / 2,
  154. rect.y() + (rect.height() - size) / 2,
  155. size,
  156. size);
  157. }
  158. void Panel::setupProgressGeometry() {
  159. if (!_progress || !_progress->shown) {
  160. return;
  161. }
  162. _progress->geometryLifetime.destroy();
  163. if (_webviewBottom) {
  164. _webviewBottom->geometryValue(
  165. ) | rpl::start_with_next([=](QRect bottom) {
  166. const auto height = bottom.height();
  167. const auto size = st::paymentsLoading.size;
  168. const auto skip = (height - size.height()) / 2;
  169. const auto inner = _widget->innerGeometry();
  170. const auto right = inner.x() + inner.width();
  171. const auto top = inner.y() + inner.height() - height;
  172. // This doesn't work, because first we get the correct bottom
  173. // geometry and after that we get the previous event (which
  174. // triggered the 'fire' of correct geometry before getting here).
  175. //const auto right = bottom.x() + bottom.width();
  176. //const auto top = bottom.y();
  177. _progress->widget.setGeometry(QRect{
  178. QPoint(right - skip - size.width(), top + skip),
  179. size });
  180. }, _progress->geometryLifetime);
  181. } else if (_weakFormSummary) {
  182. _weakFormSummary->sizeValue(
  183. ) | rpl::start_with_next([=](QSize form) {
  184. const auto full = _widget->innerGeometry();
  185. const auto size = st::defaultBoxButton.height;
  186. const auto inner = _weakFormSummary->contentHeight();
  187. const auto left = full.height() - inner;
  188. if (left >= 2 * size) {
  189. _progress->widget.setGeometry(
  190. full.x() + (full.width() - size) / 2,
  191. full.y() + inner + (left - size) / 2,
  192. size,
  193. size);
  194. } else {
  195. _progress->widget.setGeometry(full);
  196. }
  197. }, _progress->geometryLifetime);
  198. } else if (_weakEditInformation) {
  199. _weakEditInformation->geometryValue(
  200. ) | rpl::start_with_next([=] {
  201. _progress->widget.setGeometry(_widget->innerGeometry());
  202. }, _progress->geometryLifetime);
  203. } else if (_weakEditCard) {
  204. _weakEditCard->geometryValue(
  205. ) | rpl::start_with_next([=] {
  206. _progress->widget.setGeometry(_widget->innerGeometry());
  207. }, _progress->geometryLifetime);
  208. }
  209. _progress->widget.show();
  210. _progress->widget.raise();
  211. if (_progress->shown) {
  212. _progress->widget.setFocus();
  213. }
  214. }
  215. void Panel::showForm(
  216. const Invoice &invoice,
  217. const RequestedInformation &current,
  218. const PaymentMethodDetails &method,
  219. const ShippingOptions &options) {
  220. if (invoice
  221. && method.savedMethods.empty()
  222. && !method.native.supported) {
  223. const auto available = Webview::Availability();
  224. if (available.error != Webview::Available::Error::None) {
  225. showWebviewError(
  226. tr::lng_payments_webview_no_use(tr::now),
  227. available);
  228. return;
  229. }
  230. }
  231. _testMode = invoice.isTest;
  232. setTitle(invoice.receipt
  233. ? tr::lng_payments_receipt_title()
  234. : tr::lng_payments_checkout_title());
  235. auto form = base::make_unique_q<FormSummary>(
  236. _widget.get(),
  237. invoice,
  238. current,
  239. method,
  240. options,
  241. _delegate,
  242. _formScrollTop.current());
  243. _weakFormSummary = form.get();
  244. _widget->showInner(std::move(form));
  245. _widget->setBackAllowed(false);
  246. _formScrollTop = _weakFormSummary->scrollTopValue();
  247. setupProgressGeometry();
  248. }
  249. void Panel::updateFormThumbnail(const QImage &thumbnail) {
  250. if (_weakFormSummary) {
  251. _weakFormSummary->updateThumbnail(thumbnail);
  252. }
  253. }
  254. void Panel::showEditInformation(
  255. const Invoice &invoice,
  256. const RequestedInformation &current,
  257. InformationField field) {
  258. setTitle(tr::lng_payments_shipping_address_title());
  259. auto edit = base::make_unique_q<EditInformation>(
  260. _widget.get(),
  261. invoice,
  262. current,
  263. field,
  264. _delegate);
  265. _weakEditInformation = edit.get();
  266. _widget->showInner(std::move(edit));
  267. _widget->setBackAllowed(true);
  268. _weakEditInformation->setFocusFast(field);
  269. setupProgressGeometry();
  270. }
  271. void Panel::showInformationError(
  272. const Invoice &invoice,
  273. const RequestedInformation &current,
  274. InformationField field) {
  275. if (_weakEditInformation) {
  276. _weakEditInformation->showError(field);
  277. } else {
  278. showEditInformation(invoice, current, field);
  279. if (_weakEditInformation
  280. && field == InformationField::ShippingCountry) {
  281. _weakEditInformation->showError(field);
  282. }
  283. }
  284. }
  285. void Panel::chooseShippingOption(const ShippingOptions &options) {
  286. showBox(Box([=](not_null<GenericBox*> box) {
  287. const auto i = ranges::find(
  288. options.list,
  289. options.selectedId,
  290. &ShippingOption::id);
  291. const auto index = (i != end(options.list))
  292. ? int(i - begin(options.list))
  293. : -1;
  294. const auto group = std::make_shared<RadiobuttonGroup>(index);
  295. const auto layout = box->verticalLayout();
  296. auto counter = 0;
  297. for (const auto &option : options.list) {
  298. const auto index = counter++;
  299. const auto button = layout->add(
  300. object_ptr<Radiobutton>(
  301. layout,
  302. group,
  303. index,
  304. QString(),
  305. st::defaultBoxCheckbox,
  306. st::defaultRadio),
  307. st::paymentsShippingMargin);
  308. const auto label = CreateChild<FlatLabel>(
  309. layout.get(),
  310. option.title,
  311. st::paymentsShippingLabel);
  312. const auto total = ranges::accumulate(
  313. option.prices,
  314. int64(0),
  315. std::plus<>(),
  316. &LabeledPrice::price);
  317. const auto price = CreateChild<FlatLabel>(
  318. layout.get(),
  319. FillAmountAndCurrency(total, options.currency),
  320. st::paymentsShippingPrice);
  321. const auto area = CreateChild<AbstractButton>(layout.get());
  322. area->setClickedCallback([=] { group->setValue(index); });
  323. button->geometryValue(
  324. ) | rpl::start_with_next([=](QRect geometry) {
  325. label->move(
  326. geometry.topLeft() + st::paymentsShippingLabelPosition);
  327. price->move(
  328. geometry.topLeft() + st::paymentsShippingPricePosition);
  329. const auto right = geometry.x()
  330. + st::paymentsShippingLabelPosition.x();
  331. area->setGeometry(
  332. right,
  333. geometry.y(),
  334. std::max(
  335. label->x() + label->width() - right,
  336. price->x() + price->width() - right),
  337. price->y() + price->height() - geometry.y());
  338. }, button->lifetime());
  339. }
  340. box->setTitle(tr::lng_payments_shipping_method());
  341. box->addButton(tr::lng_cancel(), [=] { box->closeBox(); });
  342. group->setChangedCallback([=](int index) {
  343. if (index >= 0) {
  344. _delegate->panelChangeShippingOption(
  345. options.list[index].id);
  346. box->closeBox();
  347. }
  348. });
  349. }));
  350. }
  351. void Panel::chooseTips(const Invoice &invoice) {
  352. const auto max = invoice.tipsMax;
  353. const auto now = invoice.tipsSelected;
  354. const auto currency = invoice.currency;
  355. showBox(Box([=](not_null<GenericBox*> box) {
  356. box->setTitle(tr::lng_payments_tips_box_title());
  357. const auto row = box->lifetime().make_state<Field>(
  358. box,
  359. FieldConfig{
  360. .type = FieldType::Money,
  361. .value = QString::number(now),
  362. .currency = currency,
  363. });
  364. box->setFocusCallback([=] {
  365. row->setFocusFast();
  366. });
  367. box->addRow(row->ownedWidget());
  368. const auto errorWrap = box->addRow(
  369. object_ptr<FadeWrap<FlatLabel>>(
  370. box,
  371. object_ptr<FlatLabel>(
  372. box,
  373. tr::lng_payments_tips_max(
  374. lt_amount,
  375. rpl::single(FillAmountAndCurrency(max, currency))),
  376. st::paymentTipsErrorLabel)),
  377. st::paymentTipsErrorPadding);
  378. errorWrap->hide(anim::type::instant);
  379. const auto submit = [=] {
  380. const auto value = row->value().toLongLong();
  381. if (value > max) {
  382. row->showError();
  383. errorWrap->show(anim::type::normal);
  384. } else {
  385. _delegate->panelChangeTips(value);
  386. box->closeBox();
  387. }
  388. };
  389. row->submitted(
  390. ) | rpl::start_with_next(submit, box->lifetime());
  391. box->addButton(tr::lng_settings_save(), submit);
  392. box->addButton(tr::lng_cancel(), [=] { box->closeBox(); });
  393. }));
  394. }
  395. void Panel::showEditPaymentMethod(const PaymentMethodDetails &method) {
  396. setTitle(tr::lng_payments_card_title());
  397. if (method.native.supported) {
  398. showEditCard(method.native, CardField::Number);
  399. } else {
  400. showEditCardByUrl(
  401. method.url,
  402. method.provider,
  403. method.canSaveInformation);
  404. }
  405. }
  406. void Panel::showEditCardByUrl(
  407. const QString &url,
  408. const QString &provider,
  409. bool canSaveInformation) {
  410. auto bottomText = canSaveInformation
  411. ? rpl::producer<QString>()
  412. : tr::lng_payments_processed_by(lt_provider, rpl::single(provider));
  413. if (!showWebview(url, true, std::move(bottomText))) {
  414. const auto available = Webview::Availability();
  415. if (available.error != Webview::Available::Error::None) {
  416. showWebviewError(
  417. tr::lng_payments_webview_no_use(tr::now),
  418. available);
  419. } else {
  420. showCriticalError({ "Error: Could not initialize WebView." });
  421. }
  422. _widget->setBackAllowed(true);
  423. } else if (canSaveInformation) {
  424. const auto &padding = st::paymentsPanelPadding;
  425. _saveWebviewInformation = CreateChild<Checkbox>(
  426. _webviewBottom.get(),
  427. tr::lng_payments_save_information(tr::now),
  428. false);
  429. const auto height = padding.top()
  430. + _saveWebviewInformation->heightNoMargins()
  431. + padding.bottom();
  432. _saveWebviewInformation->moveToLeft(padding.right(), padding.top());
  433. _saveWebviewInformation->show();
  434. _webviewBottom->resize(_webviewBottom->width(), height);
  435. }
  436. }
  437. void Panel::showAdditionalMethod(
  438. const PaymentMethodAdditional &method,
  439. const QString &provider,
  440. bool canSaveInformation) {
  441. setTitle(rpl::single(method.title));
  442. showEditCardByUrl(method.url, provider, canSaveInformation);
  443. }
  444. void Panel::showWebviewProgress() {
  445. if (_webviewProgress && _progress && _progress->shown) {
  446. return;
  447. }
  448. _webviewProgress = true;
  449. toggleProgress(true);
  450. }
  451. void Panel::hideWebviewProgress() {
  452. if (!_webviewProgress) {
  453. return;
  454. }
  455. _webviewProgress = false;
  456. toggleProgress(false);
  457. }
  458. bool Panel::showWebview(
  459. const QString &url,
  460. bool allowBack,
  461. rpl::producer<QString> bottomText) {
  462. const auto params = _delegate->panelWebviewThemeParams();
  463. if (!_webview && !createWebview(params)) {
  464. return false;
  465. }
  466. showWebviewProgress();
  467. _widget->hideLayer(anim::type::instant);
  468. updateThemeParams(params);
  469. _webview->window.navigate(url);
  470. _widget->setBackAllowed(allowBack);
  471. if (bottomText) {
  472. const auto &padding = st::paymentsPanelPadding;
  473. const auto label = CreateChild<FlatLabel>(
  474. _webviewBottom.get(),
  475. std::move(bottomText),
  476. st::paymentsWebviewBottom);
  477. const auto height = padding.top()
  478. + label->heightNoMargins()
  479. + padding.bottom();
  480. rpl::combine(
  481. _webviewBottom->widthValue(),
  482. label->widthValue()
  483. ) | rpl::start_with_next([=](int outerWidth, int width) {
  484. label->move((outerWidth - width) / 2, padding.top());
  485. }, label->lifetime());
  486. label->show();
  487. _webviewBottom->resize(_webviewBottom->width(), height);
  488. }
  489. return true;
  490. }
  491. bool Panel::createWebview(const Webview::ThemeParams &params) {
  492. auto outer = base::make_unique_q<RpWidget>(_widget.get());
  493. const auto container = outer.get();
  494. _widget->showInner(std::move(outer));
  495. const auto webviewParent = QPointer<RpWidget>(container);
  496. _webviewBottom = std::make_unique<RpWidget>(_widget.get());
  497. const auto bottom = _webviewBottom.get();
  498. bottom->show();
  499. rpl::combine(
  500. container->geometryValue() | rpl::map([=] {
  501. return _widget->innerGeometry();
  502. }),
  503. bottom->heightValue()
  504. ) | rpl::start_with_next([=](QRect inner, int height) {
  505. bottom->move(inner.x(), inner.y() + inner.height() - height);
  506. bottom->resizeToWidth(inner.width());
  507. _footerHeight = bottom->height();
  508. }, bottom->lifetime());
  509. container->show();
  510. _webview = std::make_unique<WebviewWithLifetime>(
  511. container,
  512. Webview::WindowConfig{
  513. .opaqueBg = params.bodyBg,
  514. .storageId = _delegate->panelWebviewStorageId(),
  515. });
  516. const auto raw = &_webview->window;
  517. QObject::connect(container, &QObject::destroyed, [=] {
  518. if (_webview && &_webview->window == raw) {
  519. base::take(_webview);
  520. if (_webviewProgress) {
  521. hideWebviewProgress();
  522. if (_progress && !_progress->shown) {
  523. _progress = nullptr;
  524. }
  525. }
  526. }
  527. if (_webviewBottom.get() == bottom) {
  528. _webviewBottom = nullptr;
  529. }
  530. });
  531. if (!raw->widget()) {
  532. return false;
  533. }
  534. QObject::connect(raw->widget(), &QObject::destroyed, [=] {
  535. const auto parent = webviewParent.data();
  536. if (!_webview
  537. || &_webview->window != raw
  538. || !parent
  539. || _widget->inner() != parent) {
  540. // If we destroyed _webview ourselves,
  541. // or if we changed _widget->inner ourselves,
  542. // we don't show any message, nothing crashed.
  543. return;
  544. }
  545. crl::on_main(this, [=] {
  546. showCriticalError({ "Error: WebView has crashed." });
  547. });
  548. });
  549. rpl::combine(
  550. container->geometryValue(),
  551. _footerHeight.value()
  552. ) | rpl::start_with_next([=](QRect geometry, int footer) {
  553. if (const auto view = raw->widget()) {
  554. view->setGeometry(geometry.marginsRemoved({ 0, 0, 0, footer }));
  555. }
  556. }, _webview->lifetime);
  557. raw->setMessageHandler([=](const QJsonDocument &message) {
  558. const auto save = _saveWebviewInformation
  559. && _saveWebviewInformation->checked();
  560. _delegate->panelWebviewMessage(message, save);
  561. });
  562. raw->setNavigationStartHandler([=](const QString &uri, bool newWindow) {
  563. if (!_delegate->panelWebviewNavigationAttempt(uri)) {
  564. return false;
  565. } else if (newWindow) {
  566. return false;
  567. }
  568. showWebviewProgress();
  569. return true;
  570. });
  571. raw->setNavigationDoneHandler([=](bool success) {
  572. hideWebviewProgress();
  573. });
  574. raw->init(R"(
  575. window.TelegramWebviewProxy = {
  576. postEvent: function(eventType, eventData) {
  577. if (window.external && window.external.invoke) {
  578. window.external.invoke(JSON.stringify([eventType, eventData]));
  579. }
  580. }
  581. };)");
  582. if (!_webview) {
  583. return false;
  584. }
  585. setupProgressGeometry();
  586. return true;
  587. }
  588. void Panel::choosePaymentMethod(const PaymentMethodDetails &method) {
  589. if (method.savedMethods.empty() && method.additionalMethods.empty()) {
  590. showEditPaymentMethod(method);
  591. return;
  592. }
  593. showBox(Box([=](not_null<GenericBox*> box) {
  594. const auto save = [=](int option) {
  595. const auto saved = int(method.savedMethods.size());
  596. if (!option) {
  597. showEditPaymentMethod(method);
  598. } else if (option > saved) {
  599. const auto index = option - saved - 1;
  600. Assert(index < method.additionalMethods.size());
  601. showAdditionalMethod(
  602. method.additionalMethods[index],
  603. method.provider,
  604. method.canSaveInformation);
  605. } else {
  606. const auto index = option - 1;
  607. _savedMethodChosen.fire_copy(method.savedMethods[index].id);
  608. }
  609. };
  610. auto options = std::vector{
  611. tr::lng_payments_new_card(tr::now),
  612. };
  613. for (const auto &saved : method.savedMethods) {
  614. options.push_back(saved.title);
  615. }
  616. for (const auto &additional : method.additionalMethods) {
  617. options.push_back(additional.title);
  618. }
  619. SingleChoiceBox(box, {
  620. .title = tr::lng_payments_payment_method(),
  621. .options = std::move(options),
  622. .initialSelection = (method.savedMethods.empty()
  623. ? -1
  624. : (method.savedMethodIndex + 1)),
  625. .callback = save,
  626. });
  627. }));
  628. }
  629. void Panel::askSetPassword() {
  630. showBox(Box([=](not_null<GenericBox*> box) {
  631. box->addRow(
  632. object_ptr<FlatLabel>(
  633. box.get(),
  634. tr::lng_payments_need_password(),
  635. st::boxLabel),
  636. st::boxPadding);
  637. box->addButton(tr::lng_continue(), [=] {
  638. _delegate->panelSetPassword();
  639. box->closeBox();
  640. });
  641. box->addButton(tr::lng_cancel(), [=] { box->closeBox(); });
  642. }));
  643. }
  644. void Panel::showCloseConfirm() {
  645. showBox(Box([=](not_null<GenericBox*> box) {
  646. box->addRow(
  647. object_ptr<FlatLabel>(
  648. box.get(),
  649. tr::lng_payments_sure_close(),
  650. st::boxLabel),
  651. st::boxPadding);
  652. box->addButton(tr::lng_close(), [=] {
  653. _delegate->panelCloseSure();
  654. });
  655. box->addButton(tr::lng_cancel(), [=] { box->closeBox(); });
  656. }));
  657. }
  658. void Panel::showWarning(const QString &bot, const QString &provider) {
  659. showBox(Box([=](not_null<GenericBox*> box) {
  660. box->setTitle(tr::lng_payments_warning_title());
  661. box->addRow(object_ptr<FlatLabel>(
  662. box.get(),
  663. tr::lng_payments_warning_body(
  664. lt_bot1,
  665. rpl::single(bot),
  666. lt_provider,
  667. rpl::single(provider),
  668. lt_bot2,
  669. rpl::single(bot),
  670. lt_bot3,
  671. rpl::single(bot)),
  672. st::boxLabel));
  673. box->addButton(tr::lng_continue(), [=] {
  674. _delegate->panelTrustAndSubmit();
  675. box->closeBox();
  676. });
  677. box->addButton(tr::lng_cancel(), [=] { box->closeBox(); });
  678. }));
  679. }
  680. void Panel::requestTermsAcceptance(
  681. const QString &username,
  682. const QString &url,
  683. bool recurring) {
  684. showBox(Box([=](not_null<GenericBox*> box) {
  685. box->setTitle(tr::lng_payments_terms_title());
  686. box->addRow(object_ptr<Ui::FlatLabel>(
  687. box.get(),
  688. (recurring
  689. ? tr::lng_payments_terms_text
  690. : tr::lng_payments_terms_text_once)(
  691. lt_bot,
  692. rpl::single(Ui::Text::Bold('@' + username)),
  693. Ui::Text::WithEntities),
  694. st::boxLabel));
  695. const auto update = std::make_shared<Fn<void()>>();
  696. auto checkView = std::make_unique<Ui::CheckView>(
  697. st::defaultCheck,
  698. false,
  699. [=] { if (*update) { (*update)(); } });
  700. const auto check = checkView.get();
  701. const auto row = box->addRow(
  702. object_ptr<Ui::Checkbox>(
  703. box.get(),
  704. tr::lng_payments_terms_agree(
  705. lt_link,
  706. rpl::single(Ui::Text::Link(
  707. tr::lng_payments_terms_link(tr::now),
  708. url)),
  709. Ui::Text::WithEntities),
  710. st::defaultBoxCheckbox,
  711. std::move(checkView)),
  712. {
  713. st::boxRowPadding.left(),
  714. st::boxRowPadding.left(),
  715. st::boxRowPadding.right(),
  716. st::defaultBoxCheckbox.margin.bottom(),
  717. });
  718. row->setAllowTextLines(5);
  719. row->setClickHandlerFilter([=](
  720. const ClickHandlerPtr &link,
  721. Qt::MouseButton button) {
  722. ActivateClickHandler(_widget.get(), link, ClickContext{
  723. .button = button,
  724. .other = _delegate->panelClickHandlerContext(),
  725. });
  726. return false;
  727. });
  728. (*update) = [=] { row->update(); };
  729. const auto showError = Ui::CheckView::PrepareNonToggledError(
  730. check,
  731. box->lifetime());
  732. box->addButton(tr::lng_payments_terms_accept(), [=] {
  733. if (check->checked()) {
  734. _delegate->panelAcceptTermsAndSubmit();
  735. box->closeBox();
  736. } else {
  737. showError();
  738. }
  739. });
  740. box->addButton(tr::lng_cancel(), [=] { box->closeBox(); });
  741. }));
  742. }
  743. void Panel::showEditCard(
  744. const NativeMethodDetails &native,
  745. CardField field) {
  746. Expects(native.supported);
  747. auto edit = base::make_unique_q<EditCard>(
  748. _widget.get(),
  749. native,
  750. field,
  751. _delegate);
  752. _weakEditCard = edit.get();
  753. _widget->showInner(std::move(edit));
  754. _widget->setBackAllowed(true);
  755. _weakEditCard->setFocusFast(field);
  756. setupProgressGeometry();
  757. }
  758. void Panel::showCardError(
  759. const NativeMethodDetails &native,
  760. CardField field) {
  761. if (_weakEditCard) {
  762. _weakEditCard->showError(field);
  763. } else {
  764. // We cancelled card edit already.
  765. //showEditCard(native, field);
  766. //if (_weakEditCard
  767. // && field == CardField::AddressCountry) {
  768. // _weakEditCard->showError(field);
  769. //}
  770. }
  771. }
  772. void Panel::setTitle(rpl::producer<QString> title) {
  773. using namespace rpl::mappers;
  774. if (_testMode) {
  775. _widget->setTitle(std::move(title) | rpl::map(_1 + " (Test)"));
  776. } else {
  777. _widget->setTitle(std::move(title));
  778. }
  779. }
  780. rpl::producer<> Panel::backRequests() const {
  781. return _widget->backRequests();
  782. }
  783. rpl::producer<QString> Panel::savedMethodChosen() const {
  784. return _savedMethodChosen.events();
  785. }
  786. void Panel::showBox(object_ptr<BoxContent> box) {
  787. if (const auto widget = _webview ? _webview->window.widget() : nullptr) {
  788. const auto hideNow = !widget->isHidden();
  789. if (hideNow || _webview->lastHidingBox) {
  790. const auto raw = _webview->lastHidingBox = box.data();
  791. box->boxClosing(
  792. ) | rpl::start_with_next([=] {
  793. const auto widget = _webview
  794. ? _webview->window.widget()
  795. : nullptr;
  796. if (widget
  797. && widget->isHidden()
  798. && _webview->lastHidingBox == raw) {
  799. widget->show();
  800. }
  801. }, _webview->lifetime);
  802. if (hideNow) {
  803. widget->hide();
  804. }
  805. }
  806. }
  807. _widget->showBox(
  808. std::move(box),
  809. LayerOption::KeepOther,
  810. anim::type::normal);
  811. }
  812. void Panel::showToast(TextWithEntities &&text) {
  813. _widget->showToast(std::move(text));
  814. }
  815. void Panel::showCriticalError(const TextWithEntities &text) {
  816. _progress = nullptr;
  817. _webviewProgress = false;
  818. if (!_weakFormSummary || !_weakFormSummary->showCriticalError(text)) {
  819. auto error = base::make_unique_q<PaddingWrap<FlatLabel>>(
  820. _widget.get(),
  821. object_ptr<FlatLabel>(
  822. _widget.get(),
  823. rpl::single(text),
  824. st::paymentsCriticalError),
  825. st::paymentsCriticalErrorPadding);
  826. error->entity()->setClickHandlerFilter([=](
  827. const ClickHandlerPtr &handler,
  828. Qt::MouseButton) {
  829. const auto entity = handler->getTextEntity();
  830. if (entity.type != EntityType::CustomUrl) {
  831. return true;
  832. }
  833. _delegate->panelOpenUrl(entity.data);
  834. return false;
  835. });
  836. _widget->showInner(std::move(error));
  837. }
  838. }
  839. std::shared_ptr<Show> Panel::uiShow() {
  840. return _widget->uiShow();
  841. }
  842. void Panel::showWebviewError(
  843. const QString &text,
  844. const Webview::Available &information) {
  845. showCriticalError(TextWithEntities{ text }.append(
  846. "\n\n"
  847. ).append(BotWebView::ErrorText(information)));
  848. }
  849. void Panel::updateThemeParams(const Webview::ThemeParams &params) {
  850. if (!_webview || !_webview->window.widget()) {
  851. return;
  852. }
  853. _webview->window.updateTheme(
  854. params.bodyBg,
  855. params.scrollBg,
  856. params.scrollBgOver,
  857. params.scrollBarBg,
  858. params.scrollBarBgOver);
  859. _webview->window.eval(R"(
  860. if (window.TelegramGameProxy) {
  861. window.TelegramGameProxy.receiveEvent(
  862. "theme_changed",
  863. { "theme_params": )" + params.json + R"( });
  864. }
  865. )");
  866. }
  867. rpl::lifetime &Panel::lifetime() {
  868. return _widget->lifetime();
  869. }
  870. } // namespace Payments::Ui