settings_credits_graphics.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771
  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 "settings/settings_credits_graphics.h"
  8. #include "api/api_chat_invite.h"
  9. #include "api/api_credits.h"
  10. #include "api/api_earn.h"
  11. #include "api/api_premium.h"
  12. #include "apiwrap.h"
  13. #include "base/random.h"
  14. #include "base/timer_rpl.h"
  15. #include "base/unixtime.h"
  16. #include "boxes/gift_premium_box.h"
  17. #include "boxes/share_box.h"
  18. #include "boxes/star_gift_box.h"
  19. #include "boxes/transfer_gift_box.h"
  20. #include "chat_helpers/stickers_gift_box_pack.h"
  21. #include "chat_helpers/stickers_lottie.h"
  22. #include "core/application.h"
  23. #include "core/click_handler_types.h"
  24. #include "core/click_handler_types.h" // UrlClickHandler
  25. #include "core/ui_integration.h"
  26. #include "data/components/credits.h"
  27. #include "data/data_boosts.h"
  28. #include "data/data_channel.h"
  29. #include "data/data_document.h"
  30. #include "data/data_document_media.h"
  31. #include "data/data_emoji_statuses.h"
  32. #include "data/data_file_origin.h"
  33. #include "data/data_photo_media.h"
  34. #include "data/data_session.h"
  35. #include "data/data_subscriptions.h"
  36. #include "data/data_user.h"
  37. #include "data/stickers/data_custom_emoji.h"
  38. #include "history/history.h"
  39. #include "history/history_item.h"
  40. #include "history/history_item_components.h" // HistoryServicePaymentRefund.
  41. #include "info/bot/starref/info_bot_starref_common.h"
  42. #include "info/channel_statistics/boosts/giveaway/boost_badge.h" // InfiniteRadialAnimationWidget.
  43. #include "info/channel_statistics/earn/info_channel_earn_widget.h" // Info::ChannelEarn::Make.
  44. #include "info/peer_gifts/info_peer_gifts_common.h"
  45. #include "info/settings/info_settings_widget.h" // SectionCustomTopBarData.
  46. #include "info/statistics/info_statistics_list_controllers.h"
  47. #include "info/info_controller.h"
  48. #include "info/info_memento.h"
  49. #include "iv/iv_instance.h"
  50. #include "lang/lang_keys.h"
  51. #include "lottie/lottie_single_player.h"
  52. #include "main/main_app_config.h"
  53. #include "main/main_session.h"
  54. #include "payments/payments_checkout_process.h"
  55. #include "payments/payments_form.h"
  56. #include "payments/payments_non_panel_process.h"
  57. #include "settings/settings_common_session.h"
  58. #include "settings/settings_credits.h"
  59. #include "statistics/widgets/chart_header_widget.h"
  60. #include "ui/boxes/confirm_box.h"
  61. #include "ui/controls/userpic_button.h"
  62. #include "ui/dynamic_image.h"
  63. #include "ui/dynamic_thumbnails.h"
  64. #include "ui/effects/credits_graphics.h"
  65. #include "ui/effects/premium_graphics.h"
  66. #include "ui/effects/premium_stars_colored.h"
  67. #include "ui/effects/premium_top_bar.h"
  68. #include "ui/effects/toggle_arrow.h"
  69. #include "ui/image/image_prepare.h"
  70. #include "ui/layers/generic_box.h"
  71. #include "ui/painter.h"
  72. #include "ui/rect.h"
  73. #include "ui/text/format_values.h"
  74. #include "ui/text/text_utilities.h"
  75. #include "ui/toast/toast.h"
  76. #include "ui/vertical_list.h"
  77. #include "ui/widgets/buttons.h"
  78. #include "ui/widgets/discrete_sliders.h"
  79. #include "ui/widgets/fields/number_input.h"
  80. #include "ui/widgets/popup_menu.h"
  81. #include "ui/widgets/label_with_custom_emoji.h"
  82. #include "ui/widgets/labels.h"
  83. #include "ui/widgets/tooltip.h"
  84. #include "ui/wrap/fade_wrap.h"
  85. #include "ui/wrap/padding_wrap.h"
  86. #include "ui/wrap/slide_wrap.h"
  87. #include "ui/wrap/vertical_layout.h"
  88. #include "ui/ui_utility.h"
  89. #include "window/window_session_controller.h"
  90. #include "styles/style_calls.h"
  91. #include "styles/style_channel_earn.h"
  92. #include "styles/style_chat.h"
  93. #include "styles/style_credits.h"
  94. #include "styles/style_giveaway.h"
  95. #include "styles/style_info.h"
  96. #include "styles/style_layers.h"
  97. #include "styles/style_media_view.h"
  98. #include "styles/style_menu_icons.h"
  99. #include "styles/style_premium.h"
  100. #include "styles/style_settings.h"
  101. #include "styles/style_statistics.h"
  102. #include <xxhash.h> // XXH64.
  103. #include <QtSvg/QSvgRenderer>
  104. namespace Settings {
  105. namespace {
  106. const auto kTopUpPrefix = "cloud_lng_topup_purpose_";
  107. [[nodiscard]] uint64 UniqueIdFromOption(
  108. const Data::CreditTopupOption &d) {
  109. const auto string = QString::number(d.credits)
  110. + d.product
  111. + d.currency
  112. + QString::number(d.amount);
  113. return XXH64(string.data(), string.size() * sizeof(ushort), 0);
  114. }
  115. [[nodiscard]] int WithdrawalMin(not_null<Main::Session*> session) {
  116. const auto key = u"stars_revenue_withdrawal_min"_q;
  117. return session->appConfig().get<int>(key, 1000);
  118. }
  119. [[nodiscard]] rpl::producer<TextWithEntities> DeepLinkBalanceAbout(
  120. const QString &purpose) {
  121. const auto phrase = Lang::GetNonDefaultValue(
  122. kTopUpPrefix + purpose.toUtf8());
  123. return phrase.isEmpty()
  124. ? tr::lng_credits_small_balance_fallback(Ui::Text::RichLangValue)
  125. : rpl::single(Ui::Text::RichLangValue(phrase));
  126. }
  127. class Balance final
  128. : public Ui::RpWidget
  129. , public Ui::AbstractTooltipShower {
  130. public:
  131. using Ui::RpWidget::RpWidget;
  132. void setBalance(StarsAmount balance) {
  133. _balance = balance;
  134. _tooltip = Lang::FormatStarsAmountDecimal(balance);
  135. }
  136. void enterEventHook(QEnterEvent *e) override {
  137. if (_balance >= StarsAmount(10'000)) {
  138. Ui::Tooltip::Show(1000, this);
  139. }
  140. }
  141. void leaveEventHook(QEvent *e) override {
  142. Ui::Tooltip::Hide();
  143. }
  144. QString tooltipText() const override {
  145. return _tooltip;
  146. }
  147. QPoint tooltipPos() const override {
  148. return QCursor::pos();
  149. }
  150. bool tooltipWindowActive() const override {
  151. return Ui::AppInFocus() && Ui::InFocusChain(window());
  152. }
  153. private:
  154. QString _tooltip;
  155. StarsAmount _balance;
  156. };
  157. void ToggleStarGiftSaved(
  158. std::shared_ptr<ChatHelpers::Show> show,
  159. Data::SavedStarGiftId savedId,
  160. bool save,
  161. Fn<void(bool)> done = nullptr) {
  162. using Flag = MTPpayments_SaveStarGift::Flag;
  163. const auto api = &show->session().api();
  164. const auto channelGift = savedId.chat();
  165. api->request(MTPpayments_SaveStarGift(
  166. MTP_flags(save ? Flag(0) : Flag::f_unsave),
  167. Api::InputSavedStarGiftId(savedId)
  168. )).done([=] {
  169. using GiftAction = Data::GiftUpdate::Action;
  170. show->session().data().notifyGiftUpdate({
  171. .id = savedId,
  172. .action = (save ? GiftAction::Save : GiftAction::Unsave),
  173. });
  174. if (const auto onstack = done) {
  175. onstack(true);
  176. }
  177. show->showToast((save
  178. ? (channelGift
  179. ? tr::lng_gift_display_done_channel
  180. : tr::lng_gift_display_done)
  181. : (channelGift
  182. ? tr::lng_gift_display_done_hide_channel
  183. : tr::lng_gift_display_done_hide))(tr::now));
  184. }).fail([=](const MTP::Error &error) {
  185. if (const auto onstack = done) {
  186. onstack(false);
  187. }
  188. show->showToast(error.type());
  189. }).send();
  190. }
  191. void ToggleStarGiftPinned(
  192. std::shared_ptr<ChatHelpers::Show> show,
  193. Data::SavedStarGiftId savedId,
  194. std::vector<Data::SavedStarGiftId> already,
  195. bool pinned,
  196. std::shared_ptr<Data::UniqueGift> uniqueData = nullptr,
  197. std::shared_ptr<Data::UniqueGift> replacingData = nullptr) {
  198. already.erase(ranges::remove(already, savedId), end(already));
  199. if (pinned) {
  200. already.insert(begin(already), savedId);
  201. const auto limit = show->session().appConfig().pinnedGiftsLimit();
  202. if (already.size() > limit) {
  203. already.erase(begin(already) + limit, end(already));
  204. }
  205. }
  206. auto inputs = QVector<MTPInputSavedStarGift>();
  207. inputs.reserve(already.size());
  208. for (const auto &id : already) {
  209. inputs.push_back(Api::InputSavedStarGiftId(id));
  210. }
  211. const auto api = &show->session().api();
  212. const auto peer = savedId.chat()
  213. ? savedId.chat()
  214. : show->session().user();
  215. api->request(MTPpayments_ToggleStarGiftsPinnedToTop(
  216. peer->input,
  217. MTP_vector<MTPInputSavedStarGift>(std::move(inputs))
  218. )).done([=] {
  219. using GiftAction = Data::GiftUpdate::Action;
  220. show->session().data().notifyGiftUpdate({
  221. .id = savedId,
  222. .action = (pinned ? GiftAction::Pin : GiftAction::Unpin),
  223. });
  224. if (pinned) {
  225. show->showToast({
  226. .title = (uniqueData
  227. ? tr::lng_gift_pinned_done_title(
  228. tr::now,
  229. lt_gift,
  230. Data::UniqueGiftName(*uniqueData))
  231. : QString()),
  232. .text = (replacingData
  233. ? tr::lng_gift_pinned_done_replaced(
  234. tr::now,
  235. lt_gift,
  236. TextWithEntities{
  237. Data::UniqueGiftName(*replacingData),
  238. },
  239. Ui::Text::WithEntities)
  240. : tr::lng_gift_pinned_done(
  241. tr::now,
  242. Ui::Text::WithEntities)),
  243. .duration = Ui::Toast::kDefaultDuration * 2,
  244. });
  245. }
  246. }).fail([=](const MTP::Error &error) {
  247. show->showToast(error.type());
  248. }).send();
  249. }
  250. void ConfirmConvertStarGift(
  251. std::shared_ptr<Ui::Show> show,
  252. rpl::producer<TextWithEntities> confirmText,
  253. int stars,
  254. int daysLeft,
  255. Fn<void()> convert) {
  256. auto text = rpl::combine(
  257. std::move(confirmText),
  258. tr::lng_gift_convert_sure_limit(
  259. lt_count,
  260. rpl::single(daysLeft * 1.),
  261. Ui::Text::RichLangValue),
  262. tr::lng_gift_convert_sure_caution(Ui::Text::RichLangValue)
  263. ) | rpl::map([](
  264. TextWithEntities &&a,
  265. TextWithEntities &&b,
  266. TextWithEntities &&c) {
  267. return a.append("\n\n").append(b).append("\n\n").append(c);
  268. });
  269. show->show(Ui::MakeConfirmBox({
  270. .text = std::move(text),
  271. .confirmed = [=](Fn<void()> close) { close(); convert(); },
  272. .confirmText = tr::lng_gift_convert_sure(),
  273. .title = tr::lng_gift_convert_sure_title(),
  274. }));
  275. }
  276. void ConvertStarGift(
  277. std::shared_ptr<ChatHelpers::Show> show,
  278. Data::SavedStarGiftId savedId,
  279. int stars,
  280. Fn<void(bool)> done) {
  281. const auto api = &show->session().api();
  282. api->request(MTPpayments_ConvertStarGift(
  283. Api::InputSavedStarGiftId(savedId)
  284. )).done([=] {
  285. if (const auto window = show->resolveWindow()) {
  286. if (const auto channel = savedId.chat()) {
  287. window->showSection(Info::ChannelEarn::Make(channel));
  288. } else {
  289. window->showSettings(Settings::CreditsId());
  290. }
  291. }
  292. show->showToast((savedId.chat()
  293. ? tr::lng_gift_channel_got
  294. : tr::lng_gift_got_stars)(
  295. tr::now,
  296. lt_count,
  297. stars,
  298. Ui::Text::RichLangValue));
  299. done(true);
  300. }).fail([=](const MTP::Error &error) {
  301. show->showToast(error.type());
  302. done(false);
  303. }).send();
  304. }
  305. void AddViewMediaHandler(
  306. not_null<Ui::RpWidget*> thumb,
  307. std::shared_ptr<ChatHelpers::Show> show,
  308. const Data::CreditsHistoryEntry &e) {
  309. if (e.extended.empty()) {
  310. return;
  311. }
  312. thumb->setCursor(style::cur_pointer);
  313. struct State {
  314. ~State() {
  315. if (item) {
  316. item->destroy();
  317. }
  318. }
  319. HistoryItem *item = nullptr;
  320. bool pressed = false;
  321. bool over = false;
  322. };
  323. const auto state = thumb->lifetime().make_state<State>();
  324. const auto session = &show->session();
  325. const auto owner = &session->data();
  326. const auto peerId = e.barePeerId
  327. ? PeerId(e.barePeerId)
  328. : session->userPeerId();
  329. const auto history = owner->history(session->user());
  330. state->item = history->makeMessage({
  331. .id = history->nextNonHistoryEntryId(),
  332. .flags = MessageFlag::HasFromId | MessageFlag::AdminLogEntry,
  333. .from = peerId,
  334. .date = base::unixtime::serialize(e.date),
  335. }, TextWithEntities(), MTP_messageMediaEmpty());
  336. auto fake = std::vector<std::unique_ptr<Data::Media>>();
  337. fake.reserve(e.extended.size());
  338. for (const auto &item : e.extended) {
  339. if (item.type == Data::CreditsHistoryMediaType::Photo) {
  340. fake.push_back(std::make_unique<Data::MediaPhoto>(
  341. state->item,
  342. owner->photo(item.id),
  343. false)); // spoiler
  344. } else {
  345. const auto document = owner->document(item.id);
  346. const auto item = state->item;
  347. using MediaFile = Data::MediaFile;
  348. using Args = MediaFile::Args;
  349. fake.push_back(std::make_unique<MediaFile>(item, document, Args{
  350. .skipPremiumEffect = true,
  351. }));
  352. }
  353. }
  354. state->item->overrideMedia(std::make_unique<Data::MediaInvoice>(
  355. state->item,
  356. Data::Invoice{
  357. .amount = uint64(e.credits.abs().whole()),
  358. .currency = Ui::kCreditsCurrency,
  359. .extendedMedia = std::move(fake),
  360. .isPaidMedia = true,
  361. }));
  362. const auto showMedia = [=] {
  363. const auto window = show->resolveWindow();
  364. if (!window) {
  365. return;
  366. } else if (const auto media = state->item->media()) {
  367. if (const auto invoice = media->invoice()) {
  368. if (!invoice->extendedMedia.empty()) {
  369. const auto first = invoice->extendedMedia[0].get();
  370. if (const auto photo = first->photo()) {
  371. window->openPhoto(photo, {
  372. .id = state->item->fullId(),
  373. });
  374. } else if (const auto document = first->document()) {
  375. window->openDocument(document, true, {
  376. .id = state->item->fullId(),
  377. });
  378. }
  379. }
  380. }
  381. }
  382. };
  383. thumb->events() | rpl::start_with_next([=](not_null<QEvent*> e) {
  384. if (e->type() == QEvent::MouseButtonPress) {
  385. const auto mouse = static_cast<QMouseEvent*>(e.get());
  386. if (mouse->button() == Qt::LeftButton) {
  387. state->over = true;
  388. state->pressed = true;
  389. }
  390. } else if (e->type() == QEvent::MouseButtonRelease
  391. && state->over
  392. && state->pressed) {
  393. showMedia();
  394. } else if (e->type() == QEvent::Enter) {
  395. state->over = true;
  396. } else if (e->type() == QEvent::Leave) {
  397. state->over = false;
  398. }
  399. }, thumb->lifetime());
  400. }
  401. } // namespace
  402. void AddMiniStars(
  403. not_null<Ui::VerticalLayout*> content,
  404. not_null<Ui::RpWidget*> widget,
  405. int photoSize,
  406. int boxWidth,
  407. float64 heightRatio) {
  408. using ColoredMiniStars = Ui::Premium::ColoredMiniStars;
  409. const auto stars = widget->lifetime().make_state<ColoredMiniStars>(
  410. widget,
  411. false,
  412. Ui::Premium::MiniStars::Type::BiStars);
  413. stars->setColorOverride(Ui::Premium::CreditsIconGradientStops());
  414. widget->resize(boxWidth - photoSize, photoSize * heightRatio);
  415. content->sizeValue(
  416. ) | rpl::start_with_next([=](const QSize &size) {
  417. widget->moveToLeft(photoSize / 2, 0);
  418. const auto starsRect = Rect(widget->size());
  419. stars->setPosition(starsRect.topLeft());
  420. stars->setSize(starsRect.size());
  421. widget->lower();
  422. }, widget->lifetime());
  423. widget->paintRequest(
  424. ) | rpl::start_with_next([=](const QRect &r) {
  425. auto p = QPainter(widget);
  426. p.fillRect(r, Qt::transparent);
  427. stars->paint(p);
  428. }, widget->lifetime());
  429. }
  430. SubscriptionRightLabel PaintSubscriptionRightLabelCallback(
  431. not_null<Main::Session*> session,
  432. const style::PeerListItem &st,
  433. int amount) {
  434. const auto text = std::make_shared<Ui::Text::String>();
  435. text->setMarkedText(
  436. st::semiboldTextStyle,
  437. TextWithEntities()
  438. .append(session->data().customEmojiManager().creditsEmoji())
  439. .append(QChar::Space)
  440. .append(Lang::FormatCountDecimal(amount)),
  441. kMarkupTextOptions,
  442. Core::TextContext({ .session = session }));
  443. const auto &font = text->style()->font;
  444. const auto &statusFont = st::contactsStatusFont;
  445. const auto status = tr::lng_group_invite_joined_right(tr::now);
  446. const auto rightSkip = st::boxRowPadding.right();
  447. const auto statusWidth = statusFont->width(status);
  448. const auto size = QSize(
  449. std::max(text->maxWidth(), statusWidth) + rightSkip,
  450. font->height + statusFont->height);
  451. const auto statusX = size.width() - statusWidth;
  452. auto draw = [=](QPainter &p, int x, int y, int h) {
  453. p.setPen(st.statusFg);
  454. p.setFont(statusFont);
  455. const auto skip = y + (h - size.height()) / 2;
  456. p.drawText(
  457. x + statusX,
  458. font->height + statusFont->ascent + skip,
  459. status);
  460. p.setPen(st.nameFg);
  461. const auto textWidth = text->maxWidth();
  462. text->draw(p, Ui::Text::PaintContext{
  463. .position = QPoint(x + size.width() - textWidth, skip),
  464. .outerWidth = textWidth,
  465. .availableWidth = textWidth,
  466. });
  467. };
  468. return { std::move(draw), size };
  469. }
  470. void FillCreditOptions(
  471. std::shared_ptr<Main::SessionShow> show,
  472. not_null<Ui::VerticalLayout*> container,
  473. not_null<PeerData*> peer,
  474. StarsAmount minimumCredits,
  475. Fn<void()> paid,
  476. rpl::producer<QString> subtitle,
  477. std::vector<Data::CreditTopupOption> preloadedTopupOptions) {
  478. const auto options = container->add(
  479. object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  480. container,
  481. object_ptr<Ui::VerticalLayout>(container)));
  482. const auto content = options->entity();
  483. Ui::AddSkip(content, st::settingsPremiumOptionsPadding.top());
  484. const auto singleStarWidth = Ui::GenerateStars(
  485. st::creditsTopupButton.height,
  486. 1).width() / style::DevicePixelRatio();
  487. const auto fill = [=](Data::CreditTopupOptions options) {
  488. while (content->count()) {
  489. delete content->widgetAt(0);
  490. }
  491. if (subtitle) {
  492. Ui::AddSubsectionTitle(content, std::move(subtitle));
  493. }
  494. const auto buttons = content->add(
  495. object_ptr<Ui::VerticalLayout>(content));
  496. const auto showMoreWrap = content->add(
  497. object_ptr<Ui::SlideWrap<Ui::SettingsButton>>(
  498. content,
  499. object_ptr<Ui::SettingsButton>(
  500. content,
  501. tr::lng_credits_more_options(),
  502. st::statisticsShowMoreButton)));
  503. const auto showMore = showMoreWrap->entity();
  504. showMore->setClickedCallback([=] {
  505. showMoreWrap->toggle(false, anim::type::instant);
  506. });
  507. Ui::AddToggleUpDownArrowToMoreButton(showMore);
  508. const auto &st = st::creditsTopupButton;
  509. const auto diffBetweenTextAndStar = st.padding.left()
  510. - st.iconLeft
  511. - int(singleStarWidth * 1.5);
  512. const auto buttonHeight = st.height + rect::m::sum::v(st.padding);
  513. const auto minCredits = (!options.empty()
  514. && (minimumCredits > StarsAmount(options.back().credits)))
  515. ? StarsAmount()
  516. : minimumCredits;
  517. for (auto i = 0; i < options.size(); i++) {
  518. const auto &option = options[i];
  519. if (StarsAmount(option.credits) < minCredits) {
  520. continue;
  521. }
  522. const auto button = [&] {
  523. auto owned = object_ptr<Ui::SettingsButton>(
  524. buttons,
  525. rpl::never<QString>(),
  526. st);
  527. if (!option.extended) {
  528. return buttons->add(std::move(owned));
  529. }
  530. const auto wrap = buttons->add(
  531. object_ptr<Ui::SlideWrap<Ui::SettingsButton>>(
  532. buttons,
  533. std::move(owned)));
  534. wrap->toggle(false, anim::type::instant);
  535. showMore->clicks() | rpl::start_with_next([=] {
  536. wrap->toggle(true, anim::type::normal);
  537. }, wrap->lifetime());
  538. return wrap->entity();
  539. }();
  540. const auto text = button->lifetime().make_state<Ui::Text::String>(
  541. st.style,
  542. tr::lng_credits_summary_options_credits(
  543. tr::now,
  544. lt_count_decimal,
  545. option.credits));
  546. const auto price = Ui::CreateChild<Ui::FlatLabel>(
  547. button,
  548. Ui::FillAmountAndCurrency(option.amount, option.currency),
  549. st::creditsTopupPrice);
  550. const auto inner = Ui::CreateChild<Ui::RpWidget>(button);
  551. const auto stars = Ui::GenerateStars(st.height, (i + 1));
  552. const auto textLeft = diffBetweenTextAndStar
  553. + stars.width() / style::DevicePixelRatio();
  554. inner->paintRequest(
  555. ) | rpl::start_with_next([=](const QRect &rect) {
  556. auto p = QPainter(inner);
  557. p.drawImage(0, 0, stars);
  558. p.setPen(st.textFg);
  559. text->draw(p, {
  560. .position = QPoint(textLeft, 0),
  561. .availableWidth = inner->width() - textLeft,
  562. .elisionLines = 1,
  563. });
  564. }, inner->lifetime());
  565. button->widthValue(
  566. ) | rpl::start_with_next([=](int width) {
  567. price->moveToRight(st.padding.right(), st.padding.top());
  568. inner->moveToLeft(st.iconLeft, st.padding.top());
  569. inner->resize(
  570. width - price->width() - st.padding.left(),
  571. buttonHeight);
  572. }, button->lifetime());
  573. button->setClickedCallback([=] {
  574. const auto invoice = Payments::InvoiceCredits{
  575. .session = &show->session(),
  576. .randomId = UniqueIdFromOption(option),
  577. .credits = option.credits,
  578. .product = option.product,
  579. .currency = option.currency,
  580. .amount = option.amount,
  581. .extended = option.extended,
  582. .giftPeerId = PeerId(option.giftBarePeerId),
  583. };
  584. const auto weak = Ui::MakeWeak(button);
  585. const auto done = [=](Payments::CheckoutResult result) {
  586. if (const auto strong = weak.data()) {
  587. strong->window()->setFocus();
  588. if (result == Payments::CheckoutResult::Paid) {
  589. if (const auto onstack = paid) {
  590. onstack();
  591. }
  592. }
  593. }
  594. };
  595. Payments::CheckoutProcess::Start(std::move(invoice), done);
  596. });
  597. Ui::ToggleChildrenVisibility(button, true);
  598. }
  599. // Footer.
  600. {
  601. auto text = tr::lng_credits_summary_options_about(
  602. lt_link,
  603. rpl::combine(
  604. tr::lng_credits_summary_options_about_link(),
  605. tr::lng_credits_summary_options_about_url()
  606. ) | rpl::map([](const QString &text, const QString &url) {
  607. return Ui::Text::Link(text, url);
  608. }),
  609. Ui::Text::RichLangValue);
  610. Ui::AddSkip(content);
  611. Ui::AddDividerText(content, std::move(text));
  612. }
  613. content->resizeToWidth(container->width());
  614. };
  615. using ApiOptions = Api::CreditsTopupOptions;
  616. const auto apiCredits = content->lifetime().make_state<ApiOptions>(peer);
  617. if (show->session().premiumPossible()) {
  618. if (preloadedTopupOptions.empty()) {
  619. apiCredits->request(
  620. ) | rpl::start_with_error_done([=](const QString &error) {
  621. show->showToast(error);
  622. }, [=] {
  623. fill(apiCredits->options());
  624. }, content->lifetime());
  625. } else {
  626. fill(std::move(preloadedTopupOptions));
  627. }
  628. }
  629. show->session().premiumPossibleValue(
  630. ) | rpl::start_with_next([=](bool premiumPossible) {
  631. if (!premiumPossible) {
  632. fill({});
  633. }
  634. }, content->lifetime());
  635. }
  636. not_null<Ui::RpWidget*> AddBalanceWidget(
  637. not_null<Ui::RpWidget*> parent,
  638. rpl::producer<StarsAmount> balanceValue,
  639. bool rightAlign,
  640. rpl::producer<float64> opacityValue) {
  641. struct State final {
  642. QImage star;
  643. float64 opacity = 1.0;
  644. Ui::Text::String label;
  645. Ui::Text::String count;
  646. };
  647. const auto balance = Ui::CreateChild<Balance>(parent);
  648. const auto state = balance->lifetime().make_state<State>();
  649. state->star = QImage(Ui::GenerateStars(st::creditsBalanceStarHeight, 1));
  650. const auto starSize = state->star.size() / style::DevicePixelRatio();
  651. state->label = Ui::Text::String(
  652. st::defaultTextStyle,
  653. tr::lng_credits_summary_balance(tr::now));
  654. state->count = Ui::Text::String(
  655. st::semiboldTextStyle,
  656. tr::lng_contacts_loading(tr::now));
  657. if (opacityValue) {
  658. std::move(opacityValue) | rpl::start_with_next([=](float64 value) {
  659. state->opacity = value;
  660. }, balance->lifetime());
  661. }
  662. const auto diffBetweenStarAndCount = state->count.style()->font->spacew;
  663. const auto resize = [=] {
  664. balance->resize(
  665. std::max(
  666. state->label.maxWidth(),
  667. state->count.maxWidth()
  668. + starSize.width()
  669. + diffBetweenStarAndCount),
  670. state->label.style()->font->height + starSize.height());
  671. };
  672. std::move(
  673. balanceValue
  674. ) | rpl::start_with_next([=](StarsAmount value) {
  675. state->count.setText(
  676. st::semiboldTextStyle,
  677. Lang::FormatStarsAmountToShort(value).string);
  678. balance->setBalance(value);
  679. resize();
  680. }, balance->lifetime());
  681. balance->paintRequest(
  682. ) | rpl::start_with_next([=] {
  683. auto p = QPainter(balance);
  684. p.setOpacity(state->opacity);
  685. p.setPen(st::boxTextFg);
  686. state->label.draw(p, {
  687. .position = QPoint(
  688. rightAlign ? (balance->width() - state->label.maxWidth()) : 0,
  689. 0),
  690. .availableWidth = balance->width(),
  691. });
  692. state->count.draw(p, {
  693. .position = QPoint(
  694. (rightAlign
  695. ? (balance->width() - state->count.maxWidth())
  696. : (starSize.width() + diffBetweenStarAndCount)),
  697. state->label.minHeight()
  698. + (starSize.height() - state->count.minHeight()) / 2),
  699. .availableWidth = balance->width(),
  700. });
  701. p.drawImage(
  702. (rightAlign
  703. ? (balance->width()
  704. - state->count.maxWidth()
  705. - starSize.width()
  706. - diffBetweenStarAndCount)
  707. : 0),
  708. state->label.minHeight(),
  709. state->star);
  710. }, balance->lifetime());
  711. return balance;
  712. }
  713. void BoostCreditsBox(
  714. not_null<Ui::GenericBox*> box,
  715. not_null<Window::SessionController*> controller,
  716. const Data::Boost &b) {
  717. box->setStyle(st::giveawayGiftCodeBox);
  718. box->setNoContentMargin(true);
  719. const auto content = box->verticalLayout();
  720. const auto session = &controller->session();
  721. Ui::AddSkip(content);
  722. {
  723. const auto &stUser = st::premiumGiftsUserpicButton;
  724. const auto widget = content->add(object_ptr<Ui::RpWidget>(content));
  725. AddMiniStars(content, widget, stUser.photoSize, st::boxWidth, 1.3);
  726. const auto svg = std::make_shared<QSvgRenderer>(
  727. Ui::Premium::ColorizedSvg(
  728. Ui::Premium::CreditsIconGradientStops()));
  729. widget->paintRequest() | rpl::start_with_next([=](const QRect &r) {
  730. auto p = QPainter(widget);
  731. svg->render(
  732. &p,
  733. QRectF(
  734. (widget->width() - stUser.photoSize) / 2.,
  735. (widget->height() - stUser.photoSize) / 2.,
  736. stUser.photoSize,
  737. stUser.photoSize));
  738. }, widget->lifetime());
  739. }
  740. content->add(
  741. object_ptr<Ui::CenterWrap<Ui::FlatLabel>>(
  742. content,
  743. object_ptr<Ui::FlatLabel>(
  744. content,
  745. tr::lng_gift_stars_title(
  746. lt_count,
  747. rpl::single(float64(b.credits))),
  748. st::boxTitle)));
  749. Ui::AddSkip(content);
  750. if (b.multiplier) {
  751. const auto &st = st::statisticsDetailsBottomCaptionStyle;
  752. const auto badge = content->add(object_ptr<Ui::RpWidget>(content));
  753. badge->resize(badge->width(), st.font->height * 1.5);
  754. const auto text = badge->lifetime().make_state<Ui::Text::String>(
  755. st::boxWidth
  756. - st::boxRowPadding.left()
  757. - st::boxRowPadding.right());
  758. auto textWithEntities = TextWithEntities();
  759. textWithEntities.append(
  760. Ui::Text::SingleCustomEmoji(
  761. session->data().customEmojiManager().registerInternalEmoji(
  762. st::boostsListMiniIcon,
  763. { st.font->descent * 2, st.font->descent / 2, 0, 0 },
  764. true)));
  765. textWithEntities.append(
  766. tr::lng_boosts_list_title(tr::now, lt_count, b.multiplier));
  767. text->setMarkedText(
  768. st,
  769. std::move(textWithEntities),
  770. kMarkupTextOptions,
  771. Core::TextContext({
  772. .session = session,
  773. .repaint = [=] { badge->update(); },
  774. }));
  775. badge->paintRequest(
  776. ) | rpl::start_with_next([=] {
  777. auto p = QPainter(badge);
  778. auto hq = PainterHighQualityEnabler(p);
  779. const auto radius = badge->height() / 2;
  780. const auto badgeWidth = text->maxWidth() + radius;
  781. p.setPen(Qt::NoPen);
  782. p.setBrush(st::premiumButtonBg2);
  783. p.drawRoundedRect(
  784. QRect(
  785. (badge->width() - badgeWidth) / 2,
  786. 0,
  787. badgeWidth,
  788. badge->height()),
  789. radius,
  790. radius);
  791. p.setPen(st::premiumButtonFg);
  792. p.setBrush(Qt::NoBrush);
  793. text->draw(p, Ui::Text::PaintContext{
  794. .position = QPoint(
  795. (badge->width() - text->maxWidth() - radius) / 2,
  796. (badge->height() - text->minHeight()) / 2),
  797. .outerWidth = badge->width(),
  798. .availableWidth = badge->width(),
  799. });
  800. }, badge->lifetime());
  801. Ui::AddSkip(content);
  802. }
  803. AddCreditsBoostTable(controller->uiShow(), content, {}, b);
  804. Ui::AddSkip(content);
  805. box->addRow(object_ptr<Ui::CenterWrap<>>(
  806. box,
  807. object_ptr<Ui::FlatLabel>(
  808. box,
  809. tr::lng_credits_box_out_about(
  810. lt_link,
  811. tr::lng_payments_terms_link(
  812. ) | Ui::Text::ToLink(
  813. tr::lng_credits_box_out_about_link(tr::now)),
  814. Ui::Text::WithEntities),
  815. st::creditsBoxAboutDivider)));
  816. Ui::AddSkip(content);
  817. const auto button = box->addButton(tr::lng_box_ok(), [=] {
  818. box->closeBox();
  819. });
  820. const auto buttonWidth = st::boxWidth
  821. - rect::m::sum::h(st::giveawayGiftCodeBox.buttonPadding);
  822. button->widthValue() | rpl::filter([=] {
  823. return (button->widthNoMargins() != buttonWidth);
  824. }) | rpl::start_with_next([=] {
  825. button->resizeToWidth(buttonWidth);
  826. }, button->lifetime());
  827. }
  828. void ProcessReceivedSubscriptions(
  829. QPointer<Ui::GenericBox> weak,
  830. not_null<Main::Session*> session) {
  831. const auto rebuilder = session->data().activeCreditsSubsRebuilder();
  832. if (const auto strong = weak.data()) {
  833. if (!rebuilder) {
  834. return strong->closeBox();
  835. }
  836. const auto api
  837. = strong->lifetime().make_state<Api::CreditsHistory>(
  838. session->user(),
  839. true,
  840. true);
  841. api->requestSubscriptions({}, [=](Data::CreditsStatusSlice first) {
  842. rebuilder->fire(std::move(first));
  843. if (const auto strong = weak.data()) {
  844. strong->closeBox();
  845. }
  846. });
  847. }
  848. }
  849. void FillUniqueGiftMenu(
  850. std::shared_ptr<ChatHelpers::Show> show,
  851. not_null<Ui::PopupMenu*> menu,
  852. const Data::CreditsHistoryEntry &e,
  853. SavedStarGiftMenuType type,
  854. CreditsEntryBoxStyleOverrides st) {
  855. const auto session = &show->session();
  856. const auto savedId = EntryToSavedStarGiftId(session, e);
  857. const auto giftChannel = savedId.chat();
  858. const auto canToggle = savedId
  859. && e.id.isEmpty()
  860. && (e.in || (giftChannel && giftChannel->canManageGifts()))
  861. && !e.giftTransferred
  862. && !e.giftRefunded;
  863. const auto unique = e.uniqueGift;
  864. if (unique
  865. && canToggle
  866. && e.savedToProfile
  867. && e.pinnedSavedGifts) {
  868. const auto pinned = e.pinnedSavedGifts;
  869. const auto ids = [session](
  870. const std::vector<Data::CreditsHistoryEntry> &pinned) {
  871. auto result = std::vector<Data::SavedStarGiftId>();
  872. result.reserve(pinned.size());
  873. for (const auto &entry : pinned) {
  874. result.push_back(EntryToSavedStarGiftId(session, entry));
  875. }
  876. return result;
  877. };
  878. if (e.giftPinned) {
  879. menu->addAction(tr::lng_context_unpin_from_top(tr::now), [=] {
  880. ToggleStarGiftPinned(show, savedId, ids(pinned()), false);
  881. }, st.unpin ? st.unpin : &st::menuIconUnpin);
  882. } else {
  883. menu->addAction(tr::lng_context_pin_to_top(tr::now), [=] {
  884. const auto list = pinned();
  885. const auto &appConfig = show->session().appConfig();
  886. const auto limit = appConfig.pinnedGiftsLimit();
  887. auto already = ids(list);
  888. if (list.size() >= limit) {
  889. Info::PeerGifts::SelectGiftToUnpin(show, list, [=](
  890. Data::SavedStarGiftId id) {
  891. auto copy = already;
  892. const auto i = ranges::find(copy, id);
  893. const auto replaced = (i != end(copy))
  894. ? list[i - begin(copy)].uniqueGift
  895. : nullptr;
  896. if (i != end(copy)) {
  897. copy.erase(i);
  898. }
  899. using GiftAction = Data::GiftUpdate::Action;
  900. show->session().data().notifyGiftUpdate({
  901. .id = id,
  902. .action = GiftAction::Unpin,
  903. });
  904. ToggleStarGiftPinned(
  905. show,
  906. savedId,
  907. already,
  908. true,
  909. unique,
  910. replaced);
  911. });
  912. } else {
  913. ToggleStarGiftPinned(
  914. show,
  915. savedId,
  916. already,
  917. true,
  918. unique);
  919. }
  920. }, st.pin ? st.pin : &st::menuIconPin);
  921. }
  922. }
  923. if (unique) {
  924. const auto local = u"nft/"_q + unique->slug;
  925. const auto url = show->session().createInternalLinkFull(local);
  926. menu->addAction(tr::lng_context_copy_link(tr::now), [=] {
  927. TextUtilities::SetClipboardText({ url });
  928. show->showToast(tr::lng_channel_public_link_copied(tr::now));
  929. }, st.link ? st.link : &st::menuIconLink);
  930. const auto shareBoxSt = st.shareBox;
  931. menu->addAction(tr::lng_chat_link_share(tr::now), [=] {
  932. FastShareLink(
  933. show,
  934. url,
  935. shareBoxSt ? *shareBoxSt : ShareBoxStyleOverrides());
  936. }, st.share ? st.share : &st::menuIconShare);
  937. }
  938. if (canToggle && type == SavedStarGiftMenuType::List) {
  939. if (e.savedToProfile) {
  940. menu->addAction(tr::lng_gift_menu_hide(tr::now), [=] {
  941. ToggleStarGiftSaved(show, savedId, false);
  942. }, st.hide ? st.hide : &st::menuIconStealth);
  943. } else {
  944. menu->addAction(tr::lng_gift_menu_show(tr::now), [=] {
  945. ToggleStarGiftSaved(show, savedId, true);
  946. }, st.show ? st.show : &st::menuIconShowInChat);
  947. }
  948. }
  949. if (!unique) {
  950. return;
  951. }
  952. const auto transfer = savedId
  953. && (savedId.isUser() ? e.in : savedId.chat()->canTransferGifts())
  954. && (unique->starsForTransfer >= 0);
  955. if (transfer) {
  956. menu->addAction(tr::lng_gift_transfer_button(tr::now), [=] {
  957. if (const auto window = show->resolveWindow()) {
  958. ShowTransferGiftBox(window, unique, savedId);
  959. }
  960. }, st.transfer ? st.transfer : &st::menuIconReplace);
  961. }
  962. const auto owner = show->session().data().peer(unique->ownerId);
  963. const auto wear = owner->isSelf()
  964. ? e.in
  965. : (owner->isChannel() && owner->asChannel()->canEditEmoji());
  966. if (wear) {
  967. const auto name = UniqueGiftName(*unique);
  968. const auto now = owner->emojiStatusId().collectible;
  969. if (now && unique->slug == now->slug) {
  970. menu->addAction(tr::lng_gift_transfer_take_off(tr::now), [=] {
  971. show->session().data().emojiStatuses().set(owner, {});
  972. }, st.takeoff ? st.takeoff : &st::menuIconNftTakeOff);
  973. } else {
  974. menu->addAction(tr::lng_gift_transfer_wear(tr::now), [=] {
  975. ShowUniqueGiftWearBox(show, owner, *unique, st.giftWearBox
  976. ? *st.giftWearBox
  977. : GiftWearBoxStyleOverride());
  978. }, st.wear ? st.wear : &st::menuIconNftWear);
  979. }
  980. }
  981. }
  982. GiftWearBoxStyleOverride DarkGiftWearBoxStyle() {
  983. return {
  984. .box = &st::darkUpgradeGiftBox,
  985. .title = &st::darkUpgradeGiftTitle,
  986. .subtitle = &st::darkUpgradeGiftSubtitle,
  987. .radiantIcon = &st::darkUpgradeGiftRadiant,
  988. .proofIcon = &st::darkUpgradeGiftProof,
  989. .infoTitle = &st::darkUpgradeGiftInfoTitle,
  990. .infoAbout = &st::darkUpgradeGiftInfoAbout,
  991. };
  992. }
  993. CreditsEntryBoxStyleOverrides DarkCreditsEntryBoxStyle() {
  994. return {
  995. .box = &st::darkGiftCodeBox,
  996. .menu = &st::mediaviewPopupMenu,
  997. .table = &st::darkGiftTable,
  998. .tableValueMultiline = &st::darkGiftTableValueMultiline,
  999. .tableValueMessage = &st::darkGiftTableMessage,
  1000. .link = &st::darkGiftLink,
  1001. .share = &st::darkGiftShare,
  1002. .transfer = &st::darkGiftTransfer,
  1003. .wear = &st::darkGiftNftWear,
  1004. .takeoff = &st::darkGiftNftTakeOff,
  1005. .show = &st::darkGiftShow,
  1006. .hide = &st::darkGiftHide,
  1007. .pin = &st::darkGiftPin,
  1008. .unpin = &st::darkGiftUnpin,
  1009. .shareBox = std::make_shared<ShareBoxStyleOverrides>(
  1010. DarkShareBoxStyle()),
  1011. .giftWearBox = std::make_shared<GiftWearBoxStyleOverride>(
  1012. DarkGiftWearBoxStyle()),
  1013. };
  1014. }
  1015. void GenericCreditsEntryBox(
  1016. not_null<Ui::GenericBox*> box,
  1017. std::shared_ptr<ChatHelpers::Show> show,
  1018. const Data::CreditsHistoryEntry &e,
  1019. const Data::SubscriptionEntry &s,
  1020. CreditsEntryBoxStyleOverrides st) {
  1021. const auto session = &show->session();
  1022. const auto selfPeerId = session->userPeerId().value;
  1023. const auto owner = &session->data();
  1024. const auto item = owner->message(
  1025. PeerId(e.barePeerId),
  1026. MsgId(e.bareMsgId));
  1027. const auto isStarGift = e.stargift || e.soldOutInfo;
  1028. const auto creditsHistoryStarGift = isStarGift && !e.id.isEmpty();
  1029. const auto sentStarGift = creditsHistoryStarGift && !e.in;
  1030. const auto convertedStarGift = creditsHistoryStarGift && e.converted;
  1031. const auto giftToSelf = isStarGift
  1032. && (e.barePeerId == selfPeerId)
  1033. && (e.in || e.bareGiftOwnerId == selfPeerId);
  1034. const auto giftChannel = (isStarGift && e.giftChannelSavedId)
  1035. ? session->data().peer(
  1036. PeerId(e.bareEntryOwnerId))->asChannel()
  1037. : nullptr;
  1038. const auto giftToChannel = (giftChannel != nullptr);
  1039. const auto giftToChannelCanManage = giftToChannel
  1040. && giftChannel->canManageGifts();
  1041. const auto giftToChannelCanTransfer = giftToChannel
  1042. && giftChannel->canTransferGifts();
  1043. const auto starGiftCanManage = isStarGift
  1044. && !creditsHistoryStarGift
  1045. && (e.in || giftToChannelCanManage);
  1046. const auto starGiftCanTransfer = isStarGift
  1047. && !creditsHistoryStarGift
  1048. && (e.in || giftToChannelCanTransfer);
  1049. const auto starGiftSender = (isStarGift && item)
  1050. ? item->history()->peer->asUser()
  1051. : (isStarGift && e.in)
  1052. ? owner->peer(PeerId(e.barePeerId))->asUser()
  1053. : (isStarGift && e.bareActorId)
  1054. ? owner->peer(PeerId(e.bareActorId)).get()
  1055. : nullptr;
  1056. const auto convertLast = base::unixtime::serialize(e.date)
  1057. + session->appConfig().stargiftConvertPeriodMax();
  1058. const auto timeLeft = int64(convertLast) - int64(base::unixtime::now());
  1059. const auto timeExceeded = (timeLeft <= 0);
  1060. const auto uniqueGift = e.uniqueGift.get();
  1061. const auto forConvert = starGiftCanTransfer
  1062. && e.starsConverted
  1063. && !e.converted
  1064. && starGiftSender;
  1065. const auto canConvert = forConvert && !timeExceeded;
  1066. if (auto savedId = EntryToSavedStarGiftId(session, e)) {
  1067. session->data().giftUpdates(
  1068. ) | rpl::start_with_next([=](const Data::GiftUpdate &update) {
  1069. if (update.id == savedId) {
  1070. box->closeBox();
  1071. }
  1072. }, box->lifetime());
  1073. }
  1074. box->setStyle(st.box ? *st.box : st::giveawayGiftCodeBox);
  1075. box->setWidth(st::boxWideWidth);
  1076. box->setNoContentMargin(true);
  1077. const auto content = box->verticalLayout();
  1078. if (!uniqueGift) {
  1079. Ui::AddSkip(content);
  1080. Ui::AddSkip(content);
  1081. Ui::AddSkip(content);
  1082. }
  1083. using Type = Data::CreditsHistoryEntry::PeerType;
  1084. const auto &stUser = st::boostReplaceUserpic;
  1085. const auto isPrize = e.bareGiveawayMsgId > 0;
  1086. const auto starGiftSticker = (isStarGift && e.bareGiftStickerId)
  1087. ? owner->document(e.bareGiftStickerId).get()
  1088. : nullptr;
  1089. const auto peer = isPrize
  1090. ? nullptr
  1091. : (s.barePeerId)
  1092. ? owner->peer(PeerId(s.barePeerId)).get()
  1093. : (e.peerType == Type::PremiumBot)
  1094. ? nullptr
  1095. : e.bareActorId
  1096. ? owner->peer(PeerId(e.bareActorId)).get()
  1097. : e.barePeerId
  1098. ? owner->peer(PeerId(e.barePeerId)).get()
  1099. : nullptr;
  1100. if (uniqueGift) {
  1101. box->setNoContentMargin(true);
  1102. AddUniqueGiftCover(content, rpl::single(*uniqueGift));
  1103. AddSkip(content, st::defaultVerticalListSkip * 2);
  1104. AddUniqueCloseButton(box, st, [=](not_null<Ui::PopupMenu*> menu) {
  1105. const auto type = SavedStarGiftMenuType::View;
  1106. FillUniqueGiftMenu(show, menu, e, type, st);
  1107. });
  1108. } else if (const auto callback = Ui::PaintPreviewCallback(session, e)) {
  1109. const auto thumb = content->add(object_ptr<Ui::CenterWrap<>>(
  1110. content,
  1111. GenericEntryPhoto(content, callback, stUser.photoSize)));
  1112. AddViewMediaHandler(thumb->entity(), show, e);
  1113. } else if (s.photoId || (e.photoId && !e.subscriptionUntil.isNull())) {
  1114. if (!(s.cancelled || s.expired || s.cancelledByBot)) {
  1115. const auto widget = Ui::CreateChild<Ui::RpWidget>(content);
  1116. const auto photoSize = stUser.photoSize;
  1117. AddMiniStars(content, widget, photoSize, st::boxWideWidth, 1.5);
  1118. }
  1119. const auto photoId = s.photoId ? s.photoId : e.photoId;
  1120. const auto callback = [=](Fn<void()> update) {
  1121. return Ui::GenerateCreditsPaintEntryCallback(
  1122. owner->photo(photoId),
  1123. std::move(update));
  1124. };
  1125. content->add(object_ptr<Ui::CenterWrap<>>(
  1126. content,
  1127. GenericEntryPhoto(content, callback, stUser.photoSize)));
  1128. } else if (peer && !e.gift && !e.premiumMonthsForStars) {
  1129. if (e.subscriptionUntil.isNull() && s.until.isNull()) {
  1130. content->add(object_ptr<Ui::CenterWrap<>>(
  1131. content,
  1132. object_ptr<Ui::UserpicButton>(content, peer, stUser)));
  1133. } else {
  1134. content->add(object_ptr<Ui::CenterWrap<>>(
  1135. content,
  1136. SubscriptionUserpic(content, peer, stUser.photoSize)));
  1137. }
  1138. } else if (e.gift || isPrize || e.premiumMonthsForStars) {
  1139. struct State final {
  1140. DocumentData *sticker = nullptr;
  1141. std::shared_ptr<Data::DocumentMedia> media;
  1142. std::unique_ptr<Lottie::SinglePlayer> lottie;
  1143. rpl::lifetime downloadLifetime;
  1144. };
  1145. Ui::AddSkip(content, isStarGift
  1146. ? st::creditsHistoryEntryStarGiftSpace
  1147. : st::creditsHistoryEntryGiftStickerSpace);
  1148. const auto icon = Ui::CreateChild<Ui::RpWidget>(content);
  1149. icon->resize(Size(isStarGift
  1150. ? st::creditsHistoryEntryStarGiftSize
  1151. : st::creditsHistoryEntryGiftStickerSize));
  1152. const auto state = icon->lifetime().make_state<State>();
  1153. auto &packs = session->giftBoxStickersPacks();
  1154. const auto document = starGiftSticker
  1155. ? starGiftSticker
  1156. : packs.lookup(e.premiumMonthsForStars
  1157. ? e.premiumMonthsForStars
  1158. : packs.monthsForStars(e.credits.whole()));
  1159. if (document && document->sticker()) {
  1160. state->sticker = document;
  1161. state->media = document->createMediaView();
  1162. state->media->thumbnailWanted(packs.origin());
  1163. state->media->automaticLoad(packs.origin(), nullptr);
  1164. rpl::single() | rpl::then(
  1165. session->downloaderTaskFinished()
  1166. ) | rpl::filter([=] {
  1167. return state->media->loaded();
  1168. }) | rpl::start_with_next([=] {
  1169. state->lottie = ChatHelpers::LottiePlayerFromDocument(
  1170. state->media.get(),
  1171. ChatHelpers::StickerLottieSize::MessageHistory,
  1172. icon->size(),
  1173. Lottie::Quality::High);
  1174. state->lottie->updates() | rpl::start_with_next([=] {
  1175. icon->update();
  1176. }, icon->lifetime());
  1177. state->downloadLifetime.destroy();
  1178. }, state->downloadLifetime);
  1179. }
  1180. icon->paintRequest(
  1181. ) | rpl::start_with_next([=] {
  1182. auto p = Painter(icon);
  1183. const auto &lottie = state->lottie;
  1184. const auto factor = style::DevicePixelRatio();
  1185. const auto request = Lottie::FrameRequest{
  1186. .box = icon->size() * factor,
  1187. };
  1188. const auto frame = (lottie && lottie->ready())
  1189. ? lottie->frameInfo(request)
  1190. : Lottie::Animation::FrameInfo();
  1191. if (!frame.image.isNull()) {
  1192. p.drawImage(
  1193. QRect(QPoint(), frame.image.size() / factor),
  1194. frame.image);
  1195. if (lottie->frameIndex() < lottie->framesCount() - 1) {
  1196. lottie->markFrameShown();
  1197. }
  1198. }
  1199. }, icon->lifetime());
  1200. content->sizeValue(
  1201. ) | rpl::start_with_next([=](const QSize &size) {
  1202. icon->move((size.width() - icon->width()) / 2, isStarGift
  1203. ? st::creditsHistoryEntryStarGiftSkip
  1204. : st::creditsHistoryEntryGiftStickerSkip);
  1205. }, icon->lifetime());
  1206. } else {
  1207. const auto widget = content->add(
  1208. object_ptr<Ui::CenterWrap<>>(
  1209. content,
  1210. object_ptr<Ui::RpWidget>(content)))->entity();
  1211. using Draw = Fn<void(Painter &, int, int, int, int)>;
  1212. const auto draw = widget->lifetime().make_state<Draw>(
  1213. Ui::GenerateCreditsPaintUserpicCallback(e));
  1214. widget->resize(Size(stUser.photoSize));
  1215. widget->paintRequest(
  1216. ) | rpl::start_with_next([=] {
  1217. auto p = Painter(widget);
  1218. (*draw)(p, 0, 0, stUser.photoSize, stUser.photoSize);
  1219. }, widget->lifetime());
  1220. }
  1221. if (!uniqueGift) {
  1222. Ui::AddSkip(content);
  1223. Ui::AddSkip(content);
  1224. box->addRow(object_ptr<Ui::CenterWrap<>>(
  1225. box,
  1226. object_ptr<Ui::FlatLabel>(
  1227. box,
  1228. rpl::single(!s.title.isEmpty()
  1229. ? s.title
  1230. : !s.until.isNull()
  1231. ? tr::lng_credits_box_subscription_title(tr::now)
  1232. : isPrize
  1233. ? tr::lng_credits_box_history_entry_giveaway_name(tr::now)
  1234. : (!e.subscriptionUntil.isNull() && e.title.isEmpty())
  1235. ? tr::lng_credits_box_history_entry_subscription(tr::now)
  1236. : e.paidMessagesCount
  1237. ? tr::lng_credits_paid_messages_fee(
  1238. tr::now,
  1239. lt_count,
  1240. e.paidMessagesCount)
  1241. : e.premiumMonthsForStars
  1242. ? tr::lng_premium_summary_title(tr::now)
  1243. : !e.title.isEmpty()
  1244. ? e.title
  1245. : e.starrefCommission
  1246. ? tr::lng_credits_commission(
  1247. tr::now,
  1248. lt_amount,
  1249. Info::BotStarRef::FormatCommission(e.starrefCommission))
  1250. : e.soldOutInfo
  1251. ? tr::lng_credits_box_history_entry_gift_unavailable(tr::now)
  1252. : sentStarGift
  1253. ? tr::lng_credits_box_history_entry_gift_sent(tr::now)
  1254. : convertedStarGift
  1255. ? tr::lng_credits_box_history_entry_gift_converted(tr::now)
  1256. : (isStarGift && !starGiftCanManage)
  1257. ? tr::lng_gift_link_label_gift(tr::now)
  1258. : giftToSelf
  1259. ? tr::lng_action_gift_self_subtitle(tr::now)
  1260. : e.gift
  1261. ? tr::lng_credits_box_history_entry_gift_name(tr::now)
  1262. : (peer && !e.reaction)
  1263. ? peer->name()
  1264. : Ui::GenerateEntryName(e).text),
  1265. st::creditsBoxAboutTitle)));
  1266. Ui::AddSkip(content);
  1267. }
  1268. if (!isStarGift || creditsHistoryStarGift || e.soldOutInfo) {
  1269. constexpr auto kMinus = QChar(0x2212);
  1270. auto &lifetime = content->lifetime();
  1271. const auto text = lifetime.make_state<Ui::Text::String>();
  1272. const auto roundedText = e.refunded
  1273. ? tr::lng_channel_earn_history_return(tr::now)
  1274. : e.pending
  1275. ? tr::lng_channel_earn_history_pending(tr::now)
  1276. : e.failed
  1277. ? tr::lng_channel_earn_history_failed(tr::now)
  1278. : QString();
  1279. const auto rounded = !roundedText.isEmpty()
  1280. ? lifetime.make_state<Ui::Text::String>(
  1281. st::defaultTextStyle,
  1282. roundedText)
  1283. : (Ui::Text::String*)(nullptr);
  1284. const auto amount = content->add(
  1285. object_ptr<Ui::FixedHeightWidget>(
  1286. content,
  1287. st::defaultTextStyle.font->height));
  1288. const auto context = Core::TextContext({
  1289. .session = session,
  1290. .repaint = [=] { amount->update(); },
  1291. });
  1292. if (e.soldOutInfo) {
  1293. text->setText(
  1294. st::defaultTextStyle,
  1295. tr::lng_credits_box_history_entry_gift_sold_out(tr::now));
  1296. } else if (s) {
  1297. text->setMarkedText(
  1298. st::defaultTextStyle,
  1299. tr::lng_credits_subscription_subtitle(
  1300. tr::now,
  1301. lt_emoji,
  1302. owner->customEmojiManager().creditsEmoji(),
  1303. lt_cost,
  1304. { QString::number(s.subscription.credits) },
  1305. Ui::Text::WithEntities),
  1306. kMarkupTextOptions,
  1307. context);
  1308. } else {
  1309. auto t = TextWithEntities()
  1310. .append((e.in && (creditsHistoryStarGift || !isStarGift))
  1311. ? u"+"_q
  1312. : (e.gift && !creditsHistoryStarGift)
  1313. ? QString()
  1314. : QString(kMinus))
  1315. .append(Lang::FormatStarsAmountDecimal(e.credits.abs()))
  1316. .append(QChar(' '))
  1317. .append(owner->customEmojiManager().creditsEmoji());
  1318. text->setMarkedText(
  1319. st::semiboldTextStyle,
  1320. std::move(t),
  1321. kMarkupTextOptions,
  1322. context);
  1323. }
  1324. const auto font = text->style()->font;
  1325. const auto roundedFont = st::defaultTextStyle.font;
  1326. const auto roundedSkip = roundedFont->spacew * 2;
  1327. const auto roundedWidth = rounded
  1328. ? roundedFont->width(roundedText)
  1329. + roundedSkip
  1330. + roundedFont->height
  1331. : 0;
  1332. const auto fullWidth = text->maxWidth() + roundedWidth;
  1333. amount->paintRequest(
  1334. ) | rpl::start_with_next([=] {
  1335. auto p = Painter(amount);
  1336. p.setPen(e.soldOutInfo
  1337. ? st::menuIconAttentionColor
  1338. : s
  1339. ? st::windowSubTextFg
  1340. : e.pending
  1341. ? st::creditsStroke
  1342. : (e.in || (isStarGift && !creditsHistoryStarGift))
  1343. ? st::boxTextFgGood
  1344. : (e.gift && !creditsHistoryStarGift)
  1345. ? st::windowBoldFg
  1346. : st::menuIconAttentionColor);
  1347. const auto x = (amount->width() - fullWidth) / 2;
  1348. text->draw(p, Ui::Text::PaintContext{
  1349. .position = QPoint(
  1350. x,
  1351. (amount->height() - font->height) / 2),
  1352. .outerWidth = amount->width(),
  1353. .availableWidth = amount->width(),
  1354. });
  1355. if (rounded) {
  1356. const auto roundedLeft = fullWidth
  1357. + x
  1358. - roundedWidth
  1359. + roundedSkip;
  1360. const auto pen = p.pen();
  1361. auto color = pen.color();
  1362. color.setAlphaF(color.alphaF() * 0.15);
  1363. p.setPen(Qt::NoPen);
  1364. p.setBrush(color);
  1365. {
  1366. auto hq = PainterHighQualityEnabler(p);
  1367. p.drawRoundedRect(
  1368. roundedLeft,
  1369. (amount->height() - roundedFont->height) / 2,
  1370. roundedWidth - roundedSkip,
  1371. roundedFont->height,
  1372. roundedFont->height / 2,
  1373. roundedFont->height / 2);
  1374. }
  1375. p.setPen(pen);
  1376. rounded->draw(p, Ui::Text::PaintContext{
  1377. .position = QPoint(
  1378. roundedLeft + roundedFont->height / 2,
  1379. (amount->height() - roundedFont->height) / 2),
  1380. .outerWidth = roundedWidth,
  1381. .availableWidth = roundedWidth,
  1382. });
  1383. }
  1384. }, amount->lifetime());
  1385. }
  1386. if (!isStarGift && !e.description.empty()) {
  1387. Ui::AddSkip(content);
  1388. box->addRow(object_ptr<Ui::CenterWrap<>>(
  1389. box,
  1390. object_ptr<Ui::FlatLabel>(
  1391. box,
  1392. rpl::single(e.description),
  1393. st::creditsBoxAbout)));
  1394. }
  1395. const auto arrow = Ui::Text::IconEmoji(&st::textMoreIconEmoji);
  1396. if (!uniqueGift && starGiftCanManage) {
  1397. Ui::AddSkip(content);
  1398. const auto about = box->addRow(
  1399. object_ptr<Ui::CenterWrap<Ui::FlatLabel>>(
  1400. box,
  1401. object_ptr<Ui::FlatLabel>(
  1402. box,
  1403. (e.giftRefunded
  1404. ? tr::lng_action_gift_refunded(
  1405. Ui::Text::RichLangValue)
  1406. : e.starsUpgradedBySender
  1407. ? tr::lng_action_gift_got_upgradable_text(
  1408. Ui::Text::RichLangValue)
  1409. : (e.starsToUpgrade
  1410. && giftToSelf
  1411. && !e.giftTransferred)
  1412. ? tr::lng_action_gift_self_about_unique(
  1413. Ui::Text::WithEntities)
  1414. : (e.starsToUpgrade
  1415. && giftToChannelCanManage
  1416. && !e.giftTransferred)
  1417. ? tr::lng_action_gift_channel_about_unique(
  1418. Ui::Text::WithEntities)
  1419. : ((canConvert || e.converted)
  1420. ? rpl::combine(
  1421. (canConvert
  1422. ? (giftToSelf
  1423. ? tr::lng_action_gift_self_about
  1424. : giftToChannelCanTransfer
  1425. ? tr::lng_action_gift_channel_about
  1426. : tr::lng_action_gift_got_stars_text)
  1427. : (giftToChannel
  1428. ? tr::lng_gift_channel_got
  1429. : tr::lng_gift_got_stars))(
  1430. lt_count,
  1431. rpl::single(e.starsConverted * 1.),
  1432. Ui::Text::RichLangValue),
  1433. tr::lng_paid_about_link()
  1434. ) | rpl::map([](
  1435. TextWithEntities text,
  1436. QString link) {
  1437. return text.append(' ').append(
  1438. Ui::Text::Link(link));
  1439. })
  1440. : (e.savedToProfile
  1441. ? (giftToChannel
  1442. ? tr::lng_action_gift_can_remove_channel
  1443. : tr::lng_action_gift_can_remove_text)
  1444. : (giftToChannel
  1445. ? tr::lng_action_gift_got_gift_channel
  1446. : tr::lng_action_gift_got_gift_text))(
  1447. Ui::Text::WithEntities))),
  1448. st::creditsBoxAbout)))->entity();
  1449. about->setClickHandlerFilter([=](const auto &...) {
  1450. Core::App().iv().openWithIvPreferred(
  1451. session,
  1452. tr::lng_paid_about_link_url(tr::now));
  1453. return false;
  1454. });
  1455. if (e.giftRefunded) {
  1456. about->setTextColorOverride(st::menuIconAttentionColor->c);
  1457. }
  1458. } else if (isStarGift) {
  1459. } else if (e.gift || isPrize) {
  1460. Ui::AddSkip(content);
  1461. auto link = tr::lng_credits_box_history_entry_gift_about_link(
  1462. lt_emoji,
  1463. rpl::single(arrow),
  1464. Ui::Text::RichLangValue
  1465. ) | rpl::map([](TextWithEntities text) {
  1466. return Ui::Text::Link(
  1467. std::move(text),
  1468. u"internal:stars_examples"_q);
  1469. });
  1470. box->addRow(object_ptr<Ui::CenterWrap<>>(
  1471. box,
  1472. Ui::CreateLabelWithCustomEmoji(
  1473. box,
  1474. (!e.in && peer)
  1475. ? tr::lng_credits_box_history_entry_gift_out_about(
  1476. lt_user,
  1477. rpl::single(TextWithEntities{ peer->shortName() }),
  1478. lt_link,
  1479. std::move(link),
  1480. Ui::Text::RichLangValue)
  1481. : tr::lng_credits_box_history_entry_gift_in_about(
  1482. lt_link,
  1483. std::move(link),
  1484. Ui::Text::RichLangValue),
  1485. Core::TextContext({ .session = session }),
  1486. st::creditsBoxAbout)));
  1487. } else if (e.paidMessagesCommission && e.barePeerId) {
  1488. Ui::AddSkip(content);
  1489. auto link = tr::lng_credits_paid_messages_fee_about_link(
  1490. lt_emoji,
  1491. rpl::single(arrow),
  1492. Ui::Text::RichLangValue
  1493. ) | rpl::map([id = e.barePeerId](TextWithEntities text) {
  1494. return Ui::Text::Link(
  1495. std::move(text),
  1496. u"internal:edit_paid_messages_fee/"_q + QString::number(id));
  1497. });
  1498. const auto percent = 100. - (e.paidMessagesCommission / 10.);
  1499. box->addRow(object_ptr<Ui::CenterWrap<>>(
  1500. box,
  1501. Ui::CreateLabelWithCustomEmoji(
  1502. box,
  1503. tr::lng_credits_paid_messages_fee_about(
  1504. lt_percent,
  1505. rpl::single(
  1506. Ui::Text::Bold(QString::number(percent) + '%')),
  1507. lt_link,
  1508. std::move(link),
  1509. Ui::Text::RichLangValue),
  1510. Core::TextContext({ .session = session }),
  1511. st::creditsBoxAbout)));
  1512. }
  1513. Ui::AddSkip(content);
  1514. Ui::AddSkip(content);
  1515. struct State final {
  1516. rpl::variable<bool> confirmButtonBusy;
  1517. rpl::variable<bool> convertButtonBusy;
  1518. };
  1519. const auto state = box->lifetime().make_state<State>();
  1520. const auto canToggle = starGiftCanManage
  1521. && !e.giftTransferred
  1522. && !e.giftRefunded;
  1523. const auto toggleVisibility = [=, weak = Ui::MakeWeak(box)](bool save) {
  1524. const auto showSection = !e.fromGiftsList;
  1525. const auto savedId = EntryToSavedStarGiftId(&show->session(), e);
  1526. const auto done = [=](bool ok) {
  1527. if (ok && showSection) {
  1528. if (const auto window = show->resolveWindow()) {
  1529. window->showSection(
  1530. std::make_shared<Info::Memento>(
  1531. window->session().user(),
  1532. Info::Section::Type::PeerGifts));
  1533. }
  1534. }
  1535. if (const auto strong = weak.data()) {
  1536. if (ok) {
  1537. strong->closeBox();
  1538. } else {
  1539. state->confirmButtonBusy = false;
  1540. }
  1541. }
  1542. };
  1543. ToggleStarGiftSaved(show, savedId, save, done);
  1544. };
  1545. const auto upgradeGuard = std::make_shared<bool>();
  1546. const auto upgrade = [=] {
  1547. const auto window = show->resolveWindow();
  1548. if (!window || *upgradeGuard) {
  1549. return;
  1550. }
  1551. *upgradeGuard = true;
  1552. const auto savedId = EntryToSavedStarGiftId(&window->session(), e);
  1553. const auto openWhenDone = giftToChannel
  1554. ? window->session().data().peer(PeerId(e.bareGiftOwnerId)).get()
  1555. : starGiftSender;
  1556. using namespace Ui;
  1557. ShowStarGiftUpgradeBox({
  1558. .controller = window,
  1559. .stargiftId = e.stargiftId,
  1560. .ready = [=](bool) { *upgradeGuard = false; },
  1561. .peer = openWhenDone,
  1562. .savedId = savedId,
  1563. .cost = e.starsUpgradedBySender ? 0 : e.starsToUpgrade,
  1564. .canAddSender = !giftToSelf && !e.anonymous,
  1565. .canAddComment = (!giftToSelf
  1566. && !e.anonymous
  1567. && e.hasGiftComment),
  1568. .canAddMyComment = (giftToSelf && e.hasGiftComment),
  1569. .addDetailsDefault = (giftToSelf
  1570. || (e.starsUpgradedBySender && !e.anonymous)),
  1571. });
  1572. };
  1573. const auto canUpgrade = e.stargiftId
  1574. && e.canUpgradeGift
  1575. && (e.in || giftToSelf || giftToChannelCanManage)
  1576. && !e.uniqueGift;
  1577. const auto canUpgradeFree = canUpgrade && (e.starsUpgradedBySender > 0);
  1578. if (isStarGift && e.id.isEmpty()) {
  1579. const auto convert = [=, weak = Ui::MakeWeak(box)] {
  1580. const auto stars = e.starsConverted;
  1581. const auto days = canConvert ? ((timeLeft + 86399) / 86400) : 0;
  1582. auto text = giftToChannelCanManage
  1583. ? tr::lng_gift_convert_sure_confirm_channel(
  1584. lt_count,
  1585. rpl::single(stars * 1.),
  1586. lt_channel,
  1587. rpl::single(Ui::Text::Bold(giftChannel->name())),
  1588. Ui::Text::RichLangValue)
  1589. : tr::lng_gift_convert_sure_confirm(
  1590. lt_count,
  1591. rpl::single(stars * 1.),
  1592. lt_user,
  1593. rpl::single(Ui::Text::Bold(starGiftSender->shortName())),
  1594. Ui::Text::RichLangValue);
  1595. ConfirmConvertStarGift(show, std::move(text), stars, days, [=] {
  1596. if (state->convertButtonBusy.current()
  1597. || state->confirmButtonBusy.current()) {
  1598. return;
  1599. }
  1600. state->convertButtonBusy = true;
  1601. const auto savedId = EntryToSavedStarGiftId(
  1602. &show->session(),
  1603. e);
  1604. if (stars) {
  1605. const auto done = [=](bool ok) {
  1606. if (ok) {
  1607. using GiftAction = Data::GiftUpdate::Action;
  1608. show->session().data().notifyGiftUpdate({
  1609. .id = savedId,
  1610. .action = GiftAction::Convert,
  1611. });
  1612. }
  1613. if (const auto strong = weak.data()) {
  1614. if (ok) {
  1615. strong->closeBox();
  1616. } else {
  1617. state->convertButtonBusy = false;
  1618. }
  1619. }
  1620. };
  1621. ConvertStarGift(show, savedId, stars, done);
  1622. }
  1623. });
  1624. };
  1625. AddStarGiftTable(
  1626. show,
  1627. content,
  1628. st,
  1629. e,
  1630. canConvert ? convert : Fn<void()>(),
  1631. canUpgrade ? upgrade : Fn<void()>());
  1632. } else {
  1633. AddCreditsHistoryEntryTable(show, content, st, e);
  1634. AddSubscriptionEntryTable(show, content, st, s);
  1635. }
  1636. Ui::AddSkip(content);
  1637. if (!isStarGift) {
  1638. box->addRow(object_ptr<Ui::CenterWrap<>>(
  1639. box,
  1640. object_ptr<Ui::FlatLabel>(
  1641. box,
  1642. tr::lng_credits_box_out_about(
  1643. lt_link,
  1644. tr::lng_payments_terms_link(
  1645. ) | Ui::Text::ToLink(
  1646. tr::lng_credits_box_out_about_link(tr::now)),
  1647. Ui::Text::WithEntities),
  1648. st::creditsBoxAboutDivider)));
  1649. } else if (starGiftCanManage) {
  1650. const auto hiddenPhrase = giftToChannelCanManage
  1651. ? tr::lng_gift_hidden_hint_channel
  1652. : uniqueGift
  1653. ? tr::lng_gift_hidden_unique
  1654. : tr::lng_gift_hidden_hint;
  1655. const auto visiblePhrase = giftToChannelCanManage
  1656. ? tr::lng_gift_visible_hint_channel
  1657. : tr::lng_gift_visible_hint;
  1658. auto withHide = rpl::combine(
  1659. visiblePhrase(),
  1660. tr::lng_gift_visible_hide()
  1661. ) | rpl::map([](QString &&hint, QString &&hide) {
  1662. return TextWithEntities{ std::move(hint) }.append(' ').append(
  1663. Ui::Text::Link(std::move(hide)));
  1664. });
  1665. auto text = !e.savedToProfile
  1666. ? hiddenPhrase(Ui::Text::WithEntities)
  1667. : canToggle
  1668. ? std::move(withHide)
  1669. : visiblePhrase(Ui::Text::WithEntities);
  1670. if (e.anonymous && e.barePeerId) {
  1671. text = rpl::combine(
  1672. std::move(text),
  1673. (giftToChannelCanManage
  1674. ? tr::lng_gift_anonymous_hint_channel
  1675. : tr::lng_gift_anonymous_hint)()
  1676. ) | rpl::map([](TextWithEntities &&a, QString &&b) {
  1677. return a.append("\n\n").append(b);
  1678. });
  1679. }
  1680. const auto label = box->addRow(
  1681. object_ptr<Ui::FlatLabel>(
  1682. box,
  1683. std::move(text),
  1684. st::creditsBoxAboutDivider));
  1685. label->setClickHandlerFilter([=](const auto &...) {
  1686. toggleVisibility(!e.savedToProfile);
  1687. return false;
  1688. });
  1689. } else if (uniqueGift && !uniqueGift->ownerAddress.isEmpty()) {
  1690. const auto label = box->addRow(
  1691. object_ptr<Ui::FlatLabel>(
  1692. box,
  1693. tr::lng_gift_in_blockchain(
  1694. lt_link,
  1695. tr::lng_gift_in_blockchain_link() | Ui::Text::ToLink(),
  1696. Ui::Text::WithEntities),
  1697. st::creditsBoxAboutDivider));
  1698. label->setClickHandlerFilter([=](const auto &...) {
  1699. UrlClickHandler::Open(
  1700. TonAddressUrl(session, uniqueGift->ownerAddress));
  1701. return false;
  1702. });
  1703. }
  1704. if (s) {
  1705. const auto user = peer ? peer->asUser() : nullptr;
  1706. const auto bot = (user && !user->isSelf()) ? user : nullptr;
  1707. const auto toCancel = !s.expired && !s.cancelled && !s.cancelledByBot;
  1708. if (toCancel) {
  1709. Ui::AddSkip(content);
  1710. }
  1711. Ui::AddSkip(content);
  1712. auto label = object_ptr<Ui::FlatLabel>(
  1713. box,
  1714. ((s.cancelledByBot && bot)
  1715. ? tr::lng_credits_subscription_off_by_bot_about(
  1716. lt_bot,
  1717. rpl::single(bot->name()))
  1718. : toCancel
  1719. ? tr::lng_credits_subscription_on_button()
  1720. : s.cancelled
  1721. ? tr::lng_credits_subscription_off_about()
  1722. : tr::lng_credits_subscription_on_about(
  1723. lt_date,
  1724. rpl::single(langDayOfMonthFull(s.until.date())))),
  1725. st::creditsBoxAboutDivider);
  1726. if (toCancel) {
  1727. label->setClickHandlerFilter([=](
  1728. const auto &,
  1729. Qt::MouseButton button) {
  1730. if (button != Qt::LeftButton) {
  1731. return false;
  1732. }
  1733. const auto done = [=, weak = Ui::MakeWeak(box)] {
  1734. ProcessReceivedSubscriptions(weak, session);
  1735. };
  1736. const auto fail = [=, s = box->uiShow()](const QString &e) {
  1737. s->showToast(e);
  1738. };
  1739. Api::EditCreditsSubscription(session, s.id, true, done, fail);
  1740. return true;
  1741. });
  1742. label->setMarkedText(
  1743. Ui::Text::Link(
  1744. tr::lng_credits_subscription_on_button(tr::now),
  1745. u"internal:"_q));
  1746. } else if (s.cancelled || s.cancelledByBot) {
  1747. label->setTextColorOverride(st::menuIconAttentionColor->c);
  1748. }
  1749. box->addRow(
  1750. object_ptr<Ui::CenterWrap<>>(box, std::move(label)));
  1751. }
  1752. Ui::AddSkip(content);
  1753. if (e.peerType == Data::CreditsHistoryEntry::PeerType::PremiumBot) {
  1754. const auto widget = Ui::CreateChild<Ui::RpWidget>(content);
  1755. AddMiniStars(content, widget, stUser.photoSize, st::boxWideWidth, 2);
  1756. }
  1757. const auto rejoinByApi = base::unixtime::serialize(s.until)
  1758. > base::unixtime::now();
  1759. const auto rejoinByInvite = !s.inviteHash.isEmpty();
  1760. const auto rejoinBySlug = !s.slug.isEmpty();
  1761. const auto toRenew = (s.cancelled || s.expired)
  1762. && (rejoinByApi || rejoinByInvite)
  1763. && !s.cancelledByBot;
  1764. const auto toRejoin = (s.cancelled || s.expired)
  1765. && rejoinBySlug
  1766. && !s.cancelledByBot;
  1767. auto confirmText = rpl::conditional(
  1768. state->confirmButtonBusy.value(),
  1769. rpl::single(QString()),
  1770. (toRenew
  1771. ? tr::lng_credits_subscription_off_button()
  1772. : toRejoin
  1773. ? tr::lng_credits_subscription_off_rejoin_button()
  1774. : canUpgradeFree
  1775. ? tr::lng_gift_upgrade_free()
  1776. : (canToggle && !e.savedToProfile)
  1777. ? (e.giftChannelSavedId
  1778. ? tr::lng_gift_show_on_channel
  1779. : tr::lng_gift_show_on_page)()
  1780. : tr::lng_box_ok()));
  1781. const auto send = [=, weak = Ui::MakeWeak(box)] {
  1782. if (toRejoin) {
  1783. if (const auto window = show->resolveWindow()) {
  1784. const auto finish = [=](Payments::CheckoutResult&&) {
  1785. ProcessReceivedSubscriptions(weak, session);
  1786. };
  1787. Payments::CheckoutProcess::Start(
  1788. &window->session(),
  1789. s.slug,
  1790. [](auto) {},
  1791. Payments::ProcessNonPanelPaymentFormFactory(
  1792. window,
  1793. finish));
  1794. }
  1795. } else if (toRenew && s.expired) {
  1796. if (const auto window = show->resolveWindow()) {
  1797. Api::CheckChatInvite(window, s.inviteHash, nullptr, [=] {
  1798. ProcessReceivedSubscriptions(weak, session);
  1799. });
  1800. }
  1801. } else {
  1802. const auto done = [=] {
  1803. ProcessReceivedSubscriptions(weak, session);
  1804. };
  1805. const auto fail = [=, show = box->uiShow()](const QString &e) {
  1806. if (const auto strong = weak.data()) {
  1807. state->confirmButtonBusy = false;
  1808. }
  1809. show->showToast(e);
  1810. };
  1811. Api::EditCreditsSubscription(session, s.id, false, done, fail);
  1812. }
  1813. };
  1814. const auto willBusy = toRejoin || (peer && toRenew);
  1815. if (willBusy) {
  1816. const auto close = Ui::CreateChild<Ui::IconButton>(
  1817. content,
  1818. st::boxTitleClose);
  1819. close->setClickedCallback([=] { box->closeBox(); });
  1820. content->widthValue() | rpl::start_with_next([=](int) {
  1821. close->moveToRight(0, 0);
  1822. }, content->lifetime());
  1823. }
  1824. const auto button = box->addButton(std::move(confirmText), [=] {
  1825. if (state->confirmButtonBusy.current()
  1826. || state->convertButtonBusy.current()) {
  1827. return;
  1828. }
  1829. if (willBusy) {
  1830. state->confirmButtonBusy = true;
  1831. send();
  1832. } else if (canUpgradeFree) {
  1833. upgrade();
  1834. } else if (canToggle && !e.savedToProfile) {
  1835. toggleVisibility(true);
  1836. } else {
  1837. box->closeBox();
  1838. }
  1839. });
  1840. {
  1841. using namespace Info::Statistics;
  1842. const auto loadingAnimation = InfiniteRadialAnimationWidget(
  1843. button,
  1844. button->height() / 2);
  1845. AddChildToWidgetCenter(button, loadingAnimation);
  1846. loadingAnimation->showOn(state->confirmButtonBusy.value());
  1847. }
  1848. const auto buttonWidth = st::boxWideWidth
  1849. - rect::m::sum::h(st::giveawayGiftCodeBox.buttonPadding);
  1850. button->widthValue() | rpl::filter([=] {
  1851. return (button->widthNoMargins() != buttonWidth);
  1852. }) | rpl::start_with_next([=] {
  1853. button->resizeToWidth(buttonWidth);
  1854. }, button->lifetime());
  1855. }
  1856. void ReceiptCreditsBox(
  1857. not_null<Ui::GenericBox*> box,
  1858. not_null<Window::SessionController*> controller,
  1859. const Data::CreditsHistoryEntry &e,
  1860. const Data::SubscriptionEntry &s) {
  1861. GenericCreditsEntryBox(box, controller->uiShow(), e, s);
  1862. }
  1863. void GiftedCreditsBox(
  1864. not_null<Ui::GenericBox*> box,
  1865. not_null<Window::SessionController*> controller,
  1866. not_null<PeerData*> from,
  1867. not_null<PeerData*> to,
  1868. int count,
  1869. TimeId date) {
  1870. const auto received = to->isSelf();
  1871. const auto anonymous = from->isServiceUser();
  1872. const auto peer = received ? from : to;
  1873. using PeerType = Data::CreditsHistoryEntry::PeerType;
  1874. Settings::ReceiptCreditsBox(box, controller, {
  1875. .id = QString(),
  1876. .title = (received
  1877. ? tr::lng_credits_box_history_entry_gift_name
  1878. : tr::lng_credits_box_history_entry_gift_sent)(tr::now),
  1879. .date = base::unixtime::parse(date),
  1880. .credits = StarsAmount(count),
  1881. .bareMsgId = uint64(),
  1882. .barePeerId = (anonymous ? uint64() : peer->id.value),
  1883. .peerType = (anonymous ? PeerType::Fragment : PeerType::Peer),
  1884. .in = received,
  1885. .gift = true,
  1886. }, {});
  1887. }
  1888. void CreditsPrizeBox(
  1889. not_null<Ui::GenericBox*> box,
  1890. not_null<Window::SessionController*> controller,
  1891. const Data::GiftCode &data,
  1892. TimeId date) {
  1893. using Type = Data::CreditsHistoryEntry::PeerType;
  1894. Settings::ReceiptCreditsBox(
  1895. box,
  1896. controller,
  1897. Data::CreditsHistoryEntry{
  1898. .id = data.slug,
  1899. .title = QString(),
  1900. .description = TextWithEntities(),
  1901. .date = base::unixtime::parse(date),
  1902. .credits = StarsAmount(data.count),
  1903. .barePeerId = data.channel
  1904. ? data.channel->id.value
  1905. : 0,
  1906. .bareGiveawayMsgId = uint64(data.giveawayMsgId.bare),
  1907. .peerType = Type::Peer,
  1908. .in = true,
  1909. },
  1910. Data::SubscriptionEntry());
  1911. }
  1912. void GlobalStarGiftBox(
  1913. not_null<Ui::GenericBox*> box,
  1914. std::shared_ptr<ChatHelpers::Show> show,
  1915. const Data::StarGift &data,
  1916. CreditsEntryBoxStyleOverrides st) {
  1917. const auto ownerId = data.unique ? data.unique->ownerId.value : 0;
  1918. Settings::GenericCreditsEntryBox(
  1919. box,
  1920. show,
  1921. Data::CreditsHistoryEntry{
  1922. .credits = StarsAmount(data.stars),
  1923. .bareGiftStickerId = data.document->id,
  1924. .bareGiftOwnerId = ownerId,
  1925. .stargiftId = data.id,
  1926. .uniqueGift = data.unique,
  1927. .peerType = Data::CreditsHistoryEntry::PeerType::Peer,
  1928. .limitedCount = data.limitedCount,
  1929. .limitedLeft = data.limitedLeft,
  1930. .stargift = true,
  1931. .fromGiftSlug = true,
  1932. .in = (ownerId == show->session().userPeerId().value),
  1933. .gift = true,
  1934. },
  1935. Data::SubscriptionEntry(),
  1936. st);
  1937. }
  1938. Data::CreditsHistoryEntry SavedStarGiftEntry(
  1939. not_null<PeerData*> owner,
  1940. const Data::SavedStarGift &data) {
  1941. const auto chatGiftPeer = data.manageId.chat();
  1942. return {
  1943. .description = data.message,
  1944. .date = base::unixtime::parse(data.date),
  1945. .credits = StarsAmount(data.info.stars),
  1946. .bareMsgId = uint64(data.manageId.userMessageId().bare),
  1947. .barePeerId = data.fromId.value,
  1948. .bareGiftStickerId = data.info.document->id,
  1949. .bareGiftOwnerId = owner->id.value,
  1950. .bareActorId = data.fromId.value,
  1951. .bareEntryOwnerId = chatGiftPeer ? chatGiftPeer->id.value : 0,
  1952. .giftChannelSavedId = data.manageId.chatSavedId(),
  1953. .stargiftId = data.info.id,
  1954. .uniqueGift = data.info.unique,
  1955. .peerType = Data::CreditsHistoryEntry::PeerType::Peer,
  1956. .limitedCount = data.info.limitedCount,
  1957. .limitedLeft = data.info.limitedLeft,
  1958. .starsConverted = int(data.starsConverted),
  1959. .starsToUpgrade = int(data.info.starsToUpgrade),
  1960. .starsUpgradedBySender = int(data.starsUpgradedBySender),
  1961. .converted = false,
  1962. .anonymous = data.anonymous,
  1963. .stargift = true,
  1964. .giftPinned = data.pinned,
  1965. .savedToProfile = !data.hidden,
  1966. .fromGiftsList = true,
  1967. .canUpgradeGift = data.upgradable,
  1968. .in = data.mine,
  1969. .gift = true,
  1970. };
  1971. }
  1972. Data::SavedStarGiftId EntryToSavedStarGiftId(
  1973. not_null<Main::Session*> session,
  1974. const Data::CreditsHistoryEntry &entry) {
  1975. return !entry.stargift
  1976. ? Data::SavedStarGiftId()
  1977. : (entry.bareEntryOwnerId && entry.giftChannelSavedId)
  1978. ? Data::SavedStarGiftId::Chat(
  1979. session->data().peer(PeerId(entry.bareEntryOwnerId)),
  1980. entry.giftChannelSavedId)
  1981. : Data::SavedStarGiftId::User(MsgId(entry.bareMsgId));
  1982. }
  1983. void SavedStarGiftBox(
  1984. not_null<Ui::GenericBox*> box,
  1985. not_null<Window::SessionController*> controller,
  1986. not_null<PeerData*> owner,
  1987. const Data::SavedStarGift &data,
  1988. Fn<std::vector<Data::CreditsHistoryEntry>()> pinned) {
  1989. auto entry = SavedStarGiftEntry(owner, data);
  1990. entry.pinnedSavedGifts = std::move(pinned);
  1991. Settings::ReceiptCreditsBox(
  1992. box,
  1993. controller,
  1994. std::move(entry),
  1995. Data::SubscriptionEntry());
  1996. }
  1997. void FillSavedStarGiftMenu(
  1998. std::shared_ptr<ChatHelpers::Show> show,
  1999. not_null<Ui::PopupMenu*> menu,
  2000. const Data::CreditsHistoryEntry &e,
  2001. SavedStarGiftMenuType type,
  2002. CreditsEntryBoxStyleOverrides st) {
  2003. FillUniqueGiftMenu(show, menu, e, type, st);
  2004. }
  2005. void StarGiftViewBox(
  2006. not_null<Ui::GenericBox*> box,
  2007. not_null<Window::SessionController*> controller,
  2008. const Data::GiftCode &data,
  2009. not_null<HistoryItem*> item) {
  2010. const auto peer = item->history()->peer;
  2011. const auto toChannel = peer->isServiceUser() && data.channel;
  2012. const auto incoming = !toChannel
  2013. && (data.upgrade ? item->out() : !item->out());
  2014. const auto fromId = incoming ? peer->id : peer->session().userPeerId();
  2015. const auto toId = incoming ? peer->session().userPeerId() : peer->id;
  2016. const auto entry = Data::CreditsHistoryEntry{
  2017. .id = data.slug,
  2018. .description = data.message,
  2019. .date = base::unixtime::parse(item->date()),
  2020. .credits = StarsAmount(data.count),
  2021. .bareMsgId = uint64(item->id.bare),
  2022. .barePeerId = fromId.value,
  2023. .bareGiftStickerId = data.document ? data.document->id : 0,
  2024. .bareGiftOwnerId = (data.unique
  2025. ? data.unique->ownerId.value
  2026. : toId.value),
  2027. .bareActorId = (toChannel ? data.channelFrom->id.value : 0),
  2028. .bareEntryOwnerId = (toChannel ? data.channel->id.value : 0),
  2029. .giftChannelSavedId = data.channelSavedId,
  2030. .stargiftId = data.stargiftId,
  2031. .uniqueGift = data.unique,
  2032. .peerType = Data::CreditsHistoryEntry::PeerType::Peer,
  2033. .limitedCount = data.limitedCount,
  2034. .limitedLeft = data.limitedLeft,
  2035. .starsConverted = data.starsConverted,
  2036. .starsToUpgrade = data.starsToUpgrade,
  2037. .starsUpgradedBySender = data.starsUpgradedBySender,
  2038. .converted = data.converted,
  2039. .anonymous = data.anonymous,
  2040. .stargift = true,
  2041. .giftTransferred = data.transferred,
  2042. .giftRefunded = data.refunded,
  2043. .savedToProfile = data.saved,
  2044. .canUpgradeGift = data.upgradable,
  2045. .hasGiftComment = !data.message.empty(),
  2046. .in = incoming,
  2047. .gift = true,
  2048. };
  2049. Settings::ReceiptCreditsBox(
  2050. box,
  2051. controller,
  2052. entry,
  2053. Data::SubscriptionEntry());
  2054. }
  2055. void ShowRefundInfoBox(
  2056. not_null<Window::SessionController*> controller,
  2057. FullMsgId refundItemId) {
  2058. const auto owner = &controller->session().data();
  2059. const auto item = owner->message(refundItemId);
  2060. const auto refund = item
  2061. ? item->Get<HistoryServicePaymentRefund>()
  2062. : nullptr;
  2063. if (!refund) {
  2064. return;
  2065. }
  2066. Assert(refund->peer != nullptr);
  2067. auto info = Data::CreditsHistoryEntry();
  2068. info.id = refund->transactionId;
  2069. info.date = base::unixtime::parse(item->date());
  2070. info.credits = StarsAmount(refund->amount);
  2071. info.barePeerId = refund->peer->id.value;
  2072. info.peerType = Data::CreditsHistoryEntry::PeerType::Peer;
  2073. info.refunded = true;
  2074. info.in = true;
  2075. controller->show(Box(
  2076. ::Settings::ReceiptCreditsBox,
  2077. controller,
  2078. info,
  2079. Data::SubscriptionEntry{}));
  2080. }
  2081. object_ptr<Ui::RpWidget> GenericEntryPhoto(
  2082. not_null<Ui::RpWidget*> parent,
  2083. Fn<Fn<void(Painter &, int, int, int, int)>(Fn<void()>)> callback,
  2084. int photoSize) {
  2085. auto owned = object_ptr<Ui::RpWidget>(parent);
  2086. const auto widget = owned.data();
  2087. widget->resize(Size(photoSize));
  2088. const auto draw = callback(
  2089. crl::guard(widget, [=] { widget->update(); }));
  2090. widget->paintRequest(
  2091. ) | rpl::start_with_next([=] {
  2092. auto p = Painter(widget);
  2093. draw(p, 0, 0, photoSize, photoSize);
  2094. }, widget->lifetime());
  2095. return owned;
  2096. }
  2097. object_ptr<Ui::RpWidget> HistoryEntryPhoto(
  2098. not_null<Ui::RpWidget*> parent,
  2099. not_null<PhotoData*> photo,
  2100. int photoSize) {
  2101. return GenericEntryPhoto(
  2102. parent,
  2103. [=](Fn<void()> update) {
  2104. return Ui::GenerateCreditsPaintEntryCallback(photo, update);
  2105. },
  2106. photoSize);
  2107. }
  2108. object_ptr<Ui::RpWidget> PaidMediaThumbnail(
  2109. not_null<Ui::RpWidget*> parent,
  2110. not_null<PhotoData*> photo,
  2111. PhotoData *second,
  2112. int totalCount,
  2113. int photoSize) {
  2114. return GenericEntryPhoto(
  2115. parent,
  2116. [=](Fn<void()> update) {
  2117. return Ui::GeneratePaidMediaPaintCallback(
  2118. photo,
  2119. second,
  2120. totalCount,
  2121. update);
  2122. },
  2123. photoSize);
  2124. }
  2125. object_ptr<Ui::RpWidget> SubscriptionUserpic(
  2126. not_null<Ui::RpWidget*> parent,
  2127. not_null<PeerData*> peer,
  2128. int photoSize) {
  2129. auto widget = object_ptr<Ui::RpWidget>(parent);
  2130. const auto raw = widget.data();
  2131. widget->resize(photoSize, photoSize);
  2132. const auto userpicMedia = Ui::MakeUserpicThumbnail(peer, false);
  2133. userpicMedia->subscribeToUpdates([=] { raw->update(); });
  2134. const auto creditsIconSize = photoSize / 3;
  2135. const auto creditsIconCallback =
  2136. Ui::PaintOutlinedColoredCreditsIconCallback(
  2137. creditsIconSize,
  2138. 1.5);
  2139. widget->paintRequest() | rpl::start_with_next([=] {
  2140. auto p = QPainter(raw);
  2141. p.fillRect(Rect(Size(photoSize)), Qt::transparent);
  2142. auto image = userpicMedia->image(photoSize);
  2143. {
  2144. auto q = QPainter(&image);
  2145. q.translate(photoSize, photoSize);
  2146. q.translate(-creditsIconSize, -creditsIconSize);
  2147. creditsIconCallback(q);
  2148. }
  2149. p.drawImage(0, 0, image);
  2150. }, widget->lifetime());
  2151. return widget;
  2152. }
  2153. void SmallBalanceBox(
  2154. not_null<Ui::GenericBox*> box,
  2155. std::shared_ptr<Main::SessionShow> show,
  2156. uint64 wholeCredits,
  2157. SmallBalanceSource source,
  2158. Fn<void()> paid) {
  2159. Expects(show->session().credits().loaded());
  2160. auto credits = StarsAmount(wholeCredits);
  2161. box->setWidth(st::boxWideWidth);
  2162. box->addButton(tr::lng_close(), [=] { box->closeBox(); });
  2163. const auto done = [=] {
  2164. box->closeBox();
  2165. paid();
  2166. };
  2167. const auto owner = &show->session().data();
  2168. const auto name = v::match(source, [&](SmallBalanceBot value) {
  2169. return value.botId
  2170. ? owner->peer(peerFromUser(value.botId))->name()
  2171. : QString();
  2172. }, [&](SmallBalanceReaction value) {
  2173. return owner->peer(peerFromChannel(value.channelId))->name();
  2174. }, [](SmallBalanceSubscription value) {
  2175. return value.name;
  2176. }, [](SmallBalanceDeepLink value) {
  2177. return QString();
  2178. }, [&](SmallBalanceStarGift value) {
  2179. return owner->peer(value.recipientId)->shortName();
  2180. }, [&](SmallBalanceForMessage value) {
  2181. return value.recipientId
  2182. ? owner->peer(value.recipientId)->shortName()
  2183. : QString();
  2184. });
  2185. auto needed = show->session().credits().balanceValue(
  2186. ) | rpl::map([=](StarsAmount balance) {
  2187. return (balance < credits) ? (credits - balance) : StarsAmount();
  2188. });
  2189. const auto content = [&]() -> Ui::Premium::TopBarAbstract* {
  2190. return box->setPinnedToTopContent(object_ptr<Ui::Premium::TopBar>(
  2191. box,
  2192. st::creditsLowBalancePremiumCover,
  2193. Ui::Premium::TopBarDescriptor{
  2194. .title = tr::lng_credits_small_balance_title(
  2195. lt_count,
  2196. rpl::duplicate(
  2197. needed
  2198. ) | rpl::filter(
  2199. rpl::mappers::_1 > StarsAmount(0)
  2200. ) | rpl::map([](StarsAmount amount) {
  2201. return amount.value();
  2202. })),
  2203. .about = (v::is<SmallBalanceSubscription>(source)
  2204. ? tr::lng_credits_small_balance_subscribe(
  2205. lt_channel,
  2206. rpl::single(Ui::Text::Bold(name)),
  2207. Ui::Text::RichLangValue)
  2208. : v::is<SmallBalanceReaction>(source)
  2209. ? tr::lng_credits_small_balance_reaction(
  2210. lt_channel,
  2211. rpl::single(Ui::Text::Bold(name)),
  2212. Ui::Text::RichLangValue)
  2213. : v::is<SmallBalanceDeepLink>(source)
  2214. ? DeepLinkBalanceAbout(
  2215. v::get<SmallBalanceDeepLink>(source).purpose)
  2216. : v::is<SmallBalanceStarGift>(source)
  2217. ? tr::lng_credits_small_balance_star_gift(
  2218. lt_user,
  2219. rpl::single(Ui::Text::Bold(name)),
  2220. Ui::Text::RichLangValue)
  2221. : v::is<SmallBalanceForMessage>(source)
  2222. ? (name.isEmpty()
  2223. ? tr::lng_credits_small_balance_for_messages(
  2224. Ui::Text::RichLangValue)
  2225. : tr::lng_credits_small_balance_for_message(
  2226. lt_user,
  2227. rpl::single(Ui::Text::Bold(name)),
  2228. Ui::Text::RichLangValue))
  2229. : name.isEmpty()
  2230. ? tr::lng_credits_small_balance_fallback(
  2231. Ui::Text::RichLangValue)
  2232. : tr::lng_credits_small_balance_about(
  2233. lt_bot,
  2234. rpl::single(TextWithEntities{ name }),
  2235. Ui::Text::RichLangValue)),
  2236. .light = true,
  2237. .gradientStops = Ui::Premium::CreditsIconGradientStops(),
  2238. }));
  2239. }();
  2240. FillCreditOptions(
  2241. show,
  2242. box->verticalLayout(),
  2243. show->session().user(),
  2244. credits - show->session().credits().balance(),
  2245. [=] { show->session().credits().load(true); },
  2246. tr::lng_credits_summary_options_subtitle(),
  2247. {});
  2248. content->setMaximumHeight(st::creditsLowBalancePremiumCoverHeight);
  2249. content->setMinimumHeight(st::infoLayerTopBarHeight);
  2250. content->resize(content->width(), content->maximumHeight());
  2251. content->additionalHeight(
  2252. ) | rpl::start_with_next([=](int additionalHeight) {
  2253. const auto wasMax = (content->height() == content->maximumHeight());
  2254. content->setMaximumHeight(st::creditsLowBalancePremiumCoverHeight
  2255. + additionalHeight);
  2256. if (wasMax) {
  2257. content->resize(content->width(), content->maximumHeight());
  2258. }
  2259. }, content->lifetime());
  2260. {
  2261. const auto balance = AddBalanceWidget(
  2262. content,
  2263. show->session().credits().balanceValue(),
  2264. true);
  2265. show->session().credits().load(true);
  2266. rpl::combine(
  2267. balance->sizeValue(),
  2268. content->sizeValue()
  2269. ) | rpl::start_with_next([=](const QSize &, const QSize &) {
  2270. balance->moveToRight(
  2271. st::creditsHistoryRightSkip * 2,
  2272. st::creditsHistoryRightSkip);
  2273. balance->update();
  2274. }, balance->lifetime());
  2275. }
  2276. std::move(
  2277. needed
  2278. ) | rpl::filter(
  2279. !rpl::mappers::_1
  2280. ) | rpl::start_with_next(done, content->lifetime());
  2281. }
  2282. void AddWithdrawalWidget(
  2283. not_null<Ui::VerticalLayout*> container,
  2284. not_null<Window::SessionController*> controller,
  2285. not_null<PeerData*> peer,
  2286. rpl::producer<QString> secondButtonUrl,
  2287. rpl::producer<StarsAmount> availableBalanceValue,
  2288. rpl::producer<QDateTime> dateValue,
  2289. bool withdrawalEnabled,
  2290. rpl::producer<QString> usdValue) {
  2291. Ui::AddSkip(container);
  2292. const auto labels = container->add(
  2293. object_ptr<Ui::CenterWrap<Ui::RpWidget>>(
  2294. container,
  2295. object_ptr<Ui::RpWidget>(container)))->entity();
  2296. const auto majorLabel = Ui::CreateChild<Ui::FlatLabel>(
  2297. labels,
  2298. rpl::duplicate(
  2299. availableBalanceValue
  2300. ) | rpl::map([](StarsAmount v) {
  2301. return Lang::FormatStarsAmountDecimal(v);
  2302. }),
  2303. st::channelEarnBalanceMajorLabel);
  2304. const auto icon = Ui::CreateSingleStarWidget(
  2305. labels,
  2306. majorLabel->height());
  2307. majorLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
  2308. majorLabel->sizeValue(
  2309. ) | rpl::start_with_next([=](const QSize &majorSize) {
  2310. const auto skip = st::channelEarnBalanceMinorLabelSkip;
  2311. labels->resize(
  2312. majorSize.width() + icon->width() + skip,
  2313. majorSize.height());
  2314. majorLabel->moveToLeft(icon->width() + skip, 0);
  2315. }, labels->lifetime());
  2316. Ui::ToggleChildrenVisibility(labels, true);
  2317. Ui::AddSkip(container);
  2318. container->add(
  2319. object_ptr<Ui::CenterWrap<>>(
  2320. container,
  2321. object_ptr<Ui::FlatLabel>(
  2322. container,
  2323. std::move(usdValue),
  2324. st::channelEarnOverviewSubMinorLabel)));
  2325. Ui::AddSkip(container);
  2326. const auto withdrawalWrap = container->add(
  2327. object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  2328. container,
  2329. object_ptr<Ui::VerticalLayout>(container)));
  2330. const auto input = Ui::AddInputFieldForCredits(
  2331. withdrawalWrap->entity(),
  2332. rpl::duplicate(availableBalanceValue));
  2333. Ui::AddSkip(withdrawalWrap->entity());
  2334. Ui::AddSkip(withdrawalWrap->entity());
  2335. const auto &stButton = st::defaultActiveButton;
  2336. const auto buttonsContainer = withdrawalWrap->entity()->add(
  2337. Ui::CreateSkipWidget(withdrawalWrap->entity(), stButton.height),
  2338. st::boxRowPadding);
  2339. withdrawalWrap->toggle(withdrawalEnabled, anim::type::instant);
  2340. const auto button = Ui::CreateChild<Ui::RoundButton>(
  2341. buttonsContainer,
  2342. rpl::never<QString>(),
  2343. stButton);
  2344. const auto buttonCredits = Ui::CreateChild<Ui::RoundButton>(
  2345. buttonsContainer,
  2346. tr::lng_bot_earn_balance_button_buy_ads(),
  2347. stButton);
  2348. buttonCredits->setTextTransform(
  2349. Ui::RoundButton::TextTransform::NoTransform);
  2350. Ui::ToggleChildrenVisibility(buttonsContainer, true);
  2351. rpl::combine(
  2352. std::move(secondButtonUrl),
  2353. buttonsContainer->sizeValue()
  2354. ) | rpl::start_with_next([=](const QString &url, const QSize &size) {
  2355. if (url.isEmpty()) {
  2356. button->resize(size.width(), size.height());
  2357. buttonCredits->resize(0, 0);
  2358. } else {
  2359. const auto w = size.width() - st::boxRowPadding.left() / 2;
  2360. button->resize(w / 2, size.height());
  2361. buttonCredits->resize(w / 2, size.height());
  2362. buttonCredits->moveToRight(0, 0);
  2363. buttonCredits->setClickedCallback([=] {
  2364. UrlClickHandler::Open(url);
  2365. });
  2366. }
  2367. }, buttonsContainer->lifetime());
  2368. auto lockedValue = rpl::duplicate(
  2369. dateValue
  2370. ) | rpl::map([](const QDateTime &dt) { return !dt.isNull(); });
  2371. rpl::duplicate(
  2372. lockedValue
  2373. ) | rpl::start_with_next([=](bool v) {
  2374. button->setAttribute(Qt::WA_TransparentForMouseEvents, v);
  2375. }, button->lifetime());
  2376. const auto session = &controller->session();
  2377. const auto label = Ui::CreateChild<Ui::FlatLabel>(
  2378. button,
  2379. tr::lng_channel_earn_balance_button(tr::now),
  2380. st::channelEarnSemiboldLabel);
  2381. const auto processInputChange = [&] {
  2382. const auto buttonEmoji = Ui::Text::SingleCustomEmoji(
  2383. session->data().customEmojiManager().registerInternalEmoji(
  2384. st::settingsPremiumIconStar,
  2385. { 0, -st::moderateBoxExpandInnerSkip, 0, 0 },
  2386. true));
  2387. using Balance = rpl::variable<StarsAmount>;
  2388. const auto currentBalance = input->lifetime().make_state<Balance>(
  2389. rpl::duplicate(availableBalanceValue));
  2390. const auto process = [=] {
  2391. const auto amount = input->getLastText().toDouble();
  2392. if (amount >= currentBalance->current().value()) {
  2393. label->setText(
  2394. tr::lng_bot_earn_balance_button_all(tr::now));
  2395. } else {
  2396. label->setMarkedText(
  2397. tr::lng_bot_earn_balance_button(
  2398. tr::now,
  2399. lt_count,
  2400. amount,
  2401. lt_emoji,
  2402. buttonEmoji,
  2403. Ui::Text::RichLangValue),
  2404. Core::TextContext({ .session = session }));
  2405. }
  2406. };
  2407. QObject::connect(input, &Ui::MaskedInputField::changed, process);
  2408. process();
  2409. return process;
  2410. }();
  2411. label->setTextColorOverride(stButton.textFg->c);
  2412. label->setAttribute(Qt::WA_TransparentForMouseEvents);
  2413. rpl::combine(
  2414. rpl::duplicate(lockedValue),
  2415. button->sizeValue(),
  2416. label->sizeValue()
  2417. ) | rpl::start_with_next([=](bool v, const QSize &b, const QSize &l) {
  2418. label->moveToLeft(
  2419. (b.width() - l.width()) / 2,
  2420. (v ? -10 : 1) * (b.height() - l.height()) / 2);
  2421. }, label->lifetime());
  2422. const auto lockedColor = anim::with_alpha(stButton.textFg->c, .5);
  2423. const auto lockedLabel = Ui::CreateChild<Ui::RpWidget>(button);
  2424. lockedLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
  2425. struct LockedState final {
  2426. Ui::Text::String text;
  2427. bool locked = false;
  2428. bool dateIsNull = false;
  2429. rpl::lifetime dateUpdateLifetime;
  2430. };
  2431. const auto state = lockedLabel->lifetime().make_state<LockedState>();
  2432. rpl::combine(
  2433. rpl::duplicate(lockedValue),
  2434. button->sizeValue()
  2435. ) | rpl::start_with_next([=](bool locked, const QSize &s) {
  2436. state->locked = locked;
  2437. lockedLabel->resize(s);
  2438. }, lockedLabel->lifetime());
  2439. lockedLabel->paintRequest() | rpl::start_with_next([=] {
  2440. auto p = QPainter(lockedLabel);
  2441. p.setPen(state->locked ? QPen(lockedColor) : stButton.textFg->p);
  2442. if (state->dateIsNull && state->locked) {
  2443. p.setFont(st::channelEarnSemiboldLabel.style.font);
  2444. p.drawText(
  2445. lockedLabel->rect(),
  2446. style::al_center,
  2447. tr::lng_bot_earn_balance_button_locked(tr::now));
  2448. return;
  2449. }
  2450. state->text.draw(p, {
  2451. .position = QPoint(
  2452. 0,
  2453. (lockedLabel->height() - state->text.minHeight()) / 2),
  2454. .outerWidth = lockedLabel->width(),
  2455. .availableWidth = lockedLabel->width(),
  2456. .align = style::al_center,
  2457. });
  2458. }, lockedLabel->lifetime());
  2459. std::move(
  2460. dateValue
  2461. ) | rpl::start_with_next([=](const QDateTime &dt) {
  2462. state->dateUpdateLifetime.destroy();
  2463. state->dateIsNull = dt.isNull();
  2464. if (dt.isNull()) {
  2465. return;
  2466. }
  2467. constexpr auto kDateUpdateInterval = crl::time(250);
  2468. const auto was = base::unixtime::serialize(dt);
  2469. const auto context = Core::TextContext({
  2470. .session = session,
  2471. .repaint = [=] { lockedLabel->update(); },
  2472. });
  2473. const auto emoji = Ui::Text::SingleCustomEmoji(
  2474. session->data().customEmojiManager().registerInternalEmoji(
  2475. st::chatSimilarLockedIcon,
  2476. st::botEarnButtonLockMargins,
  2477. true));
  2478. rpl::single(
  2479. rpl::empty
  2480. ) | rpl::then(
  2481. base::timer_each(kDateUpdateInterval)
  2482. ) | rpl::start_with_next([=] {
  2483. const auto secondsDifference = std::max(
  2484. was - base::unixtime::now() - 1,
  2485. 0);
  2486. const auto hours = secondsDifference / 3600;
  2487. const auto minutes = (secondsDifference % 3600) / 60;
  2488. const auto seconds = secondsDifference % 60;
  2489. constexpr auto kZero = QChar('0');
  2490. const auto formatted = (hours > 0)
  2491. ? (u"%1:%2:%3"_q)
  2492. .arg(hours, 2, 10, kZero)
  2493. .arg(minutes, 2, 10, kZero)
  2494. .arg(seconds, 2, 10, kZero)
  2495. : (u"%1:%2"_q)
  2496. .arg(minutes, 2, 10, kZero)
  2497. .arg(seconds, 2, 10, kZero);
  2498. state->text.setMarkedText(
  2499. st::botEarnLockedButtonLabel.style,
  2500. TextWithEntities()
  2501. .append(tr::lng_bot_earn_balance_button_locked(tr::now))
  2502. .append('\n')
  2503. .append(emoji)
  2504. .append(formatted),
  2505. kMarkupTextOptions,
  2506. context);
  2507. lockedLabel->update();
  2508. }, state->dateUpdateLifetime);
  2509. }, lockedLabel->lifetime());
  2510. Api::HandleWithdrawalButton(
  2511. Api::RewardReceiver{
  2512. .creditsReceiver = peer,
  2513. .creditsAmount = [=, show = controller->uiShow()] {
  2514. const auto amount = input->getLastText().toULongLong();
  2515. const auto min = float64(WithdrawalMin(session));
  2516. if (amount < min) {
  2517. auto text = tr::lng_bot_earn_credits_out_minimal(
  2518. tr::now,
  2519. lt_link,
  2520. Ui::Text::Link(
  2521. tr::lng_bot_earn_credits_out_minimal_link(
  2522. tr::now,
  2523. lt_count,
  2524. min),
  2525. u"internal:"_q),
  2526. Ui::Text::RichLangValue);
  2527. show->showToast(Ui::Toast::Config{
  2528. .text = std::move(text),
  2529. .filter = [=](const auto ...) {
  2530. input->setText(QString::number(min));
  2531. processInputChange();
  2532. return true;
  2533. },
  2534. });
  2535. return 0ULL;
  2536. }
  2537. return amount;
  2538. },
  2539. },
  2540. button,
  2541. controller->uiShow());
  2542. Ui::ToggleChildrenVisibility(button, true);
  2543. Ui::AddSkip(container);
  2544. Ui::AddSkip(container);
  2545. const auto arrow = Ui::Text::IconEmoji(&st::textMoreIconEmoji);
  2546. auto about = Ui::CreateLabelWithCustomEmoji(
  2547. container,
  2548. tr::lng_bot_earn_learn_credits_out_about(
  2549. lt_link,
  2550. tr::lng_channel_earn_about_link(
  2551. lt_emoji,
  2552. rpl::single(arrow),
  2553. Ui::Text::RichLangValue
  2554. ) | rpl::map([](TextWithEntities text) {
  2555. return Ui::Text::Link(
  2556. std::move(text),
  2557. tr::lng_bot_earn_balance_about_url(tr::now));
  2558. }),
  2559. Ui::Text::RichLangValue),
  2560. Core::TextContext({ .session = session }),
  2561. st::boxDividerLabel);
  2562. Ui::AddSkip(container);
  2563. container->add(object_ptr<Ui::DividerLabel>(
  2564. container,
  2565. std::move(about),
  2566. st::defaultBoxDividerLabelPadding,
  2567. RectPart::Top | RectPart::Bottom));
  2568. Ui::AddSkip(container);
  2569. }
  2570. void MaybeRequestBalanceIncrease(
  2571. std::shared_ptr<Main::SessionShow> show,
  2572. uint64 credits,
  2573. SmallBalanceSource source,
  2574. Fn<void(SmallBalanceResult)> done) {
  2575. struct State {
  2576. rpl::lifetime lifetime;
  2577. bool success = false;
  2578. };
  2579. const auto state = std::make_shared<State>();
  2580. const auto session = &show->session();
  2581. session->credits().load();
  2582. session->credits().loadedValue(
  2583. ) | rpl::filter(rpl::mappers::_1) | rpl::start_with_next([=] {
  2584. state->lifetime.destroy();
  2585. const auto balance = session->credits().balance();
  2586. if (StarsAmount(credits) <= balance) {
  2587. if (const auto onstack = done) {
  2588. onstack(SmallBalanceResult::Already);
  2589. }
  2590. } else if (show->session().premiumPossible()) {
  2591. const auto success = [=] {
  2592. state->success = true;
  2593. if (const auto onstack = done) {
  2594. onstack(SmallBalanceResult::Success);
  2595. }
  2596. };
  2597. const auto box = show->show(Box(
  2598. Settings::SmallBalanceBox,
  2599. show,
  2600. credits,
  2601. source,
  2602. success));
  2603. box->boxClosing() | rpl::start_with_next([=] {
  2604. crl::on_main([=] {
  2605. if (!state->success) {
  2606. if (const auto onstack = done) {
  2607. onstack(SmallBalanceResult::Cancelled);
  2608. }
  2609. }
  2610. });
  2611. }, box->lifetime());
  2612. } else {
  2613. show->showToast(
  2614. tr::lng_credits_purchase_blocked(tr::now));
  2615. if (const auto onstack = done) {
  2616. onstack(SmallBalanceResult::Blocked);
  2617. }
  2618. }
  2619. }, state->lifetime);
  2620. }
  2621. } // namespace Settings