window_peer_menu.cpp 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323
  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 "window/window_peer_menu.h"
  8. #include "base/call_delayed.h"
  9. #include "menu/menu_check_item.h"
  10. #include "boxes/share_box.h"
  11. #include "boxes/star_gift_box.h"
  12. #include "chat_helpers/compose/compose_show.h"
  13. #include "chat_helpers/message_field.h"
  14. #include "chat_helpers/share_message_phrase_factory.h"
  15. #include "ui/controls/userpic_button.h"
  16. #include "ui/wrap/slide_wrap.h"
  17. #include "ui/widgets/fields/input_field.h"
  18. #include "api/api_chat_participants.h"
  19. #include "lang/lang_keys.h"
  20. #include "ui/boxes/confirm_box.h"
  21. #include "base/random.h"
  22. #include "base/options.h"
  23. #include "base/unixtime.h"
  24. #include "base/qt/qt_key_modifiers.h"
  25. #include "boxes/delete_messages_box.h"
  26. #include "boxes/max_invite_box.h"
  27. #include "boxes/moderate_messages_box.h"
  28. #include "boxes/choose_filter_box.h"
  29. #include "boxes/create_poll_box.h"
  30. #include "boxes/pin_messages_box.h"
  31. #include "boxes/premium_limits_box.h"
  32. #include "boxes/report_messages_box.h"
  33. #include "boxes/peers/add_bot_to_chat_box.h"
  34. #include "boxes/peers/add_participants_box.h"
  35. #include "boxes/peers/edit_forum_topic_box.h"
  36. #include "boxes/peers/edit_contact_box.h"
  37. #include "calls/calls_instance.h"
  38. #include "inline_bots/bot_attach_web_view.h" // InlineBots::PeerType.
  39. #include "ui/toast/toast.h"
  40. #include "ui/text/format_values.h"
  41. #include "ui/text/text_utilities.h"
  42. #include "ui/widgets/chat_filters_tabs_strip.h"
  43. #include "ui/widgets/labels.h"
  44. #include "ui/widgets/checkbox.h"
  45. #include "ui/widgets/popup_menu.h"
  46. #include "ui/widgets/menu/menu_add_action_callback_factory.h"
  47. #include "ui/layers/generic_box.h"
  48. #include "ui/delayed_activation.h"
  49. #include "ui/vertical_list.h"
  50. #include "ui/ui_utility.h"
  51. #include "main/main_session.h"
  52. #include "main/main_session_settings.h"
  53. #include "menu/menu_mute.h"
  54. #include "menu/menu_ttl_validator.h"
  55. #include "apiwrap.h"
  56. #include "mainwidget.h"
  57. #include "api/api_blocked_peers.h"
  58. #include "api/api_chat_filters.h"
  59. #include "api/api_polls.h"
  60. #include "api/api_updates.h"
  61. #include "mtproto/mtproto_config.h"
  62. #include "history/history.h"
  63. #include "history/history_item_helpers.h" // GetErrorForSending.
  64. #include "history/view/history_view_context_menu.h"
  65. #include "window/window_separate_id.h"
  66. #include "window/window_session_controller.h"
  67. #include "window/window_controller.h"
  68. #include "settings/settings_advanced.h"
  69. #include "support/support_helper.h"
  70. #include "info/info_controller.h"
  71. #include "info/info_memento.h"
  72. #include "info/channel_statistics/boosts/info_boosts_widget.h"
  73. #include "info/channel_statistics/earn/info_channel_earn_widget.h"
  74. #include "info/profile/info_profile_cover.h"
  75. #include "info/profile/info_profile_values.h"
  76. #include "info/statistics/info_statistics_widget.h"
  77. #include "info/stories/info_stories_widget.h"
  78. #include "data/components/scheduled_messages.h"
  79. #include "data/notify/data_notify_settings.h"
  80. #include "data/data_changes.h"
  81. #include "data/data_session.h"
  82. #include "data/data_folder.h"
  83. #include "data/data_poll.h"
  84. #include "data/data_channel.h"
  85. #include "data/data_chat.h"
  86. #include "data/data_forum.h"
  87. #include "data/data_forum_topic.h"
  88. #include "data/data_user.h"
  89. #include "data/data_saved_sublist.h"
  90. #include "data/data_histories.h"
  91. #include "data/data_chat_filters.h"
  92. #include "dialogs/dialogs_key.h"
  93. #include "core/application.h"
  94. #include "export/export_manager.h"
  95. #include "boxes/peers/edit_peer_info_box.h"
  96. #include "styles/style_chat.h"
  97. #include "styles/style_layers.h"
  98. #include "styles/style_boxes.h"
  99. #include "styles/style_window.h" // st::windowMinWidth
  100. #include "styles/style_menu_icons.h"
  101. #include <QAction>
  102. #include <QtWidgets/QApplication>
  103. namespace Window {
  104. namespace {
  105. constexpr auto kTopicsSearchMinCount = 1;
  106. void ShareBotGame(
  107. not_null<UserData*> bot,
  108. not_null<Data::Thread*> thread,
  109. const QString &shortName) {
  110. auto &histories = thread->owner().histories();
  111. const auto history = thread->owningHistory();
  112. const auto randomId = base::RandomValue<uint64>();
  113. const auto replyTo = thread->topicRootId();
  114. const auto topicRootId = replyTo;
  115. auto flags = MTPmessages_SendMedia::Flags(0);
  116. if (replyTo) {
  117. flags |= MTPmessages_SendMedia::Flag::f_reply_to;
  118. }
  119. histories.sendPreparedMessage(
  120. history,
  121. FullReplyTo{
  122. .messageId = { replyTo ? history->peer->id : 0, replyTo },
  123. .topicRootId = topicRootId,
  124. },
  125. randomId,
  126. Data::Histories::PrepareMessage<MTPmessages_SendMedia>(
  127. MTP_flags(flags),
  128. history->peer->input,
  129. Data::Histories::ReplyToPlaceholder(),
  130. MTP_inputMediaGame(
  131. MTP_inputGameShortName(
  132. bot->inputUser,
  133. MTP_string(shortName))),
  134. MTP_string(),
  135. MTP_long(randomId),
  136. MTPReplyMarkup(),
  137. MTPVector<MTPMessageEntity>(),
  138. MTP_int(0), // schedule_date
  139. MTPInputPeer(), // send_as
  140. MTPInputQuickReplyShortcut(),
  141. MTPlong(),
  142. MTPlong()
  143. ), [=](const MTPUpdates &, const MTP::Response &) {
  144. }, [=](const MTP::Error &error, const MTP::Response &) {
  145. history->session().api().sendMessageFail(error, history->peer);
  146. });
  147. }
  148. } // namespace
  149. const char kOptionViewProfileInChatsListContextMenu[]
  150. = "view-profile-in-chats-list-context-menu";
  151. namespace {
  152. constexpr auto kArchivedToastDuration = crl::time(5000);
  153. constexpr auto kMaxUnreadWithoutConfirmation = 1000;
  154. base::options::toggle ViewProfileInChatsListContextMenu({
  155. .id = kOptionViewProfileInChatsListContextMenu,
  156. .name = "Add \"View Profile\"",
  157. .description = "Add \"View Profile\" to context menu in chats list",
  158. });
  159. void SetActionText(not_null<QAction*> action, rpl::producer<QString> &&text) {
  160. const auto lifetime = Ui::CreateChild<rpl::lifetime>(action.get());
  161. std::move(
  162. text
  163. ) | rpl::start_with_next([=](const QString &actionText) {
  164. action->setText(actionText);
  165. }, *lifetime);
  166. }
  167. void MarkAsReadChatList(not_null<Dialogs::MainList*> list) {
  168. auto mark = std::vector<not_null<History*>>();
  169. for (const auto &row : list->indexed()->all()) {
  170. if (const auto history = row->history()) {
  171. mark.push_back(history);
  172. }
  173. }
  174. ranges::for_each(mark, MarkAsReadThread);
  175. }
  176. void PeerMenuAddMuteSubmenuAction(
  177. not_null<Window::SessionController*> controller,
  178. not_null<Data::Thread*> thread,
  179. const PeerMenuCallback &addAction) {
  180. const auto notifySettings = &thread->owner().notifySettings();
  181. notifySettings->request(thread);
  182. const auto weak = base::make_weak(thread);
  183. const auto with = [=](Fn<void(not_null<Data::Thread*>)> callback) {
  184. return [=] {
  185. if (const auto strong = weak.get()) {
  186. callback(strong);
  187. }
  188. };
  189. };
  190. const auto isMuted = notifySettings->isMuted(thread);
  191. if (isMuted) {
  192. const auto text = tr::lng_context_unmute(tr::now)
  193. + '\t'
  194. + Ui::FormatMuteForTiny(thread->notify().muteUntil().value_or(0)
  195. - base::unixtime::now());
  196. addAction(text, with([=](not_null<Data::Thread*> thread) {
  197. notifySettings->update(thread, { .unmute = true });
  198. }), &st::menuIconUnmute);
  199. } else {
  200. const auto show = controller->uiShow();
  201. addAction(PeerMenuCallback::Args{
  202. .text = tr::lng_context_mute(tr::now),
  203. .handler = nullptr,
  204. .icon = (notifySettings->sound(thread).none
  205. ? &st::menuIconSilent
  206. : &st::menuIconMute),
  207. .fillSubmenu = [&](not_null<Ui::PopupMenu*> menu) {
  208. MuteMenu::FillMuteMenu(menu, thread, show);
  209. },
  210. });
  211. }
  212. }
  213. void ForwardToSelf(
  214. std::shared_ptr<Main::SessionShow> show,
  215. const Data::ForwardDraft &draft) {
  216. const auto session = &show->session();
  217. const auto history = session->data().history(session->user());
  218. auto resolved = history->resolveForwardDraft(draft);
  219. if (!resolved.items.empty()) {
  220. const auto count = resolved.items.size();
  221. auto action = Api::SendAction(history);
  222. action.clearDraft = false;
  223. action.generateLocal = false;
  224. session->api().forwardMessages(
  225. std::move(resolved),
  226. action,
  227. [=] {
  228. auto phrase = rpl::variable<TextWithEntities>(
  229. ChatHelpers::ForwardedMessagePhrase({
  230. .toCount = 1,
  231. .singleMessage = (count == 1),
  232. .to1 = session->user(),
  233. })).current();
  234. show->showToast(std::move(phrase));
  235. });
  236. }
  237. }
  238. class Filler {
  239. public:
  240. Filler(
  241. not_null<SessionController*> controller,
  242. Dialogs::EntryState request,
  243. const PeerMenuCallback &addAction);
  244. void fill();
  245. private:
  246. using Section = Dialogs::EntryState::Section;
  247. void fillChatsListActions();
  248. void fillHistoryActions();
  249. void fillProfileActions();
  250. void fillRepliesActions();
  251. void fillScheduledActions();
  252. void fillArchiveActions();
  253. void fillSavedSublistActions();
  254. void fillContextMenuActions();
  255. void addHidePromotion();
  256. void addTogglePin();
  257. void addToggleMuteSubmenu(bool addSeparator);
  258. void addSupportInfo();
  259. void addInfo();
  260. void addStoryArchive();
  261. void addNewWindow();
  262. void addToggleFolder();
  263. void addToggleUnreadMark();
  264. void addToggleArchive();
  265. void addClearHistory();
  266. void addDeleteChat();
  267. void addLeaveChat();
  268. void addJoinChat();
  269. void addTopicLink();
  270. void addManageTopic();
  271. void addManageChat();
  272. void addCreatePoll();
  273. void addThemeEdit();
  274. void addBlockUser();
  275. void addViewDiscussion();
  276. void addToggleTopicClosed();
  277. void addExportChat();
  278. void addTranslate();
  279. void addReport();
  280. void addNewContact();
  281. void addShareContact();
  282. void addEditContact();
  283. void addBotToGroup();
  284. void addNewMembers();
  285. void addDeleteContact();
  286. void addTTLSubmenu(bool addSeparator);
  287. void addSendGift();
  288. void addCreateTopic();
  289. void addViewAsMessages();
  290. void addViewAsTopics();
  291. void addSearchTopics();
  292. void addDeleteTopic();
  293. void addVideoChat();
  294. void addViewStatistics();
  295. void addBoostChat();
  296. not_null<SessionController*> _controller;
  297. Dialogs::EntryState _request;
  298. Data::Thread *_thread = nullptr;
  299. Data::ForumTopic *_topic = nullptr;
  300. PeerData *_peer = nullptr;
  301. Data::Folder *_folder = nullptr;
  302. Data::SavedSublist *_sublist = nullptr;
  303. const PeerMenuCallback &_addAction;
  304. };
  305. History *FindWastedPin(not_null<Data::Session*> data, Data::Folder *folder) {
  306. const auto &order = data->pinnedChatsOrder(folder);
  307. for (const auto &pinned : order) {
  308. if (const auto history = pinned.history()) {
  309. if (history->peer->isChat()
  310. && history->peer->asChat()->isDeactivated()
  311. && !history->inChatList()) {
  312. return history;
  313. }
  314. }
  315. }
  316. return nullptr;
  317. }
  318. void AddChatMembers(
  319. not_null<Window::SessionNavigation*> navigation,
  320. not_null<ChatData*> chat) {
  321. AddParticipantsBoxController::Start(navigation, chat);
  322. }
  323. bool PinnedLimitReached(
  324. not_null<Window::SessionController*> controller,
  325. not_null<Dialogs::Entry*> entry) {
  326. const auto owner = &entry->owner();
  327. if (owner->pinnedCanPin(entry)) {
  328. return false;
  329. }
  330. // Some old chat, that was converted, maybe is still pinned.
  331. if (const auto sublist = entry->asSublist()) {
  332. controller->show(Box(SublistsPinsLimitBox, &sublist->session()));
  333. return true;
  334. } else if (const auto topic = entry->asTopic()) {
  335. controller->show(Box(ForumPinsLimitBox, topic->forum()));
  336. return true;
  337. }
  338. const auto history = entry->asHistory();
  339. Assert(history != nullptr);
  340. const auto folder = history->folder();
  341. const auto wasted = FindWastedPin(owner, folder);
  342. if (wasted) {
  343. owner->setChatPinned(wasted, FilterId(), false);
  344. owner->setChatPinned(history, FilterId(), true);
  345. history->session().api().savePinnedOrder(folder);
  346. } else if (folder) {
  347. controller->show(Box(FolderPinsLimitBox, &history->session()));
  348. } else {
  349. controller->show(Box(PinsLimitBox, &history->session()));
  350. }
  351. return true;
  352. }
  353. bool PinnedLimitReached(
  354. not_null<Window::SessionController*> controller,
  355. not_null<History*> history,
  356. FilterId filterId) {
  357. const auto owner = &history->owner();
  358. if (owner->pinnedCanPin(filterId, history)) {
  359. return false;
  360. }
  361. controller->show(
  362. Box(FilterPinsLimitBox, &history->session(), filterId));
  363. return true;
  364. }
  365. void TogglePinnedThread(
  366. not_null<Window::SessionController*> controller,
  367. not_null<Dialogs::Entry*> entry) {
  368. if (!entry->folderKnown()) {
  369. return;
  370. }
  371. const auto owner = &entry->owner();
  372. const auto isPinned = !entry->isPinnedDialog(FilterId());
  373. if (isPinned && PinnedLimitReached(controller, entry)) {
  374. return;
  375. }
  376. owner->setChatPinned(entry, FilterId(), isPinned);
  377. if (const auto history = entry->asHistory()) {
  378. const auto flags = isPinned
  379. ? MTPmessages_ToggleDialogPin::Flag::f_pinned
  380. : MTPmessages_ToggleDialogPin::Flag(0);
  381. owner->session().api().request(MTPmessages_ToggleDialogPin(
  382. MTP_flags(flags),
  383. MTP_inputDialogPeer(history->peer->input)
  384. )).done([=] {
  385. owner->notifyPinnedDialogsOrderUpdated();
  386. }).send();
  387. if (isPinned) {
  388. controller->content()->dialogsToUp();
  389. }
  390. } else if (const auto topic = entry->asTopic()) {
  391. owner->session().api().request(MTPchannels_UpdatePinnedForumTopic(
  392. topic->channel()->inputChannel,
  393. MTP_int(topic->rootId()),
  394. MTP_bool(isPinned)
  395. )).done([=](const MTPUpdates &result) {
  396. owner->session().api().applyUpdates(result);
  397. }).send();
  398. } else if (const auto sublist = entry->asSublist()) {
  399. const auto flags = isPinned
  400. ? MTPmessages_ToggleSavedDialogPin::Flag::f_pinned
  401. : MTPmessages_ToggleSavedDialogPin::Flag(0);
  402. owner->session().api().request(MTPmessages_ToggleSavedDialogPin(
  403. MTP_flags(flags),
  404. MTP_inputDialogPeer(sublist->peer()->input)
  405. )).done([=] {
  406. owner->notifyPinnedDialogsOrderUpdated();
  407. }).send();
  408. //if (isPinned) {
  409. // controller->content()->dialogsToUp();
  410. //}
  411. }
  412. }
  413. Filler::Filler(
  414. not_null<SessionController*> controller,
  415. Dialogs::EntryState request,
  416. const PeerMenuCallback &addAction)
  417. : _controller(controller)
  418. , _request(request)
  419. , _thread(request.key.thread())
  420. , _topic(request.key.topic())
  421. , _peer(request.key.peer())
  422. , _folder(request.key.folder())
  423. , _sublist(request.key.sublist())
  424. , _addAction(addAction) {
  425. }
  426. void Filler::addHidePromotion() {
  427. const auto history = _request.key.history();
  428. if (_topic
  429. || !history
  430. || !history->useTopPromotion()
  431. || history->topPromotionType().isEmpty()) {
  432. return;
  433. }
  434. _addAction(tr::lng_context_hide_psa(tr::now), [=] {
  435. history->cacheTopPromotion(false, QString(), QString());
  436. history->session().api().request(MTPhelp_HidePromoData(
  437. history->peer->input
  438. )).send();
  439. }, &st::menuIconRemove);
  440. }
  441. void Filler::addToggleTopicClosed() {
  442. if (!_topic || !_topic->canToggleClosed()) {
  443. return;
  444. }
  445. const auto closed = _topic->closed();
  446. const auto weak = base::make_weak(_topic);
  447. _addAction(closed ? tr::lng_forum_topic_reopen(tr::now) : tr::lng_forum_topic_close(tr::now), [=] {
  448. if (const auto topic = weak.get()) {
  449. topic->setClosedAndSave(!closed);
  450. }
  451. }, closed ? &st::menuIconRestartBot : &st::menuIconBlock);
  452. }
  453. void Filler::addTogglePin() {
  454. if ((!_sublist && !_peer) || (_topic && !_topic->canTogglePinned())) {
  455. return;
  456. }
  457. const auto controller = _controller;
  458. const auto filterId = _request.filterId;
  459. const auto entry = _thread ? (Dialogs::Entry*)_thread : _sublist;
  460. if (!entry || entry->fixedOnTopIndex()) {
  461. return;
  462. }
  463. const auto pinText = [=] {
  464. return entry->isPinnedDialog(filterId)
  465. ? tr::lng_context_unpin_from_top(tr::now)
  466. : tr::lng_context_pin_to_top(tr::now);
  467. };
  468. const auto weak = base::make_weak(entry);
  469. const auto pinToggle = [=] {
  470. if (const auto strong = weak.get()) {
  471. TogglePinnedThread(controller, strong, filterId);
  472. }
  473. };
  474. _addAction(
  475. pinText(),
  476. pinToggle,
  477. (entry->isPinnedDialog(filterId)
  478. ? &st::menuIconUnpin
  479. : &st::menuIconPin));
  480. }
  481. void Filler::addToggleMuteSubmenu(bool addSeparator) {
  482. if (!_thread || _thread->peer()->isSelf()) {
  483. return;
  484. }
  485. PeerMenuAddMuteSubmenuAction(_controller, _thread, _addAction);
  486. if (addSeparator) {
  487. _addAction(PeerMenuCallback::Args{ .isSeparator = true });
  488. }
  489. }
  490. void Filler::addSupportInfo() {
  491. if (!_peer->session().supportMode()) {
  492. return;
  493. }
  494. const auto user = _peer->asUser();
  495. if (!user) {
  496. return;
  497. }
  498. const auto controller = _controller;
  499. _addAction("Edit support info", [=] {
  500. user->session().supportHelper().editInfo(controller, user);
  501. }, &st::menuIconEdit);
  502. }
  503. void Filler::addInfo() {
  504. if (_peer
  505. && (_peer->isSelf()
  506. || _peer->isRepliesChat()
  507. || _peer->isVerifyCodes())) {
  508. return;
  509. } else if (!_thread) {
  510. return;
  511. } else if (_controller->adaptive().isThreeColumn()) {
  512. const auto thread = _controller->activeChatCurrent().thread();
  513. if (thread && thread == _thread) {
  514. if (Core::App().settings().thirdSectionInfoEnabled()
  515. || Core::App().settings().tabbedReplacedWithInfo()) {
  516. return;
  517. }
  518. }
  519. }
  520. const auto controller = _controller;
  521. const auto weak = base::make_weak(_thread);
  522. const auto text = _thread->asTopic()
  523. ? tr::lng_context_view_topic(tr::now)
  524. : (_peer->isChat() || _peer->isMegagroup())
  525. ? tr::lng_context_view_group(tr::now)
  526. : _peer->isUser()
  527. ? tr::lng_context_view_profile(tr::now)
  528. : tr::lng_context_view_channel(tr::now);
  529. _addAction(text, [=] {
  530. if (const auto strong = weak.get()) {
  531. controller->showPeerInfo(strong);
  532. }
  533. }, _peer->isUser() ? &st::menuIconProfile : &st::menuIconInfo);
  534. }
  535. void Filler::addStoryArchive() {
  536. const auto channel = _peer ? _peer->asChannel() : nullptr;
  537. if (!channel || !channel->canEditStories()) {
  538. return;
  539. }
  540. const auto controller = _controller;
  541. const auto weak = base::make_weak(_thread);
  542. _addAction(tr::lng_stories_archive_button(tr::now), [=] {
  543. if (const auto strong = weak.get()) {
  544. controller->showSection(Info::Stories::Make(
  545. channel,
  546. Info::Stories::Tab::Archive));
  547. }
  548. }, &st::menuIconStoriesArchiveSection);
  549. }
  550. void Filler::addToggleFolder() {
  551. const auto controller = _controller;
  552. const auto history = _request.key.history();
  553. if (_topic
  554. || !history
  555. || !history->owner().chatsFilters().has()
  556. || !history->inChatList()) {
  557. return;
  558. }
  559. _addAction(PeerMenuCallback::Args{
  560. .text = tr::lng_filters_menu_add(tr::now),
  561. .handler = nullptr,
  562. .icon = &st::menuIconAddToFolder,
  563. .fillSubmenu = [&](not_null<Ui::PopupMenu*> menu) {
  564. FillChooseFilterMenu(controller, menu, history);
  565. },
  566. .submenuSt = &st::foldersMenu,
  567. });
  568. }
  569. void Filler::addToggleUnreadMark() {
  570. const auto peer = _peer;
  571. const auto history = _request.key.history();
  572. if (!_thread) {
  573. return;
  574. }
  575. const auto unread = IsUnreadThread(_thread);
  576. if ((_thread->asTopic() || peer->isForum()) && !unread) {
  577. return;
  578. }
  579. const auto weak = base::make_weak(_thread);
  580. const auto label = unread
  581. ? tr::lng_context_mark_read(tr::now)
  582. : tr::lng_context_mark_unread(tr::now);
  583. _addAction(label, [=] {
  584. const auto thread = weak.get();
  585. if (!thread) {
  586. return;
  587. }
  588. if (unread) {
  589. MarkAsReadThread(thread);
  590. } else if (history) {
  591. peer->owner().histories().changeDialogUnreadMark(history, true);
  592. }
  593. }, (unread ? &st::menuIconMarkRead : &st::menuIconMarkUnread));
  594. }
  595. void Filler::addNewWindow() {
  596. const auto controller = _controller;
  597. if (_folder) {
  598. _addAction(tr::lng_context_new_window(tr::now), [=] {
  599. Ui::PreventDelayedActivation();
  600. controller->showInNewWindow(SeparateId(
  601. SeparateType::Archive,
  602. &controller->session()));
  603. }, &st::menuIconNewWindow);
  604. AddSeparatorAndShiftUp(_addAction);
  605. return;
  606. } else if (const auto weak = base::make_weak(_sublist)) {
  607. _addAction(tr::lng_context_new_window(tr::now), [=] {
  608. Ui::PreventDelayedActivation();
  609. if (const auto sublist = weak.get()) {
  610. const auto peer = sublist->peer();
  611. controller->showInNewWindow(SeparateId(
  612. SeparateType::SavedSublist,
  613. peer->owner().history(peer)));
  614. }
  615. }, &st::menuIconNewWindow);
  616. AddSeparatorAndShiftUp(_addAction);
  617. return;
  618. }
  619. const auto history = _request.key.history();
  620. if (!_peer
  621. || (history
  622. && history->useTopPromotion()
  623. && !history->topPromotionType().isEmpty())) {
  624. return;
  625. }
  626. const auto peer = _peer;
  627. const auto thread = _topic
  628. ? not_null<Data::Thread*>(_topic)
  629. : _peer->owner().history(_peer);
  630. const auto weak = base::make_weak(thread);
  631. _addAction(tr::lng_context_new_window(tr::now), [=] {
  632. Ui::PreventDelayedActivation();
  633. if (const auto strong = weak.get()) {
  634. const auto forum = !strong->asTopic() && peer->isForum();
  635. controller->showInNewWindow(SeparateId(
  636. forum ? SeparateType::Forum : SeparateType::Chat,
  637. strong));
  638. }
  639. }, &st::menuIconNewWindow);
  640. AddSeparatorAndShiftUp(_addAction);
  641. }
  642. void Filler::addToggleArchive() {
  643. if (!_peer || _topic) {
  644. return;
  645. }
  646. const auto peer = _peer;
  647. const auto history = _request.key.history();
  648. if (history && history->useTopPromotion()) {
  649. return;
  650. } else if (peer->isNotificationsUser() || peer->isSelf()) {
  651. if (!history || !history->folder()) {
  652. return;
  653. }
  654. }
  655. const auto isArchived = [=] {
  656. return IsArchived(history);
  657. };
  658. const auto label = [=] {
  659. return isArchived()
  660. ? tr::lng_archived_remove(tr::now)
  661. : tr::lng_archived_add(tr::now);
  662. };
  663. const auto toggle = [=, show = _controller->uiShow()] {
  664. ToggleHistoryArchived(show, history, !isArchived());
  665. };
  666. const auto archiveAction = _addAction(
  667. label(),
  668. toggle,
  669. isArchived() ? &st::menuIconUnarchive : &st::menuIconArchive);
  670. auto actionText = history->session().changes().historyUpdates(
  671. history,
  672. Data::HistoryUpdate::Flag::Folder
  673. ) | rpl::map(label);
  674. SetActionText(archiveAction, std::move(actionText));
  675. }
  676. void Filler::addClearHistory() {
  677. if (_topic) {
  678. return;
  679. }
  680. const auto channel = _peer->asChannel();
  681. const auto isGroup = _peer->isChat() || _peer->isMegagroup();
  682. if (channel) {
  683. if (!channel->amIn()) {
  684. return;
  685. } else if (!channel->canDeleteMessages()
  686. && (!isGroup || channel->isPublic() || channel->isForum())) {
  687. return;
  688. }
  689. }
  690. _addAction(
  691. tr::lng_profile_clear_history(tr::now),
  692. ClearHistoryHandler(_controller, _peer),
  693. &st::menuIconClear);
  694. }
  695. void Filler::addDeleteChat() {
  696. if (_topic || _peer->isChannel()) {
  697. return;
  698. }
  699. _addAction({
  700. .text = (_peer->isUser()
  701. ? tr::lng_profile_delete_conversation(tr::now)
  702. : tr::lng_profile_clear_and_exit(tr::now)),
  703. .handler = DeleteAndLeaveHandler(_controller, _peer),
  704. .icon = &st::menuIconDeleteAttention,
  705. .isAttention = true,
  706. });
  707. }
  708. void Filler::addLeaveChat() {
  709. const auto channel = _peer->asChannel();
  710. if (_topic || !channel || !channel->amIn()) {
  711. return;
  712. }
  713. _addAction({
  714. .text = (_peer->isMegagroup()
  715. ? tr::lng_profile_leave_group(tr::now)
  716. : tr::lng_profile_leave_channel(tr::now)),
  717. .handler = DeleteAndLeaveHandler(_controller, _peer),
  718. .icon = &st::menuIconLeaveAttention,
  719. .isAttention = true,
  720. });
  721. }
  722. void Filler::addJoinChat() {
  723. const auto channel = _peer->asChannel();
  724. if (_topic || !channel || channel->amIn()) {
  725. return;
  726. }
  727. const auto label = _peer->isMegagroup()
  728. ? tr::lng_profile_join_group(tr::now)
  729. : tr::lng_profile_join_channel(tr::now);
  730. _addAction(label, [=] {
  731. channel->session().api().joinChannel(channel);
  732. }, &st::menuIconAddToFolder);
  733. }
  734. void Filler::addBlockUser() {
  735. const auto user = _peer->asUser();
  736. if (!user
  737. || user->isInaccessible()
  738. || user->isSelf()
  739. || user->isRepliesChat()
  740. || user->isVerifyCodes()) {
  741. return;
  742. }
  743. const auto window = &_controller->window();
  744. const auto blockText = [](not_null<UserData*> user) {
  745. return user->isBlocked()
  746. ? ((user->isBot() && !user->isSupport())
  747. ? tr::lng_profile_restart_bot(tr::now)
  748. : tr::lng_profile_unblock_user(tr::now))
  749. : ((user->isBot() && !user->isSupport())
  750. ? tr::lng_profile_block_bot(tr::now)
  751. : tr::lng_profile_block_user(tr::now));
  752. };
  753. const auto blockAction = _addAction(blockText(user), [=] {
  754. const auto show = window->uiShow();
  755. if (user->isBlocked()) {
  756. PeerMenuUnblockUserWithBotRestart(show, user);
  757. } else if (user->isBot()) {
  758. user->session().api().blockedPeers().block(user);
  759. } else {
  760. window->show(Box(
  761. PeerMenuBlockUserBox,
  762. window,
  763. user,
  764. v::null,
  765. v::null));
  766. }
  767. }, (!user->isBlocked()
  768. ? &st::menuIconBlock
  769. : user->isBot()
  770. ? &st::menuIconRestartBot
  771. : &st::menuIconUnblock));
  772. auto actionText = _peer->session().changes().peerUpdates(
  773. _peer,
  774. Data::PeerUpdate::Flag::IsBlocked
  775. ) | rpl::map([=] { return blockText(user); });
  776. SetActionText(blockAction, std::move(actionText));
  777. if (user->blockStatus() == UserData::BlockStatus::Unknown) {
  778. user->session().api().requestFullPeer(user);
  779. }
  780. }
  781. void Filler::addViewDiscussion() {
  782. const auto channel = _peer->asBroadcast();
  783. if (!channel) {
  784. return;
  785. }
  786. const auto chat = channel->linkedChat();
  787. if (!chat) {
  788. return;
  789. }
  790. const auto navigation = _controller;
  791. _addAction(tr::lng_profile_view_discussion(tr::now), [=] {
  792. if (channel->invitePeekExpires()) {
  793. navigation->showToast(tr::lng_channel_invite_private(tr::now));
  794. return;
  795. }
  796. navigation->showPeerHistory(
  797. chat,
  798. Window::SectionShow::Way::Forward);
  799. }, &st::menuIconDiscussion);
  800. }
  801. void Filler::addExportChat() {
  802. if (_thread->asTopic() || !_peer->canExportChatHistory()) {
  803. return;
  804. }
  805. const auto peer = _peer;
  806. _addAction(
  807. tr::lng_profile_export_chat(tr::now),
  808. [=] { PeerMenuExportChat(peer); },
  809. &st::menuIconExport);
  810. }
  811. void Filler::addTranslate() {
  812. if (_peer->translationFlag() != PeerData::TranslationFlag::Disabled
  813. || !_peer->session().premium()
  814. || !Core::App().settings().translateChatEnabled()) {
  815. return;
  816. }
  817. const auto history = _peer->owner().historyLoaded(_peer);
  818. if (!history
  819. || !history->translateOfferedFrom()
  820. || history->translatedTo()) {
  821. return;
  822. }
  823. _addAction(tr::lng_context_translate(tr::now), [=] {
  824. history->peer->saveTranslationDisabled(false);
  825. }, &st::menuIconTranslate);
  826. }
  827. void Filler::addReport() {
  828. const auto chat = _peer->asChat();
  829. const auto channel = _peer->asChannel();
  830. if (_topic
  831. || ((!chat || chat->amCreator())
  832. && (!channel || channel->amCreator()))) {
  833. return;
  834. }
  835. const auto peer = _peer;
  836. const auto navigation = _controller;
  837. _addAction(tr::lng_profile_report(tr::now), [=] {
  838. ShowReportMessageBox(navigation->uiShow(), peer, {}, {});
  839. }, &st::menuIconReport);
  840. }
  841. void Filler::addNewContact() {
  842. const auto user = _peer->asUser();
  843. if (!user
  844. || user->isContact()
  845. || user->isSelf()
  846. || user->isInaccessible()
  847. || user->isBot()) {
  848. return;
  849. }
  850. const auto controller = _controller;
  851. _addAction(
  852. tr::lng_info_add_as_contact(tr::now),
  853. [=] { controller->show(Box(EditContactBox, controller, user)); },
  854. &st::menuIconInvite);
  855. }
  856. void Filler::addShareContact() {
  857. const auto user = _peer->asUser();
  858. if (!user || !user->canShareThisContact()) {
  859. return;
  860. }
  861. const auto controller = _controller;
  862. _addAction(
  863. tr::lng_info_share_contact(tr::now),
  864. [=] { PeerMenuShareContactBox(controller, user); },
  865. &st::menuIconShare);
  866. }
  867. void Filler::addEditContact() {
  868. const auto user = _peer->asUser();
  869. if (!user || !user->isContact() || user->isSelf()) {
  870. return;
  871. }
  872. const auto controller = _controller;
  873. _addAction(
  874. tr::lng_info_edit_contact(tr::now),
  875. [=] { controller->show(Box(EditContactBox, controller, user)); },
  876. &st::menuIconEdit);
  877. }
  878. void Filler::addBotToGroup() {
  879. const auto user = _peer->asUser();
  880. if (!user) {
  881. return;
  882. }
  883. [[maybe_unused]] const auto lifetime = Info::Profile::InviteToChatButton(
  884. user
  885. ) | rpl::take(1) | rpl::start_with_next([=](QString label) {
  886. if (!label.isEmpty()) {
  887. const auto controller = _controller;
  888. _addAction(
  889. label,
  890. [=] { AddBotToGroupBoxController::Start(controller, user); },
  891. &st::menuIconInvite);
  892. }
  893. });
  894. }
  895. void Filler::addNewMembers() {
  896. const auto chat = _peer->asChat();
  897. const auto channel = _peer->asChannel();
  898. if ((!chat || !chat->canAddMembers())
  899. && (!channel || !channel->canAddMembers())) {
  900. return;
  901. }
  902. const auto navigation = _controller;
  903. const auto callback = chat
  904. ? Fn<void()>([=] { AddChatMembers(navigation, chat); })
  905. : [=] { PeerMenuAddChannelMembers(navigation, channel); };
  906. _addAction(
  907. ((chat || channel->isMegagroup())
  908. ? tr::lng_channel_add_members(tr::now)
  909. : tr::lng_channel_add_users(tr::now)),
  910. callback,
  911. &st::menuIconInvite);
  912. }
  913. void Filler::addDeleteContact() {
  914. const auto user = _peer->asUser();
  915. if (!user || !user->isContact() || user->isSelf()) {
  916. return;
  917. }
  918. const auto controller = _controller;
  919. _addAction({
  920. .text = tr::lng_info_delete_contact(tr::now),
  921. .handler = [=] { PeerMenuDeleteContact(controller, user); },
  922. .icon = &st::menuIconDeleteAttention,
  923. .isAttention = true,
  924. });
  925. }
  926. void Filler::addDeleteTopic() {
  927. if (!_topic || !_topic->canDelete()) {
  928. return;
  929. }
  930. const auto controller = _controller;
  931. const auto weak = base::make_weak(_topic);
  932. const auto callback = [=] {
  933. if (const auto strong = weak.get()) {
  934. PeerMenuDeleteTopicWithConfirmation(controller, strong);
  935. }
  936. };
  937. _addAction({
  938. .text = tr::lng_forum_topic_delete(tr::now),
  939. .handler = callback,
  940. .icon = &st::menuIconDeleteAttention,
  941. .isAttention = true,
  942. });
  943. }
  944. void Filler::addTopicLink() {
  945. if (!_topic || _topic->creating()) {
  946. return;
  947. }
  948. const auto channel = _topic->channel();
  949. const auto id = _topic->rootId();
  950. const auto controller = _controller;
  951. _addAction(tr::lng_context_copy_topic_link(tr::now), [=] {
  952. const auto base = channel->hasUsername()
  953. ? channel->username()
  954. : "c/" + QString::number(peerToChannel(channel->id).bare);
  955. const auto query = base + '/' + QString::number(id.bare);
  956. const auto link = channel->session().createInternalLinkFull(query);
  957. QGuiApplication::clipboard()->setText(link);
  958. controller->showToast(channel->hasUsername()
  959. ? tr::lng_channel_public_link_copied(tr::now)
  960. : tr::lng_context_about_private_link(tr::now));
  961. }, &st::menuIconCopy);
  962. }
  963. void Filler::addManageTopic() {
  964. if (!_topic || !_topic->canEdit()) {
  965. return;
  966. }
  967. const auto history = _topic->history();
  968. const auto rootId = _topic->rootId();
  969. const auto navigation = _controller;
  970. _addAction(tr::lng_forum_topic_edit(tr::now), [=] {
  971. navigation->show(
  972. Box(EditForumTopicBox, navigation, history, rootId));
  973. }, &st::menuIconEdit);
  974. }
  975. void Filler::addManageChat() {
  976. if (!EditPeerInfoBox::Available(_peer)) {
  977. return;
  978. }
  979. const auto peer = _peer;
  980. const auto navigation = _controller;
  981. const auto text = peer->isUser()
  982. ? tr::lng_manage_bot_title(tr::now)
  983. : (peer->isChat() || peer->isMegagroup())
  984. ? tr::lng_manage_group_title(tr::now)
  985. : tr::lng_manage_channel_title(tr::now);
  986. _addAction(text, [=] {
  987. navigation->showEditPeerBox(peer);
  988. }, &st::menuIconManage);
  989. }
  990. void Filler::addBoostChat() {
  991. if (const auto channel = _peer->asChannel()) {
  992. const auto text = channel->isMegagroup()
  993. ? tr::lng_boost_group_button(tr::now)
  994. : tr::lng_boost_channel_button(tr::now);
  995. const auto weak = base::make_weak(_controller);
  996. _addAction(text, [=] {
  997. if (const auto strong = weak.get()) {
  998. strong->resolveBoostState(channel);
  999. }
  1000. }, &st::menuIconBoosts);
  1001. }
  1002. }
  1003. void Filler::addViewStatistics() {
  1004. if (const auto channel = _peer->asChannel()) {
  1005. const auto controller = _controller;
  1006. const auto weak = base::make_weak(_thread);
  1007. const auto peer = _peer;
  1008. using Flag = ChannelDataFlag;
  1009. const auto canGetStats = (channel->flags() & Flag::CanGetStatistics);
  1010. const auto canViewEarn = (channel->flags() & Flag::CanViewRevenue);
  1011. const auto canViewCreditsEarn
  1012. = (channel->flags() & Flag::CanViewCreditsRevenue);
  1013. if (canGetStats) {
  1014. _addAction(tr::lng_stats_title(tr::now), [=] {
  1015. if (const auto strong = weak.get()) {
  1016. using namespace Info;
  1017. controller->showSection(Statistics::Make(peer, {}, {}));
  1018. }
  1019. }, &st::menuIconStats);
  1020. }
  1021. if (canGetStats
  1022. || channel->amCreator()
  1023. || channel->canPostStories()) {
  1024. _addAction(tr::lng_boosts_title(tr::now), [=] {
  1025. if (const auto strong = weak.get()) {
  1026. controller->showSection(Info::Boosts::Make(peer));
  1027. }
  1028. }, &st::menuIconBoosts);
  1029. }
  1030. if (canViewEarn || canViewCreditsEarn) {
  1031. _addAction(tr::lng_channel_earn_title(tr::now), [=] {
  1032. if (const auto strong = weak.get()) {
  1033. controller->showSection(Info::ChannelEarn::Make(peer));
  1034. }
  1035. }, &st::menuIconEarn);
  1036. }
  1037. }
  1038. }
  1039. void Filler::addCreatePoll() {
  1040. const auto isJoinChannel = [&] {
  1041. if (_request.section != Section::Replies) {
  1042. if (const auto c = _peer->asChannel(); c && !c->amIn()) {
  1043. return true;
  1044. }
  1045. }
  1046. return false;
  1047. }();
  1048. const auto isBotStart = [&] {
  1049. const auto user = _peer ? _peer->asUser() : nullptr;
  1050. if (!user || !user->isBot()) {
  1051. return false;
  1052. } else if (!user->botInfo->startToken.isEmpty()) {
  1053. return true;
  1054. }
  1055. const auto history = _peer->owner().history(_peer);
  1056. if (history && history->isEmpty() && !history->lastMessage()) {
  1057. return true;
  1058. }
  1059. return false;
  1060. }();
  1061. const auto isBlocked = [&] {
  1062. return _peer && _peer->isUser() && _peer->asUser()->isBlocked();
  1063. }();
  1064. if (isBlocked || isJoinChannel || isBotStart) {
  1065. return;
  1066. }
  1067. const auto can = _topic
  1068. ? Data::CanSend(_topic, ChatRestriction::SendPolls)
  1069. : _peer->canCreatePolls();
  1070. if (!can) {
  1071. return;
  1072. }
  1073. const auto peer = _peer;
  1074. const auto controller = _controller;
  1075. const auto source = (_request.section == Section::Scheduled)
  1076. ? Api::SendType::Scheduled
  1077. : Api::SendType::Normal;
  1078. const auto sendMenuType = (_request.section == Section::Scheduled)
  1079. ? SendMenu::Type::Disabled
  1080. : (_request.section == Section::Replies
  1081. || _peer->starsPerMessageChecked())
  1082. ? SendMenu::Type::SilentOnly
  1083. : SendMenu::Type::Scheduled;
  1084. const auto flag = PollData::Flags();
  1085. const auto replyTo = _request.currentReplyTo;
  1086. auto callback = [=] {
  1087. PeerMenuCreatePoll(
  1088. controller,
  1089. peer,
  1090. replyTo,
  1091. flag,
  1092. flag,
  1093. source,
  1094. { sendMenuType });
  1095. };
  1096. _addAction(
  1097. tr::lng_polls_create(tr::now),
  1098. std::move(callback),
  1099. &st::menuIconCreatePoll);
  1100. }
  1101. void Filler::addThemeEdit() {
  1102. const auto user = _peer->asUser();
  1103. if (!user || user->isInaccessible()) {
  1104. return;
  1105. }
  1106. if (user->requiresPremiumToWrite() && !user->session().premium()) {
  1107. return;
  1108. }
  1109. const auto controller = _controller;
  1110. _addAction(
  1111. tr::lng_chat_theme_wallpaper(tr::now),
  1112. [=] { controller->toggleChooseChatTheme(user); },
  1113. &st::menuIconChangeColors);
  1114. }
  1115. void Filler::addTTLSubmenu(bool addSeparator) {
  1116. if (_thread->asTopic()) {
  1117. return; // #TODO later forum
  1118. }
  1119. const auto validator = TTLMenu::TTLValidator(
  1120. _controller->uiShow(),
  1121. _peer);
  1122. if (!validator.can()) {
  1123. return;
  1124. }
  1125. const auto text = tr::lng_manage_messages_ttl_menu(tr::now)
  1126. + (_peer->messagesTTL()
  1127. ? ('\t' + Ui::FormatTTLTiny(_peer->messagesTTL()))
  1128. : QString());
  1129. _addAction(text, [=] { validator.showBox(); }, validator.icon());
  1130. if (addSeparator) {
  1131. _addAction(PeerMenuCallback::Args{ .isSeparator = true });
  1132. }
  1133. }
  1134. void Filler::addSendGift() {
  1135. const auto user = _peer->asUser();
  1136. const auto channel = _peer->asBroadcast();
  1137. if (!user && !channel) {
  1138. return;
  1139. } else if (user
  1140. && (user->isInaccessible()
  1141. || user->isSelf()
  1142. || user->isBot()
  1143. || user->isServiceUser()
  1144. || user->isNotificationsUser()
  1145. || user->isRepliesChat()
  1146. || user->isVerifyCodes()
  1147. || !user->session().premiumCanBuy())) {
  1148. return;
  1149. } else if (channel
  1150. && (channel->isForbidden() || !channel->stargiftsAvailable())) {
  1151. return;
  1152. }
  1153. const auto peer = _peer;
  1154. const auto navigation = _controller;
  1155. _addAction(tr::lng_profile_gift_premium(tr::now), [=] {
  1156. Ui::ShowStarGiftBox(navigation, peer);
  1157. }, &st::menuIconGiftPremium);
  1158. }
  1159. void Filler::fill() {
  1160. if (_folder) {
  1161. fillArchiveActions();
  1162. } else if (_sublist) {
  1163. fillSavedSublistActions();
  1164. } else switch (_request.section) {
  1165. case Section::ChatsList: fillChatsListActions(); break;
  1166. case Section::History: fillHistoryActions(); break;
  1167. case Section::Profile: fillProfileActions(); break;
  1168. case Section::Replies: fillRepliesActions(); break;
  1169. case Section::Scheduled: fillScheduledActions(); break;
  1170. case Section::ContextMenu: fillContextMenuActions(); break;
  1171. default: Unexpected("_request.section in Filler::fill.");
  1172. }
  1173. }
  1174. void Filler::addCreateTopic() {
  1175. if (!_peer || !_peer->canCreateTopics()) {
  1176. return;
  1177. }
  1178. const auto peer = _peer;
  1179. const auto controller = _controller;
  1180. _addAction(tr::lng_forum_create_topic(tr::now), [=] {
  1181. if (const auto forum = peer->forum()) {
  1182. controller->show(Box(
  1183. NewForumTopicBox,
  1184. controller,
  1185. forum->history()));
  1186. }
  1187. }, &st::menuIconDiscussion);
  1188. _addAction(PeerMenuCallback::Args{ .isSeparator = true });
  1189. }
  1190. void Filler::addViewAsMessages() {
  1191. if (!_peer || !_peer->isForum()) {
  1192. return;
  1193. }
  1194. const auto peer = _peer;
  1195. const auto controller = _controller;
  1196. const auto parentHideRequests = std::make_shared<rpl::event_stream<>>();
  1197. const auto filterOutChatPreview = [=] {
  1198. if (base::IsAltPressed()) {
  1199. const auto callback = [=](bool shown) {
  1200. if (!shown) {
  1201. parentHideRequests->fire({});
  1202. }
  1203. };
  1204. controller->showChatPreview({
  1205. peer->owner().history(peer),
  1206. FullMsgId(),
  1207. }, callback, QApplication::activePopupWidget());
  1208. return true;
  1209. } else if (base::IsCtrlPressed()) {
  1210. Ui::PreventDelayedActivation();
  1211. controller->showInNewWindow(SeparateId(
  1212. SeparateType::Chat,
  1213. peer->owner().history(peer)));
  1214. return true;
  1215. }
  1216. return false;
  1217. };
  1218. const auto open = [=] {
  1219. if (const auto forum = peer->forum()) {
  1220. peer->owner().saveViewAsMessages(forum, true);
  1221. }
  1222. controller->showPeerHistory(peer->id);
  1223. };
  1224. auto to_instant = rpl::map_to(anim::type::instant);
  1225. _addAction({
  1226. .text = tr::lng_forum_view_as_messages(tr::now),
  1227. .handler = open,
  1228. .icon = &st::menuIconAsMessages,
  1229. .triggerFilter = filterOutChatPreview,
  1230. .hideRequests = parentHideRequests->events() | to_instant
  1231. });
  1232. }
  1233. void Filler::addViewAsTopics() {
  1234. if (!_peer
  1235. || !_peer->isForum()
  1236. || !_controller->adaptive().isOneColumn()) {
  1237. return;
  1238. }
  1239. const auto peer = _peer;
  1240. const auto controller = _controller;
  1241. _addAction(tr::lng_forum_view_as_topics(tr::now), [=] {
  1242. if (const auto forum = peer->forum()) {
  1243. peer->owner().saveViewAsMessages(forum, false);
  1244. controller->showForum(forum);
  1245. }
  1246. }, &st::menuIconAsTopics);
  1247. }
  1248. void Filler::addSearchTopics() {
  1249. const auto forum = _peer ? _peer->forum() : nullptr;
  1250. if (!forum) {
  1251. return;
  1252. }
  1253. const auto history = forum->history();
  1254. const auto controller = _controller;
  1255. _addAction(tr::lng_dlg_filter(tr::now), [=] {
  1256. controller->searchInChat(history);
  1257. }, &st::menuIconSearch);
  1258. }
  1259. void Filler::fillChatsListActions() {
  1260. if (!_peer || !_peer->isForum()) {
  1261. return;
  1262. }
  1263. addCreateTopic();
  1264. addInfo();
  1265. addViewAsMessages();
  1266. const auto &all = _peer->forum()->topicsList()->indexed()->all();
  1267. if (all.size() > kTopicsSearchMinCount) {
  1268. addSearchTopics();
  1269. }
  1270. addManageChat();
  1271. addNewMembers();
  1272. addBoostChat();
  1273. addVideoChat();
  1274. _addAction(PeerMenuCallback::Args{ .isSeparator = true });
  1275. addReport();
  1276. if (_peer->asChannel()->amIn()) {
  1277. addLeaveChat();
  1278. } else {
  1279. addJoinChat();
  1280. }
  1281. }
  1282. void Filler::addVideoChat() {
  1283. auto test = Ui::PopupMenu(nullptr);
  1284. FillVideoChatMenu(
  1285. _controller,
  1286. _request,
  1287. Ui::Menu::CreateAddActionCallback(&test));
  1288. if (test.actions().size() < 2) {
  1289. FillVideoChatMenu(_controller, _request, _addAction);
  1290. return;
  1291. }
  1292. _addAction(PeerMenuCallback::Args{
  1293. .text = tr::lng_menu_start_group_call_options(tr::now),
  1294. .handler = nullptr,
  1295. .icon = &st::menuIconVideoChat,
  1296. .fillSubmenu = [&](not_null<Ui::PopupMenu*> menu) {
  1297. FillVideoChatMenu(
  1298. _controller,
  1299. _request,
  1300. Ui::Menu::CreateAddActionCallback(menu));
  1301. },
  1302. });
  1303. }
  1304. void Filler::fillContextMenuActions() {
  1305. addNewWindow();
  1306. addHidePromotion();
  1307. addToggleArchive();
  1308. addTogglePin();
  1309. if (ViewProfileInChatsListContextMenu.value()) {
  1310. addInfo();
  1311. }
  1312. addToggleMuteSubmenu(false);
  1313. addToggleUnreadMark();
  1314. addToggleTopicClosed();
  1315. addToggleFolder();
  1316. if (const auto user = _peer->asUser()) {
  1317. if (!user->isContact()) {
  1318. addBlockUser();
  1319. }
  1320. }
  1321. addClearHistory();
  1322. addDeleteChat();
  1323. addLeaveChat();
  1324. addDeleteTopic();
  1325. }
  1326. void Filler::fillHistoryActions() {
  1327. addToggleMuteSubmenu(true);
  1328. addInfo();
  1329. addViewAsTopics();
  1330. addManageChat();
  1331. addStoryArchive();
  1332. addSupportInfo();
  1333. addBoostChat();
  1334. addCreatePoll();
  1335. addThemeEdit();
  1336. addViewDiscussion();
  1337. addExportChat();
  1338. addTranslate();
  1339. addReport();
  1340. addClearHistory();
  1341. addDeleteChat();
  1342. addLeaveChat();
  1343. }
  1344. void Filler::fillProfileActions() {
  1345. addTTLSubmenu(true);
  1346. addSupportInfo();
  1347. addNewContact();
  1348. addShareContact();
  1349. addEditContact();
  1350. addBotToGroup();
  1351. addNewMembers();
  1352. addSendGift();
  1353. addViewStatistics();
  1354. addStoryArchive();
  1355. addManageChat();
  1356. addTopicLink();
  1357. addManageTopic();
  1358. addToggleTopicClosed();
  1359. addViewDiscussion();
  1360. addExportChat();
  1361. addToggleFolder();
  1362. addBlockUser();
  1363. addReport();
  1364. addLeaveChat();
  1365. addDeleteContact();
  1366. addDeleteTopic();
  1367. }
  1368. void Filler::fillRepliesActions() {
  1369. if (_topic) {
  1370. addInfo();
  1371. addManageTopic();
  1372. }
  1373. addBoostChat();
  1374. addCreatePoll();
  1375. addToggleTopicClosed();
  1376. addDeleteTopic();
  1377. }
  1378. void Filler::fillScheduledActions() {
  1379. addCreatePoll();
  1380. }
  1381. void Filler::fillArchiveActions() {
  1382. Expects(_folder != nullptr);
  1383. if (_folder->id() != Data::Folder::kId) {
  1384. return;
  1385. }
  1386. addNewWindow();
  1387. const auto controller = _controller;
  1388. const auto hidden = controller->session().settings().archiveCollapsed();
  1389. const auto inmenu = controller->session().settings().archiveInMainMenu();
  1390. if (!inmenu) {
  1391. const auto text = hidden
  1392. ? tr::lng_context_archive_expand(tr::now)
  1393. : tr::lng_context_archive_collapse(tr::now);
  1394. _addAction(text, [=] {
  1395. controller->session().settings().setArchiveCollapsed(!hidden);
  1396. controller->session().saveSettingsDelayed();
  1397. }, hidden ? &st::menuIconExpand : &st::menuIconCollapse);
  1398. }
  1399. {
  1400. const auto text = inmenu
  1401. ? tr::lng_context_archive_to_list(tr::now)
  1402. : tr::lng_context_archive_to_menu(tr::now);
  1403. _addAction(text, [=] {
  1404. if (!inmenu) {
  1405. controller->showToast({
  1406. .text = {
  1407. tr::lng_context_archive_to_menu_info(tr::now)
  1408. },
  1409. .st = &st::windowArchiveToast,
  1410. .duration = kArchivedToastDuration,
  1411. });
  1412. }
  1413. controller->session().settings().setArchiveInMainMenu(!inmenu);
  1414. controller->session().saveSettingsDelayed();
  1415. controller->window().hideSettingsAndLayer();
  1416. }, inmenu ? &st::menuIconFromMainMenu : &st::menuIconToMainMenu);
  1417. }
  1418. MenuAddMarkAsReadChatListAction(
  1419. controller,
  1420. [folder = _folder] { return folder->chatsList(); },
  1421. _addAction);
  1422. _addAction({ .isSeparator = true });
  1423. Settings::PreloadArchiveSettings(&controller->session());
  1424. _addAction(tr::lng_context_archive_settings(tr::now), [=] {
  1425. controller->show(Box(Settings::ArchiveSettingsBox, controller));
  1426. }, &st::menuIconManage);
  1427. }
  1428. void Filler::fillSavedSublistActions() {
  1429. addNewWindow();
  1430. addTogglePin();
  1431. }
  1432. } // namespace
  1433. void PeerMenuExportChat(not_null<PeerData*> peer) {
  1434. base::call_delayed(st::defaultPopupMenu.showDuration, [=] {
  1435. Core::App().exportManager().start(peer);
  1436. });
  1437. }
  1438. void PeerMenuDeleteContact(
  1439. not_null<Window::SessionController*> controller,
  1440. not_null<UserData*> user) {
  1441. const auto text = tr::lng_sure_delete_contact(
  1442. tr::now,
  1443. lt_contact,
  1444. user->name());
  1445. const auto deleteSure = [=](Fn<void()> &&close) {
  1446. close();
  1447. user->session().api().request(MTPcontacts_DeleteContacts(
  1448. MTP_vector<MTPInputUser>(1, user->inputUser)
  1449. )).done([=](const MTPUpdates &result) {
  1450. user->session().api().applyUpdates(result);
  1451. }).send();
  1452. };
  1453. auto box = Box([=](not_null<Ui::GenericBox*> box) {
  1454. Ui::AddSkip(box->verticalLayout());
  1455. Ui::IconWithTitle(
  1456. box->verticalLayout(),
  1457. Ui::CreateChild<Ui::UserpicButton>(
  1458. box,
  1459. user,
  1460. st::mainMenuUserpic),
  1461. Ui::CreateChild<Ui::FlatLabel>(
  1462. box,
  1463. tr::lng_info_delete_contact() | Ui::Text::ToBold(),
  1464. box->getDelegate()->style().title));
  1465. Ui::ConfirmBox(box, {
  1466. .text = text,
  1467. .confirmed = deleteSure,
  1468. .confirmText = tr::lng_box_delete(),
  1469. .confirmStyle = &st::attentionBoxButton,
  1470. });
  1471. });
  1472. controller->show(std::move(box), Ui::LayerOption::CloseOther);
  1473. }
  1474. void PeerMenuDeleteTopicWithConfirmation(
  1475. not_null<Window::SessionNavigation*> navigation,
  1476. not_null<Data::ForumTopic*> topic) {
  1477. const auto weak = base::make_weak(topic);
  1478. const auto callback = [=](Fn<void()> &&close) {
  1479. close();
  1480. if (const auto strong = weak.get()) {
  1481. PeerMenuDeleteTopic(navigation, strong);
  1482. }
  1483. };
  1484. const auto controller = navigation->parentController();
  1485. controller->show(Box([=](not_null<Ui::GenericBox*> box) {
  1486. Ui::AddSkip(box->verticalLayout());
  1487. Ui::IconWithTitle(
  1488. box->verticalLayout(),
  1489. Ui::CreateChild<Info::Profile::TopicIconButton>(
  1490. box,
  1491. controller,
  1492. topic),
  1493. Ui::CreateChild<Ui::FlatLabel>(
  1494. box,
  1495. topic->title(),
  1496. box->getDelegate()->style().title));
  1497. Ui::AddSkip(box->verticalLayout());
  1498. Ui::AddSkip(box->verticalLayout());
  1499. Ui::ConfirmBox(box, {
  1500. .text = tr::lng_forum_topic_delete_sure(tr::now),
  1501. .confirmed = callback,
  1502. .confirmText = tr::lng_box_delete(),
  1503. .confirmStyle = &st::attentionBoxButton,
  1504. .labelPadding = st::boxRowPadding,
  1505. });
  1506. }));
  1507. }
  1508. void PeerMenuDeleteTopic(
  1509. not_null<Window::SessionNavigation*> navigation,
  1510. not_null<ChannelData*> channel,
  1511. MsgId rootId) {
  1512. const auto api = &channel->session().api();
  1513. api->request(MTPchannels_DeleteTopicHistory(
  1514. channel->inputChannel,
  1515. MTP_int(rootId)
  1516. )).done([=](const MTPmessages_AffectedHistory &result) {
  1517. const auto offset = api->applyAffectedHistory(channel, result);
  1518. if (offset > 0) {
  1519. PeerMenuDeleteTopic(navigation, channel, rootId);
  1520. } else if (const auto forum = channel->forum()) {
  1521. forum->applyTopicDeleted(rootId);
  1522. }
  1523. }).send();
  1524. }
  1525. void PeerMenuDeleteTopic(
  1526. not_null<Window::SessionNavigation*> navigation,
  1527. not_null<Data::ForumTopic*> topic) {
  1528. PeerMenuDeleteTopic(navigation, topic->channel(), topic->rootId());
  1529. }
  1530. void PeerMenuShareContactBox(
  1531. not_null<Window::SessionNavigation*> navigation,
  1532. not_null<UserData*> user) {
  1533. // There is no async to make weak from controller.
  1534. const auto weak = std::make_shared<QPointer<Ui::BoxContent>>();
  1535. auto callback = [=](not_null<Data::Thread*> thread) {
  1536. const auto peer = thread->peer();
  1537. if (!Data::CanSend(thread, ChatRestriction::SendOther)) {
  1538. navigation->parentController()->show(
  1539. Ui::MakeInformBox(tr::lng_forward_share_cant()));
  1540. return;
  1541. } else if (peer->isSelf()) {
  1542. auto action = Api::SendAction(thread);
  1543. action.clearDraft = false;
  1544. user->session().api().shareContact(user, action);
  1545. navigation->showToast(tr::lng_share_done(tr::now));
  1546. if (auto strong = *weak) {
  1547. strong->closeBox();
  1548. }
  1549. return;
  1550. }
  1551. const auto title = thread->asTopic()
  1552. ? thread->asTopic()->title()
  1553. : peer->name();
  1554. auto recipient = peer->isUser()
  1555. ? title
  1556. : ('\xAB' + title + '\xBB');
  1557. struct State {
  1558. base::weak_ptr<Data::Thread> weak;
  1559. Fn<void(Api::SendOptions)> share;
  1560. SendPaymentHelper sendPayment;
  1561. };
  1562. const auto state = std::make_shared<State>();
  1563. state->weak = thread;
  1564. state->share = [=](Api::SendOptions options) {
  1565. const auto strong = state->weak.get();
  1566. if (!strong) {
  1567. state->share = nullptr;
  1568. return;
  1569. }
  1570. const auto withPaymentApproved = [=](int stars) {
  1571. if (const auto onstack = state->share) {
  1572. auto copy = options;
  1573. copy.starsApproved = stars;
  1574. onstack(copy);
  1575. }
  1576. };
  1577. const auto checked = state->sendPayment.check(
  1578. navigation,
  1579. peer,
  1580. 1,
  1581. options.starsApproved,
  1582. withPaymentApproved);
  1583. if (!checked) {
  1584. return;
  1585. }
  1586. navigation->showThread(
  1587. strong,
  1588. ShowAtTheEndMsgId,
  1589. Window::SectionShow::Way::ClearStack);
  1590. auto action = Api::SendAction(strong, options);
  1591. action.clearDraft = false;
  1592. strong->session().api().shareContact(user, action);
  1593. state->share = nullptr;
  1594. };
  1595. navigation->parentController()->show(
  1596. Ui::MakeConfirmBox({
  1597. .text = tr::lng_forward_share_contact(
  1598. tr::now,
  1599. lt_recipient,
  1600. recipient),
  1601. .confirmed = [state](Fn<void()> &&close) {
  1602. state->share({});
  1603. close();
  1604. },
  1605. .confirmText = tr::lng_forward_send(),
  1606. }));
  1607. };
  1608. *weak = navigation->parentController()->show(
  1609. Box<PeerListBox>(
  1610. std::make_unique<ChooseRecipientBoxController>(
  1611. ChooseRecipientArgs{
  1612. .session = &navigation->session(),
  1613. .callback = std::move(callback),
  1614. .moneyRestrictionError = WriteMoneyRestrictionError,
  1615. }),
  1616. [](not_null<PeerListBox*> box) {
  1617. box->addButton(tr::lng_cancel(), [=] {
  1618. box->closeBox();
  1619. });
  1620. }));
  1621. }
  1622. void PeerMenuCreatePoll(
  1623. not_null<Window::SessionController*> controller,
  1624. not_null<PeerData*> peer,
  1625. FullReplyTo replyTo,
  1626. PollData::Flags chosen,
  1627. PollData::Flags disabled,
  1628. Api::SendType sendType,
  1629. SendMenu::Details sendMenuDetails) {
  1630. if (peer->isChannel() && !peer->isMegagroup()) {
  1631. chosen &= ~PollData::Flag::PublicVotes;
  1632. disabled |= PollData::Flag::PublicVotes;
  1633. }
  1634. auto starsRequired = peer->session().changes().peerFlagsValue(
  1635. peer,
  1636. Data::PeerUpdate::Flag::FullInfo
  1637. | Data::PeerUpdate::Flag::StarsPerMessage
  1638. ) | rpl::map([=] {
  1639. return peer->starsPerMessageChecked();
  1640. });
  1641. auto box = Box<CreatePollBox>(
  1642. controller,
  1643. chosen,
  1644. disabled,
  1645. std::move(starsRequired),
  1646. sendType,
  1647. sendMenuDetails);
  1648. struct State {
  1649. Fn<void(const CreatePollBox::Result &)> create;
  1650. SendPaymentHelper sendPayment;
  1651. bool lock = false;
  1652. };
  1653. const auto weak = QPointer<CreatePollBox>(box);
  1654. const auto state = box->lifetime().make_state<State>();
  1655. state->create = [=](const CreatePollBox::Result &result) {
  1656. const auto withPaymentApproved = crl::guard(weak, [=](int stars) {
  1657. if (const auto onstack = state->create) {
  1658. auto copy = result;
  1659. copy.options.starsApproved = stars;
  1660. onstack(copy);
  1661. }
  1662. });
  1663. const auto checked = state->sendPayment.check(
  1664. controller,
  1665. peer,
  1666. 1,
  1667. result.options.starsApproved,
  1668. withPaymentApproved);
  1669. if (!checked || std::exchange(state->lock, true)) {
  1670. return;
  1671. }
  1672. auto action = Api::SendAction(
  1673. peer->owner().history(peer),
  1674. result.options);
  1675. action.replyTo = replyTo;
  1676. const auto topicRootId = replyTo.topicRootId;
  1677. if (const auto local = action.history->localDraft(topicRootId)) {
  1678. action.clearDraft = local->textWithTags.text.isEmpty();
  1679. } else {
  1680. action.clearDraft = false;
  1681. }
  1682. const auto api = &peer->session().api();
  1683. api->polls().create(result.poll, action, crl::guard(weak, [=] {
  1684. state->create = nullptr;
  1685. weak->closeBox();
  1686. }), crl::guard(weak, [=] {
  1687. state->lock = false;
  1688. weak->submitFailed(tr::lng_attach_failed(tr::now));
  1689. }));
  1690. };
  1691. box->submitRequests(
  1692. ) | rpl::start_with_next(state->create, box->lifetime());
  1693. controller->show(std::move(box), Ui::LayerOption::CloseOther);
  1694. }
  1695. void PeerMenuBlockUserBox(
  1696. not_null<Ui::GenericBox*> box,
  1697. not_null<Window::Controller*> window,
  1698. not_null<PeerData*> peer,
  1699. std::variant<v::null_t, bool> suggestReport,
  1700. std::variant<v::null_t, ClearChat, ClearReply> suggestClear) {
  1701. const auto settings = peer->barSettings().value_or(PeerBarSettings(0));
  1702. const auto reportNeeded = v::is_null(suggestReport)
  1703. ? ((settings & PeerBarSetting::ReportSpam) != 0)
  1704. : v::get<bool>(suggestReport);
  1705. const auto user = peer->asUser();
  1706. const auto name = user ? user->shortName() : peer->name();
  1707. if (user) {
  1708. box->addRow(object_ptr<Ui::FlatLabel>(
  1709. box,
  1710. tr::lng_blocked_list_confirm_text(
  1711. lt_name,
  1712. rpl::single(Ui::Text::Bold(name)),
  1713. Ui::Text::WithEntities),
  1714. st::blockUserConfirmation));
  1715. box->addSkip(st::boxMediumSkip);
  1716. }
  1717. const auto report = reportNeeded
  1718. ? box->addRow(object_ptr<Ui::Checkbox>(
  1719. box,
  1720. tr::lng_report_spam(tr::now),
  1721. true,
  1722. st::defaultBoxCheckbox))
  1723. : nullptr;
  1724. if (report) {
  1725. box->addSkip(st::boxMediumSkip);
  1726. }
  1727. const auto clear = v::is<ClearChat>(suggestClear)
  1728. ? box->addRow(object_ptr<Ui::Checkbox>(
  1729. box,
  1730. tr::lng_blocked_list_confirm_clear(tr::now),
  1731. true,
  1732. st::defaultBoxCheckbox))
  1733. : v::is<ClearReply>(suggestClear)
  1734. ? box->addRow(object_ptr<Ui::Checkbox>(
  1735. box,
  1736. tr::lng_context_delete_msg(tr::now),
  1737. true,
  1738. st::defaultBoxCheckbox))
  1739. : nullptr;
  1740. if (clear) {
  1741. box->addSkip(st::boxMediumSkip);
  1742. }
  1743. const auto allFromUser = v::is<ClearReply>(suggestClear)
  1744. ? box->addRow(object_ptr<Ui::Checkbox>(
  1745. box,
  1746. tr::lng_delete_all_from_user(
  1747. tr::now,
  1748. lt_user,
  1749. Ui::Text::Bold(peer->name()),
  1750. Ui::Text::WithEntities),
  1751. true,
  1752. st::defaultBoxCheckbox))
  1753. : nullptr;
  1754. if (allFromUser) {
  1755. box->addSkip(st::boxLittleSkip);
  1756. }
  1757. box->setTitle(tr::lng_blocked_list_confirm_title(
  1758. lt_name,
  1759. rpl::single(name)));
  1760. box->addButton(tr::lng_blocked_list_confirm_ok(), [=] {
  1761. const auto reportChecked = report && report->checked();
  1762. const auto clearChecked = clear && clear->checked();
  1763. const auto fromUserChecked = allFromUser && allFromUser->checked();
  1764. box->closeBox();
  1765. if (const auto clearReply = std::get_if<ClearReply>(&suggestClear)) {
  1766. using Flag = MTPcontacts_BlockFromReplies::Flag;
  1767. peer->session().api().request(MTPcontacts_BlockFromReplies(
  1768. MTP_flags((clearChecked ? Flag::f_delete_message : Flag(0))
  1769. | (fromUserChecked ? Flag::f_delete_history : Flag(0))
  1770. | (reportChecked ? Flag::f_report_spam : Flag(0))),
  1771. MTP_int(clearReply->replyId.msg)
  1772. )).done([=](const MTPUpdates &result) {
  1773. peer->session().updates().applyUpdates(result);
  1774. }).send();
  1775. } else {
  1776. peer->session().api().blockedPeers().block(peer);
  1777. if (reportChecked) {
  1778. peer->session().api().request(MTPmessages_ReportSpam(
  1779. peer->input
  1780. )).send();
  1781. }
  1782. if (clearChecked) {
  1783. crl::on_main(&peer->session(), [=] {
  1784. peer->session().api().deleteConversation(peer, false);
  1785. });
  1786. window->sessionController()->showBackFromStack();
  1787. }
  1788. }
  1789. window->showToast(
  1790. tr::lng_new_contact_block_done(tr::now, lt_user, name));
  1791. }, st::attentionBoxButton);
  1792. box->addButton(tr::lng_cancel(), [=] {
  1793. box->closeBox();
  1794. });
  1795. }
  1796. void PeerMenuUnblockUserWithBotRestart(
  1797. std::shared_ptr<Ui::Show> show,
  1798. not_null<UserData*> user) {
  1799. user->session().api().blockedPeers().unblock(user, [=](bool success) {
  1800. if (success && user->isBot() && !user->isSupport()) {
  1801. user->session().api().sendBotStart(show, user);
  1802. }
  1803. });
  1804. }
  1805. void BlockSenderFromRepliesBox(
  1806. not_null<Ui::GenericBox*> box,
  1807. not_null<SessionController*> controller,
  1808. FullMsgId id) {
  1809. const auto item = controller->session().data().message(id);
  1810. Assert(item != nullptr);
  1811. PeerMenuBlockUserBox(
  1812. box,
  1813. &controller->window(),
  1814. item->originalSender(),
  1815. true,
  1816. Window::ClearReply{ id });
  1817. }
  1818. object_ptr<Ui::BoxContent> PrepareChooseRecipientBox(
  1819. not_null<Main::Session*> session,
  1820. FnMut<bool(not_null<Data::Thread*>)> &&chosen,
  1821. rpl::producer<QString> titleOverride,
  1822. FnMut<void()> &&successCallback,
  1823. InlineBots::PeerTypes typesRestriction,
  1824. Fn<void(
  1825. std::vector<not_null<Data::Thread*>>,
  1826. Api::SendOptions)> sendMany) {
  1827. const auto weak = std::make_shared<QPointer<PeerListBox>>();
  1828. const auto selectable = (sendMany != nullptr);
  1829. class Controller final : public ChooseRecipientBoxController {
  1830. public:
  1831. using Chosen = not_null<Data::Thread*>;
  1832. Controller(
  1833. not_null<Main::Session*> session,
  1834. FnMut<void(Chosen)> callback,
  1835. Fn<bool(Chosen)> filter,
  1836. bool selectable)
  1837. : ChooseRecipientBoxController({
  1838. .session = session,
  1839. .callback = std::move(callback),
  1840. .filter = filter,
  1841. .moneyRestrictionError = WriteMoneyRestrictionError,
  1842. })
  1843. , _selectable(selectable) {
  1844. }
  1845. using PeerListController::setSearchNoResultsText;
  1846. void rowClicked(not_null<PeerListRow*> row) override final {
  1847. if (!_selectable) {
  1848. return ChooseRecipientBoxController::rowClicked(row);
  1849. }
  1850. const auto count = delegate()->peerListSelectedRowsCount();
  1851. if (showLockedError(row) || (count && row->peer()->isForum())) {
  1852. return;
  1853. } else if (row->peer()->isForum()) {
  1854. ChooseRecipientBoxController::rowClicked(row);
  1855. } else {
  1856. delegate()->peerListSetRowChecked(row, !row->checked());
  1857. _selectionChanges.fire({});
  1858. }
  1859. }
  1860. base::unique_qptr<Ui::PopupMenu> rowContextMenu(
  1861. QWidget *parent,
  1862. not_null<PeerListRow*> row) override final {
  1863. if (!_selectable) {
  1864. return ChooseRecipientBoxController::rowContextMenu(
  1865. parent,
  1866. row);
  1867. }
  1868. if (!row->checked() && !row->peer()->isForum()) {
  1869. auto menu = base::make_unique_q<Ui::PopupMenu>(
  1870. parent,
  1871. st::popupMenuWithIcons);
  1872. menu->addAction(tr::lng_bot_choose_chat(tr::now), [=] {
  1873. delegate()->peerListSetRowChecked(row, true);
  1874. _selectionChanges.fire({});
  1875. }, &st::menuIconSelect);
  1876. return menu;
  1877. }
  1878. return nullptr;
  1879. }
  1880. [[nodiscard]] rpl::producer<> selectionChanges() const {
  1881. return _selectionChanges.events_starting_with({});
  1882. }
  1883. [[nodiscard]] bool hasSelected() const {
  1884. return delegate()->peerListSelectedRowsCount() > 0;
  1885. }
  1886. [[nodiscard]] rpl::producer<Chosen> singleChosen() const {
  1887. return _singleChosen.events();
  1888. }
  1889. private:
  1890. rpl::event_stream<Chosen> _singleChosen;
  1891. rpl::event_stream<> _selectionChanges;
  1892. bool _selectable = false;
  1893. };
  1894. auto callback = [
  1895. chosen = std::move(chosen),
  1896. success = std::move(successCallback),
  1897. weak
  1898. ](not_null<Data::Thread*> thread) mutable {
  1899. if (!chosen(thread)) {
  1900. return;
  1901. } else if (const auto strong = *weak) {
  1902. strong->closeBox();
  1903. }
  1904. if (success) {
  1905. success();
  1906. }
  1907. };
  1908. auto filter = typesRestriction
  1909. ? [=](not_null<Data::Thread*> thread) -> bool {
  1910. using namespace InlineBots;
  1911. const auto peer = thread->peer();
  1912. if (const auto user = peer->asUser()) {
  1913. if (user->isBot()) {
  1914. return (typesRestriction & PeerType::Bot);
  1915. } else {
  1916. return (typesRestriction & PeerType::User);
  1917. }
  1918. } else if (peer->isBroadcast()) {
  1919. return (typesRestriction & PeerType::Broadcast);
  1920. } else {
  1921. return (typesRestriction & PeerType::Group);
  1922. }
  1923. }
  1924. : Fn<bool(not_null<Data::Thread*>)>();
  1925. auto controller = std::make_unique<Controller>(
  1926. session,
  1927. std::move(callback),
  1928. std::move(filter),
  1929. selectable);
  1930. const auto raw = controller.get();
  1931. struct State {
  1932. Fn<void(Api::SendOptions)> submit;
  1933. rpl::variable<int> starsToSend;
  1934. Fn<void()> refreshStarsToSend;
  1935. rpl::lifetime submitLifetime;
  1936. };
  1937. const auto state = std::make_shared<State>();
  1938. auto initBox = [=](not_null<PeerListBox*> box) {
  1939. state->refreshStarsToSend = [=] {
  1940. auto perMessage = 0;
  1941. for (const auto &peer : box->collectSelectedRows()) {
  1942. perMessage += peer->starsPerMessageChecked();
  1943. }
  1944. state->starsToSend = perMessage;
  1945. };
  1946. raw->selectionChanges(
  1947. ) | rpl::start_with_next([=] {
  1948. box->clearButtons();
  1949. state->refreshStarsToSend();
  1950. const auto shown = raw->hasSelected();
  1951. if (shown) {
  1952. const auto weak = Ui::MakeWeak(box);
  1953. state->submit = [=](Api::SendOptions options) {
  1954. state->submitLifetime.destroy();
  1955. const auto show = box->peerListUiShow();
  1956. const auto peers = box->collectSelectedRows();
  1957. const auto withPaymentApproved = crl::guard(weak, [=](
  1958. int approved) {
  1959. auto copy = options;
  1960. copy.starsApproved = approved;
  1961. if (const auto onstack = state->submit) {
  1962. onstack(copy);
  1963. }
  1964. });
  1965. const auto alreadyApproved = options.starsApproved;
  1966. auto paid = std::vector<not_null<PeerData*>>();
  1967. auto waiting = base::flat_set<not_null<PeerData*>>();
  1968. auto totalStars = 0;
  1969. for (const auto &peer : peers) {
  1970. const auto details = ComputePaymentDetails(peer, 1);
  1971. if (!details) {
  1972. waiting.emplace(peer);
  1973. } else if (details->stars > 0) {
  1974. totalStars += details->stars;
  1975. paid.push_back(peer);
  1976. }
  1977. }
  1978. if (!waiting.empty()) {
  1979. session->changes().peerUpdates(
  1980. Data::PeerUpdate::Flag::FullInfo
  1981. ) | rpl::start_with_next([=](const Data::PeerUpdate &update) {
  1982. if (waiting.contains(update.peer)) {
  1983. withPaymentApproved(alreadyApproved);
  1984. }
  1985. }, state->submitLifetime);
  1986. if (!session->credits().loaded()) {
  1987. session->credits().loadedValue(
  1988. ) | rpl::filter(
  1989. rpl::mappers::_1
  1990. ) | rpl::take(1) | rpl::start_with_next([=] {
  1991. withPaymentApproved(alreadyApproved);
  1992. }, state->submitLifetime);
  1993. }
  1994. return;
  1995. } else if (totalStars > alreadyApproved) {
  1996. ShowSendPaidConfirm(show, paid, SendPaymentDetails{
  1997. .messages = 1,
  1998. .stars = totalStars,
  1999. }, [=] { withPaymentApproved(totalStars); });
  2000. return;
  2001. }
  2002. state->submit = nullptr;
  2003. sendMany(ranges::views::all(
  2004. peers
  2005. ) | ranges::views::transform([&](
  2006. not_null<PeerData*> peer) -> Controller::Chosen {
  2007. return peer->owner().history(peer);
  2008. }) | ranges::to_vector, options);
  2009. };
  2010. const auto send = box->addButton(
  2011. tr::lng_send_button(),
  2012. [=] {
  2013. if (const auto onstack = state->submit) {
  2014. onstack({});
  2015. }
  2016. });
  2017. send->setText(PaidSendButtonText(
  2018. state->starsToSend.value(),
  2019. tr::lng_send_button()));
  2020. }
  2021. box->addButton(tr::lng_cancel(), [=] {
  2022. box->closeBox();
  2023. });
  2024. }, box->lifetime());
  2025. if (titleOverride) {
  2026. box->setTitle(std::move(titleOverride));
  2027. }
  2028. };
  2029. auto result = Box<PeerListBox>(
  2030. std::move(controller),
  2031. std::move(initBox));
  2032. *weak = result.data();
  2033. return result;
  2034. }
  2035. QPointer<Ui::BoxContent> ShowChooseRecipientBox(
  2036. not_null<Window::SessionNavigation*> navigation,
  2037. FnMut<bool(not_null<Data::Thread*>)> &&chosen,
  2038. rpl::producer<QString> titleOverride,
  2039. FnMut<void()> &&successCallback,
  2040. InlineBots::PeerTypes typesRestriction) {
  2041. return navigation->parentController()->show(PrepareChooseRecipientBox(
  2042. &navigation->session(),
  2043. std::move(chosen),
  2044. std::move(titleOverride),
  2045. std::move(successCallback),
  2046. typesRestriction));
  2047. }
  2048. QPointer<Ui::BoxContent> ShowForwardMessagesBox(
  2049. std::shared_ptr<ChatHelpers::Show> show,
  2050. Data::ForwardDraft &&draft,
  2051. Fn<void()> &&successCallback) {
  2052. const auto session = &show->session();
  2053. const auto owner = &session->data();
  2054. const auto itemsList = owner->idsToItems(draft.ids);
  2055. const auto msgIds = owner->itemsToIds(itemsList);
  2056. const auto sendersCount = ItemsForwardSendersCount(itemsList);
  2057. const auto captionsCount = ItemsForwardCaptionsCount(itemsList);
  2058. if (msgIds.empty()) {
  2059. return nullptr;
  2060. }
  2061. class ListBox final : public PeerListBox {
  2062. public:
  2063. ListBox(
  2064. QWidget *parent,
  2065. std::unique_ptr<PeerListController> controller,
  2066. Fn<void(not_null<ListBox*>)> init)
  2067. : PeerListBox(
  2068. parent,
  2069. std::move(controller),
  2070. [=](not_null<PeerListBox*> box) {
  2071. init(static_cast<ListBox*>(box.get()));
  2072. }) {
  2073. }
  2074. void setBottomSkip(int bottomSkip) {
  2075. PeerListBox::setInnerBottomSkip(bottomSkip);
  2076. }
  2077. [[nodiscard]] rpl::producer<> focusRequests() const {
  2078. return _focusRequests.events();
  2079. }
  2080. [[nodiscard]] Data::ForwardOptions forwardOptionsData() const {
  2081. return (_forwardOptions.captionsCount
  2082. && _forwardOptions.dropCaptions)
  2083. ? Data::ForwardOptions::NoNamesAndCaptions
  2084. : _forwardOptions.dropNames
  2085. ? Data::ForwardOptions::NoSenderNames
  2086. : Data::ForwardOptions::PreserveInfo;
  2087. }
  2088. [[nodiscard]] Ui::ForwardOptions forwardOptions() const {
  2089. return _forwardOptions;
  2090. }
  2091. void setForwardOptions(Ui::ForwardOptions forwardOptions) {
  2092. _forwardOptions = forwardOptions;
  2093. }
  2094. not_null<PeerListContent*> peerListContent() const {
  2095. return PeerListBox::content();
  2096. }
  2097. void setFilterId(FilterId filterId) {
  2098. _filterId = filterId;
  2099. }
  2100. [[nodiscard]] FilterId filterId() const {
  2101. return _filterId;
  2102. }
  2103. private:
  2104. rpl::event_stream<> _focusRequests;
  2105. Ui::ForwardOptions _forwardOptions;
  2106. FilterId _filterId = 0;
  2107. };
  2108. class Controller final : public ChooseRecipientBoxController {
  2109. public:
  2110. using Chosen = not_null<Data::Thread*>;
  2111. Controller(not_null<Main::Session*> session)
  2112. : ChooseRecipientBoxController({
  2113. .session = session,
  2114. .callback = [=](Chosen thread) {
  2115. _singleChosen.fire_copy(thread);
  2116. },
  2117. .moneyRestrictionError = WriteMoneyRestrictionError,
  2118. }) {
  2119. }
  2120. std::unique_ptr<PeerListRow> createRestoredRow(
  2121. not_null<PeerData*> peer) override final {
  2122. return ChooseRecipientBoxController::createRow(
  2123. peer->owner().history(peer));
  2124. }
  2125. using PeerListController::setSearchNoResultsText;
  2126. void rowClicked(not_null<PeerListRow*> row) override final {
  2127. const auto count = delegate()->peerListSelectedRowsCount();
  2128. if (showLockedError(row) || (count && row->peer()->isForum())) {
  2129. return;
  2130. } else if (!count || row->peer()->isForum()) {
  2131. ChooseRecipientBoxController::rowClicked(row);
  2132. } else if (count) {
  2133. delegate()->peerListSetRowChecked(row, !row->checked());
  2134. _selectionChanges.fire({});
  2135. }
  2136. }
  2137. base::unique_qptr<Ui::PopupMenu> rowContextMenu(
  2138. QWidget *parent,
  2139. not_null<PeerListRow*> row) override final {
  2140. if (!row->checked() && !row->peer()->isForum()) {
  2141. auto menu = base::make_unique_q<Ui::PopupMenu>(
  2142. parent,
  2143. st::popupMenuWithIcons);
  2144. menu->addAction(tr::lng_bot_choose_chat(tr::now), [=] {
  2145. delegate()->peerListSetRowChecked(row, true);
  2146. _selectionChanges.fire({});
  2147. }, &st::menuIconSelect);
  2148. return menu;
  2149. }
  2150. return nullptr;
  2151. }
  2152. [[nodiscard]] rpl::producer<> selectionChanges() const {
  2153. return _selectionChanges.events_starting_with({});
  2154. }
  2155. [[nodiscard]] bool hasSelected() const {
  2156. return delegate()->peerListSelectedRowsCount() > 0;
  2157. }
  2158. [[nodiscard]] rpl::producer<Chosen> singleChosen() const{
  2159. return _singleChosen.events();
  2160. }
  2161. private:
  2162. rpl::event_stream<Chosen> _singleChosen;
  2163. rpl::event_stream<> _selectionChanges;
  2164. };
  2165. struct State {
  2166. not_null<ListBox*> box;
  2167. not_null<Controller*> controller;
  2168. base::unique_qptr<Ui::PopupMenu> menu;
  2169. Fn<void(Api::SendOptions options)> submit;
  2170. rpl::variable<int> starsToSend;
  2171. Fn<void()> refreshStarsToSend;
  2172. rpl::lifetime submitLifetime;
  2173. };
  2174. const auto applyFilter = [=](not_null<ListBox*> box, FilterId id) {
  2175. box->scrollToY(0);
  2176. auto &filters = session->data().chatsFilters();
  2177. const auto &list = filters.list();
  2178. if (list.size() <= 1) {
  2179. return;
  2180. }
  2181. if (box->filterId() == id) {
  2182. return;
  2183. }
  2184. box->setFilterId(id);
  2185. using SavedState = PeerListController::SavedStateBase;
  2186. auto state = std::make_unique<PeerListState>();
  2187. state->controllerState = std::make_unique<SavedState>();
  2188. const auto addList = [&](auto chats) {
  2189. for (const auto &row : chats->all()) {
  2190. if (const auto history = row->history()) {
  2191. state->list.push_back(history->peer);
  2192. }
  2193. }
  2194. };
  2195. if (!id) {
  2196. state->list.push_back(session->user());
  2197. addList(session->data().chatsList()->indexed());
  2198. const auto folderId = Data::Folder::kId;
  2199. if (const auto folder = session->data().folderLoaded(folderId)) {
  2200. addList(folder->chatsList()->indexed());
  2201. }
  2202. addList(session->data().contactsNoChatsList());
  2203. } else {
  2204. addList(session->data().chatsFilters().chatsList(id)->indexed());
  2205. }
  2206. box->peerListContent()->restoreState(std::move(state));
  2207. };
  2208. const auto state = [&] {
  2209. auto controller = std::make_unique<Controller>(session);
  2210. const auto controllerRaw = controller.get();
  2211. auto init = [=](not_null<ListBox*> box) {
  2212. controllerRaw->setSearchNoResultsText(
  2213. tr::lng_bot_chats_not_found(tr::now));
  2214. const auto lastFilterId = box->lifetime().make_state<FilterId>(0);
  2215. const auto chatsFilters = Ui::AddChatFiltersTabsStrip(
  2216. box,
  2217. session,
  2218. [=](FilterId id) {
  2219. *lastFilterId = id;
  2220. applyFilter(box, id);
  2221. },
  2222. Window::GifPauseReason::Layer);
  2223. chatsFilters->lower();
  2224. rpl::combine(
  2225. chatsFilters->heightValue(),
  2226. rpl::producer<bool>([=](auto consumer) {
  2227. auto lifetime = rpl::lifetime();
  2228. consumer.put_next(false);
  2229. box->appendQueryChangedCallback([=](const QString &q) {
  2230. const auto hasQuery = !q.isEmpty();
  2231. applyFilter(box, hasQuery ? 0 : (*lastFilterId));
  2232. consumer.put_next_copy(hasQuery);
  2233. });
  2234. return lifetime;
  2235. })
  2236. ) | rpl::start_with_next([box](int h, bool hasQuery) {
  2237. box->setAddedTopScrollSkip(hasQuery ? 0 : h);
  2238. }, box->lifetime());
  2239. box->multiSelectHeightValue() | rpl::start_with_next([=](int h) {
  2240. chatsFilters->moveToLeft(0, h);
  2241. }, chatsFilters->lifetime());
  2242. };
  2243. auto box = Box<ListBox>(std::move(controller), std::move(init));
  2244. const auto boxRaw = box.data();
  2245. boxRaw->setForwardOptions({
  2246. .sendersCount = sendersCount,
  2247. .captionsCount = captionsCount,
  2248. });
  2249. show->showBox(std::move(box));
  2250. auto state = State{ boxRaw, controllerRaw };
  2251. return boxRaw->lifetime().make_state<State>(std::move(state));
  2252. }();
  2253. { // Chosen a single.
  2254. auto chosen = [show, draft = std::move(draft)](
  2255. not_null<Data::Thread*> thread) mutable {
  2256. const auto peer = thread->peer();
  2257. if (peer->isSelf()
  2258. && !draft.ids.empty()
  2259. && draft.ids.front().peer != peer->id) {
  2260. ForwardToSelf(show, draft);
  2261. return true;
  2262. }
  2263. const auto id = SeparateId(
  2264. (peer->isForum()
  2265. ? SeparateType::Forum
  2266. : SeparateType::Chat),
  2267. thread);
  2268. auto controller = Core::App().windowFor(id);
  2269. if (!controller) {
  2270. return false;
  2271. }
  2272. if (controller->maybeSession() != &peer->session()) {
  2273. controller = Core::App().ensureSeparateWindowFor(id);
  2274. if (controller->maybeSession() != &peer->session()) {
  2275. return false;
  2276. }
  2277. }
  2278. const auto content = controller->sessionController()->content();
  2279. return content->setForwardDraft(thread, std::move(draft));
  2280. };
  2281. auto callback = [=, chosen = std::move(chosen)](
  2282. Controller::Chosen thread) mutable {
  2283. const auto weak = Ui::MakeWeak(state->box);
  2284. if (!chosen(thread)) {
  2285. return;
  2286. } else if (const auto strong = weak.data()) {
  2287. strong->closeBox();
  2288. }
  2289. if (successCallback) {
  2290. successCallback();
  2291. }
  2292. };
  2293. state->controller->singleChosen(
  2294. ) | rpl::start_with_next(std::move(callback), state->box->lifetime());
  2295. }
  2296. const auto comment = Ui::CreateChild<Ui::SlideWrap<Ui::InputField>>(
  2297. state->box.get(),
  2298. object_ptr<Ui::InputField>(
  2299. state->box,
  2300. st::shareComment,
  2301. Ui::InputField::Mode::MultiLine,
  2302. tr::lng_photos_comment()),
  2303. st::shareCommentPadding);
  2304. const auto history = session->data().message(msgIds.front())->history();
  2305. const auto send = ShareBox::DefaultForwardCallback(
  2306. show,
  2307. history,
  2308. msgIds);
  2309. const auto countMessages = ShareBox::DefaultForwardCountMessages(
  2310. history,
  2311. msgIds);
  2312. const auto weak = Ui::MakeWeak(state->box);
  2313. const auto field = comment->entity();
  2314. state->submit = [=](Api::SendOptions options) {
  2315. const auto peers = state->box->collectSelectedRows();
  2316. auto comment = field->getTextWithAppliedMarkdown();
  2317. const auto checkPaid = [=] {
  2318. const auto withPaymentApproved = crl::guard(weak, [=](
  2319. int approved) {
  2320. auto copy = options;
  2321. copy.starsApproved = approved;
  2322. if (const auto onstack = state->submit) {
  2323. onstack(copy);
  2324. }
  2325. });
  2326. const auto alreadyApproved = options.starsApproved;
  2327. const auto messagesCount = countMessages(comment);
  2328. auto paid = std::vector<not_null<PeerData*>>();
  2329. auto waiting = base::flat_set<not_null<PeerData*>>();
  2330. auto totalStars = 0;
  2331. for (const auto &peer : peers) {
  2332. const auto details = ComputePaymentDetails(
  2333. peer,
  2334. messagesCount);
  2335. if (!details) {
  2336. waiting.emplace(peer);
  2337. } else if (details->stars > 0) {
  2338. totalStars += details->stars;
  2339. paid.push_back(peer);
  2340. }
  2341. }
  2342. if (!waiting.empty()) {
  2343. session->changes().peerUpdates(
  2344. Data::PeerUpdate::Flag::FullInfo
  2345. ) | rpl::start_with_next([=](const Data::PeerUpdate &update) {
  2346. if (waiting.contains(update.peer)) {
  2347. withPaymentApproved(alreadyApproved);
  2348. }
  2349. }, state->submitLifetime);
  2350. if (!session->credits().loaded()) {
  2351. session->credits().loadedValue(
  2352. ) | rpl::filter(
  2353. rpl::mappers::_1
  2354. ) | rpl::take(1) | rpl::start_with_next([=] {
  2355. withPaymentApproved(alreadyApproved);
  2356. }, state->submitLifetime);
  2357. }
  2358. return false;
  2359. } else if (totalStars > alreadyApproved) {
  2360. ShowSendPaidConfirm(show, paid, SendPaymentDetails{
  2361. .messages = messagesCount,
  2362. .stars = totalStars,
  2363. }, [=] { withPaymentApproved(totalStars); });
  2364. return false;
  2365. }
  2366. state->submit = nullptr;
  2367. return true;
  2368. };
  2369. send(
  2370. ranges::views::all(
  2371. peers
  2372. ) | ranges::views::transform([&](
  2373. not_null<PeerData*> peer) -> Controller::Chosen {
  2374. return peer->owner().history(peer);
  2375. }) | ranges::to_vector,
  2376. checkPaid,
  2377. std::move(comment),
  2378. options,
  2379. state->box->forwardOptionsData());
  2380. if (!state->submit && successCallback) {
  2381. successCallback();
  2382. }
  2383. };
  2384. const auto sendMenuType = [=] {
  2385. const auto selected = state->box->collectSelectedRows();
  2386. const auto hasPaid = [&] {
  2387. for (const auto peer : selected) {
  2388. if (peer->starsPerMessageChecked()) {
  2389. return true;
  2390. }
  2391. }
  2392. return false;
  2393. }();
  2394. return hasPaid
  2395. ? SendMenu::Type::SilentOnly
  2396. : ranges::all_of(selected, HistoryView::CanScheduleUntilOnline)
  2397. ? SendMenu::Type::ScheduledToUser
  2398. : ((selected.size() == 1) && selected.front()->isSelf())
  2399. ? SendMenu::Type::Reminder
  2400. : SendMenu::Type::Scheduled;
  2401. };
  2402. const auto showForwardOptions = true;
  2403. const auto showMenu = [=](not_null<Ui::RpWidget*> parent) {
  2404. if (state->menu) {
  2405. state->menu = nullptr;
  2406. return;
  2407. }
  2408. state->menu.emplace(parent, st::popupMenuWithIcons);
  2409. if (showForwardOptions) {
  2410. auto createView = [&](
  2411. rpl::producer<QString> &&text,
  2412. bool checked) {
  2413. auto item = base::make_unique_q<Menu::ItemWithCheck>(
  2414. state->menu->menu(),
  2415. st::popupMenuWithIcons.menu,
  2416. Ui::CreateChild<QAction>(state->menu->menu().get()),
  2417. nullptr,
  2418. nullptr);
  2419. std::move(
  2420. text
  2421. ) | rpl::start_with_next([action = item->action()](
  2422. QString text) {
  2423. action->setText(text);
  2424. }, item->lifetime());
  2425. item->init(checked);
  2426. const auto view = item->checkView();
  2427. state->menu->addAction(std::move(item));
  2428. return view;
  2429. };
  2430. Ui::FillForwardOptions(
  2431. std::move(createView),
  2432. state->box->forwardOptions(),
  2433. [=](Ui::ForwardOptions o) {
  2434. state->box->setForwardOptions(o);
  2435. },
  2436. state->menu->lifetime());
  2437. state->menu->addSeparator();
  2438. }
  2439. state->menu->setForcedVerticalOrigin(
  2440. Ui::PopupMenu::VerticalOrigin::Bottom);
  2441. SendMenu::FillSendMenu(
  2442. state->menu.get(),
  2443. show,
  2444. SendMenu::Details{ sendMenuType() },
  2445. SendMenu::DefaultCallback(show, crl::guard(parent, [=](
  2446. Api::SendOptions options) {
  2447. if (const auto onstack = state->submit) {
  2448. onstack(options);
  2449. }
  2450. })));
  2451. if (showForwardOptions || !state->menu->empty()) {
  2452. state->menu->popup(QCursor::pos());
  2453. }
  2454. };
  2455. state->refreshStarsToSend = [=] {
  2456. auto perMessage = 0;
  2457. for (const auto &peer : state->box->collectSelectedRows()) {
  2458. perMessage += peer->starsPerMessageChecked();
  2459. }
  2460. state->starsToSend = perMessage
  2461. * countMessages(field->getTextWithTags());
  2462. };
  2463. comment->hide(anim::type::instant);
  2464. comment->toggleOn(state->controller->selectionChanges(
  2465. ) | rpl::map([=] {
  2466. return state->controller->hasSelected();
  2467. }));
  2468. rpl::combine(
  2469. state->box->sizeValue(),
  2470. comment->heightValue()
  2471. ) | rpl::start_with_next([=](const QSize &size, int commentHeight) {
  2472. comment->moveToLeft(0, size.height() - commentHeight);
  2473. comment->resizeToWidth(size.width());
  2474. state->box->setBottomSkip(comment->isHidden() ? 0 : commentHeight);
  2475. }, comment->lifetime());
  2476. field->submits(
  2477. ) | rpl::start_with_next([=] {
  2478. if (const auto onstack = state->submit) {
  2479. onstack({});
  2480. }
  2481. }, field->lifetime());
  2482. InitMessageFieldHandlers({
  2483. .session = session,
  2484. .show = show,
  2485. .field = field,
  2486. .customEmojiPaused = [=] {
  2487. return show->paused(GifPauseReason::Layer);
  2488. },
  2489. });
  2490. field->setSubmitSettings(Core::App().settings().sendSubmitWay());
  2491. field->changes() | rpl::start_with_next([=] {
  2492. state->refreshStarsToSend();
  2493. }, field->lifetime());
  2494. Ui::SendPendingMoveResizeEvents(comment);
  2495. state->box->focusRequests(
  2496. ) | rpl::start_with_next([=] {
  2497. if (!comment->isHidden()) {
  2498. comment->entity()->setFocusFast();
  2499. }
  2500. }, comment->lifetime());
  2501. state->controller->selectionChanges(
  2502. ) | rpl::start_with_next([=] {
  2503. const auto shown = state->controller->hasSelected();
  2504. state->box->clearButtons();
  2505. state->refreshStarsToSend();
  2506. if (shown) {
  2507. const auto send = state->box->addButton(
  2508. tr::lng_send_button(),
  2509. [=] {
  2510. if (const auto onstack = state->submit) {
  2511. onstack({});
  2512. }
  2513. });
  2514. send->setAcceptBoth();
  2515. send->clicks(
  2516. ) | rpl::start_with_next([=](Qt::MouseButton button) {
  2517. if (button == Qt::RightButton) {
  2518. showMenu(send);
  2519. }
  2520. }, send->lifetime());
  2521. send->setText(PaidSendButtonText(
  2522. state->starsToSend.value(),
  2523. tr::lng_send_button()));
  2524. }
  2525. state->box->addButton(tr::lng_cancel(), [=] {
  2526. state->box->closeBox();
  2527. });
  2528. }, state->box->lifetime());
  2529. return QPointer<Ui::BoxContent>(state->box);
  2530. }
  2531. QPointer<Ui::BoxContent> ShowForwardMessagesBox(
  2532. not_null<Window::SessionNavigation*> navigation,
  2533. Data::ForwardDraft &&draft,
  2534. Fn<void()> &&successCallback) {
  2535. return ShowForwardMessagesBox(
  2536. navigation->uiShow(),
  2537. std::move(draft),
  2538. std::move(successCallback));
  2539. }
  2540. QPointer<Ui::BoxContent> ShowForwardMessagesBox(
  2541. not_null<Window::SessionNavigation*> navigation,
  2542. MessageIdsList &&items,
  2543. Fn<void()> &&successCallback) {
  2544. return ShowForwardMessagesBox(
  2545. navigation,
  2546. Data::ForwardDraft{ .ids = std::move(items) },
  2547. std::move(successCallback));
  2548. }
  2549. QPointer<Ui::BoxContent> ShowShareGameBox(
  2550. not_null<Window::SessionNavigation*> navigation,
  2551. not_null<UserData*> bot,
  2552. QString shortName) {
  2553. const auto weak = std::make_shared<QPointer<Ui::BoxContent>>();
  2554. auto chosen = [=](not_null<Data::Thread*> thread) mutable {
  2555. const auto confirm = std::make_shared<QPointer<Ui::BoxContent>>();
  2556. auto send = crl::guard(thread, [=] {
  2557. ShareBotGame(bot, thread, shortName);
  2558. if (const auto strong = *weak) {
  2559. strong->closeBox();
  2560. }
  2561. if (const auto strong = *confirm) {
  2562. strong->closeBox();
  2563. }
  2564. navigation->showThread(
  2565. thread,
  2566. ShowAtUnreadMsgId,
  2567. SectionShow::Way::ClearStack);
  2568. });
  2569. const auto confirmText = thread->peer()->isUser()
  2570. ? tr::lng_bot_sure_share_game(
  2571. tr::now,
  2572. lt_user,
  2573. thread->chatListName())
  2574. : tr::lng_bot_sure_share_game_group(
  2575. tr::now,
  2576. lt_group,
  2577. thread->chatListName());
  2578. *confirm = navigation->parentController()->show(
  2579. Ui::MakeConfirmBox({
  2580. .text = confirmText,
  2581. .confirmed = std::move(send),
  2582. }));
  2583. };
  2584. auto filter = [](not_null<Data::Thread*> thread) {
  2585. return !thread->peer()->isSelf()
  2586. && (Data::CanSend(thread, ChatRestriction::SendGames)
  2587. || thread->asForum());
  2588. };
  2589. auto initBox = [](not_null<PeerListBox*> box) {
  2590. box->addButton(tr::lng_cancel(), [box] {
  2591. box->closeBox();
  2592. });
  2593. };
  2594. *weak = navigation->parentController()->show(Box<PeerListBox>(
  2595. std::make_unique<ChooseRecipientBoxController>(ChooseRecipientArgs{
  2596. .session = &navigation->session(),
  2597. .callback = std::move(chosen),
  2598. .filter = std::move(filter),
  2599. .moneyRestrictionError = WriteMoneyRestrictionError,
  2600. }),
  2601. std::move(initBox)));
  2602. return weak->data();
  2603. }
  2604. QPointer<Ui::BoxContent> ShowDropMediaBox(
  2605. not_null<Window::SessionNavigation*> navigation,
  2606. std::shared_ptr<QMimeData> data,
  2607. not_null<Data::Forum*> forum,
  2608. FnMut<void()> &&successCallback) {
  2609. const auto weak = std::make_shared<QPointer<Ui::BoxContent>>();
  2610. auto chosen = [
  2611. data = std::move(data),
  2612. callback = std::move(successCallback),
  2613. weak,
  2614. navigation
  2615. ](not_null<Data::ForumTopic*> topic) mutable {
  2616. const auto content = navigation->parentController()->content();
  2617. if (!content->filesOrForwardDrop(topic, data.get())) {
  2618. return;
  2619. } else if (const auto strong = *weak) {
  2620. strong->closeBox();
  2621. }
  2622. if (callback) {
  2623. callback();
  2624. }
  2625. };
  2626. auto initBox = [=](not_null<PeerListBox*> box) {
  2627. box->addButton(tr::lng_cancel(), [=] {
  2628. box->closeBox();
  2629. });
  2630. forum->destroyed(
  2631. ) | rpl::start_with_next([=] {
  2632. box->closeBox();
  2633. }, box->lifetime());
  2634. };
  2635. *weak = navigation->parentController()->show(Box<PeerListBox>(
  2636. std::make_unique<ChooseTopicBoxController>(
  2637. forum,
  2638. std::move(chosen)),
  2639. std::move(initBox)));
  2640. return weak->data();
  2641. }
  2642. QPointer<Ui::BoxContent> ShowSendNowMessagesBox(
  2643. not_null<Window::SessionNavigation*> navigation,
  2644. not_null<History*> history,
  2645. MessageIdsList &&items,
  2646. Fn<void()> &&successCallback) {
  2647. const auto session = &navigation->session();
  2648. const auto text = (items.size() > 1)
  2649. ? tr::lng_scheduled_send_now_many(tr::now, lt_count, items.size())
  2650. : tr::lng_scheduled_send_now(tr::now);
  2651. const auto list = session->data().idsToItems(items);
  2652. const auto error = GetErrorForSending(
  2653. history->peer,
  2654. { .forward = &list });
  2655. if (error) {
  2656. Data::ShowSendErrorToast(navigation, history->peer, error);
  2657. return { nullptr };
  2658. }
  2659. auto done = [
  2660. =,
  2661. list = std::move(items),
  2662. callback = std::move(successCallback)
  2663. ](Fn<void()> &&close) {
  2664. close();
  2665. auto ids = QVector<MTPint>();
  2666. auto sorted = session->data().idsToItems(list);
  2667. ranges::sort(sorted, ranges::less(), &HistoryItem::date);
  2668. for (const auto &item : sorted) {
  2669. if (item->allowsSendNow()) {
  2670. ids.push_back(
  2671. MTP_int(session->scheduledMessages().lookupId(item)));
  2672. }
  2673. }
  2674. session->api().request(MTPmessages_SendScheduledMessages(
  2675. history->peer->input,
  2676. MTP_vector<MTPint>(ids)
  2677. )).done([=](const MTPUpdates &result) {
  2678. session->api().applyUpdates(result);
  2679. }).fail([=](const MTP::Error &error) {
  2680. session->api().sendMessageFail(error, history->peer);
  2681. }).send();
  2682. if (callback) {
  2683. callback();
  2684. }
  2685. };
  2686. return navigation->parentController()->show(Ui::MakeConfirmBox({
  2687. .text = text,
  2688. .confirmed = std::move(done),
  2689. .confirmText = tr::lng_send_button(),
  2690. })).data();
  2691. }
  2692. void PeerMenuAddChannelMembers(
  2693. not_null<Window::SessionNavigation*> navigation,
  2694. not_null<ChannelData*> channel) {
  2695. if (!channel->isMegagroup()
  2696. && (channel->membersCount()
  2697. >= channel->session().serverConfig().chatSizeMax)) {
  2698. navigation->parentController()->show(Box<MaxInviteBox>(channel));
  2699. return;
  2700. }
  2701. const auto api = &channel->session().api();
  2702. api->chatParticipants().requestForAdd(channel, crl::guard(navigation, [=](
  2703. const Api::ChatParticipants::TLMembers &data) {
  2704. const auto &[availableCount, list] = Api::ChatParticipants::Parse(
  2705. channel,
  2706. data);
  2707. const auto already = (
  2708. list
  2709. ) | ranges::views::transform([&](const Api::ChatParticipant &p) {
  2710. return p.isUser()
  2711. ? channel->owner().userLoaded(p.userId())
  2712. : nullptr;
  2713. }) | ranges::views::filter([](UserData *user) {
  2714. return (user != nullptr);
  2715. }) | ranges::to_vector;
  2716. AddParticipantsBoxController::Start(
  2717. navigation,
  2718. channel,
  2719. { already.begin(), already.end() });
  2720. }));
  2721. }
  2722. void ToggleMessagePinned(
  2723. not_null<Window::SessionNavigation*> navigation,
  2724. FullMsgId itemId,
  2725. bool pin) {
  2726. const auto item = navigation->session().data().message(itemId);
  2727. if (!item || !item->canPin()) {
  2728. return;
  2729. }
  2730. if (pin) {
  2731. navigation->parentController()->show(
  2732. Box(PinMessageBox, item),
  2733. Ui::LayerOption::CloseOther);
  2734. } else {
  2735. const auto peer = item->history()->peer;
  2736. const auto session = &peer->session();
  2737. const auto callback = crl::guard(session, [=](Fn<void()> &&close) {
  2738. close();
  2739. session->api().request(MTPmessages_UpdatePinnedMessage(
  2740. MTP_flags(MTPmessages_UpdatePinnedMessage::Flag::f_unpin),
  2741. peer->input,
  2742. MTP_int(itemId.msg)
  2743. )).done([=](const MTPUpdates &result) {
  2744. session->api().applyUpdates(result);
  2745. }).send();
  2746. });
  2747. navigation->parentController()->show(
  2748. Ui::MakeConfirmBox({
  2749. .text = tr::lng_pinned_unpin_sure(),
  2750. .confirmed = callback,
  2751. .confirmText = tr::lng_pinned_unpin(),
  2752. }),
  2753. Ui::LayerOption::CloseOther);
  2754. }
  2755. }
  2756. void HidePinnedBar(
  2757. not_null<Window::SessionNavigation*> navigation,
  2758. not_null<PeerData*> peer,
  2759. MsgId topicRootId,
  2760. Fn<void()> onHidden) {
  2761. const auto callback = crl::guard(navigation, [=](Fn<void()> &&close) {
  2762. close();
  2763. auto &session = peer->session();
  2764. const auto migrated = topicRootId ? nullptr : peer->migrateFrom();
  2765. const auto top = Data::ResolveTopPinnedId(
  2766. peer,
  2767. topicRootId,
  2768. migrated);
  2769. const auto universal = !top
  2770. ? MsgId(0)
  2771. : (migrated && !peerIsChannel(top.peer))
  2772. ? (top.msg - ServerMaxMsgId)
  2773. : top.msg;
  2774. if (universal) {
  2775. session.settings().setHiddenPinnedMessageId(
  2776. peer->id,
  2777. topicRootId,
  2778. universal);
  2779. session.saveSettingsDelayed();
  2780. if (onHidden) {
  2781. onHidden();
  2782. }
  2783. } else {
  2784. session.api().requestFullPeer(peer);
  2785. }
  2786. });
  2787. navigation->parentController()->show(
  2788. Ui::MakeConfirmBox({
  2789. .text = tr::lng_pinned_hide_all_sure(),
  2790. .confirmed = callback,
  2791. .confirmText = tr::lng_pinned_hide_all_hide(),
  2792. }),
  2793. Ui::LayerOption::CloseOther);
  2794. }
  2795. void UnpinAllMessages(
  2796. not_null<Window::SessionNavigation*> navigation,
  2797. not_null<Data::Thread*> thread) {
  2798. const auto weak = base::make_weak(thread);
  2799. const auto callback = crl::guard(navigation, [=](Fn<void()> &&close) {
  2800. close();
  2801. const auto strong = weak.get();
  2802. if (!strong) {
  2803. return;
  2804. }
  2805. const auto api = &strong->session().api();
  2806. const auto sendRequest = [=](auto self) -> void {
  2807. const auto history = strong->owningHistory();
  2808. const auto topicRootId = strong->topicRootId();
  2809. using Flag = MTPmessages_UnpinAllMessages::Flag;
  2810. api->request(MTPmessages_UnpinAllMessages(
  2811. MTP_flags(topicRootId ? Flag::f_top_msg_id : Flag()),
  2812. history->peer->input,
  2813. MTP_int(topicRootId.bare)
  2814. )).done([=](const MTPmessages_AffectedHistory &result) {
  2815. const auto peer = history->peer;
  2816. const auto offset = api->applyAffectedHistory(peer, result);
  2817. if (offset > 0) {
  2818. self(self);
  2819. } else {
  2820. history->unpinMessagesFor(topicRootId);
  2821. }
  2822. }).send();
  2823. };
  2824. sendRequest(sendRequest);
  2825. });
  2826. navigation->parentController()->show(
  2827. Ui::MakeConfirmBox({
  2828. .text = tr::lng_pinned_unpin_all_sure(),
  2829. .confirmed = callback,
  2830. .confirmText = tr::lng_pinned_unpin(),
  2831. }),
  2832. Ui::LayerOption::CloseOther);
  2833. }
  2834. void MenuAddMarkAsReadAllChatsAction(
  2835. not_null<Main::Session*> session,
  2836. std::shared_ptr<Ui::Show> show,
  2837. const PeerMenuCallback &addAction) {
  2838. auto callback = [=, owner = &session->data()] {
  2839. auto boxCallback = [=](Fn<void()> &&close) {
  2840. close();
  2841. MarkAsReadChatList(owner->chatsList());
  2842. if (const auto folder = owner->folderLoaded(Data::Folder::kId)) {
  2843. MarkAsReadChatList(folder->chatsList());
  2844. }
  2845. };
  2846. show->show(
  2847. Box([=](not_null<Ui::GenericBox*> box) {
  2848. Ui::AddSkip(box->verticalLayout());
  2849. Ui::AddSkip(box->verticalLayout());
  2850. const auto userpic = Ui::CreateChild<Ui::UserpicButton>(
  2851. box->verticalLayout(),
  2852. session->user(),
  2853. st::mainMenuUserpic);
  2854. Ui::IconWithTitle(
  2855. box->verticalLayout(),
  2856. userpic,
  2857. Ui::CreateChild<Ui::FlatLabel>(
  2858. box->verticalLayout(),
  2859. Info::Profile::NameValue(session->user()),
  2860. box->getDelegate()->style().title));
  2861. auto text = rpl::combine(
  2862. tr::lng_context_mark_read_all_sure(),
  2863. tr::lng_context_mark_read_all_sure_2(
  2864. Ui::Text::RichLangValue)
  2865. ) | rpl::map([](QString t1, TextWithEntities t2) {
  2866. return TextWithEntities()
  2867. .append(std::move(t1))
  2868. .append('\n')
  2869. .append('\n')
  2870. .append(std::move(t2));
  2871. });
  2872. Ui::ConfirmBox(box, {
  2873. .text = std::move(text),
  2874. .confirmed = std::move(boxCallback),
  2875. .confirmStyle = &st::attentionBoxButton,
  2876. });
  2877. }),
  2878. Ui::LayerOption::CloseOther);
  2879. };
  2880. addAction(
  2881. tr::lng_context_mark_read_all(tr::now),
  2882. std::move(callback),
  2883. &st::menuIconMarkRead);
  2884. }
  2885. void MenuAddMarkAsReadChatListAction(
  2886. not_null<Window::SessionController*> controller,
  2887. Fn<not_null<Dialogs::MainList*>()> &&list,
  2888. const PeerMenuCallback &addAction,
  2889. Fn<Dialogs::UnreadState()> customUnreadState) {
  2890. // There is no async to make weak from controller.
  2891. const auto unreadState = customUnreadState
  2892. ? customUnreadState()
  2893. : list()->unreadState();
  2894. if (!unreadState.messages && !unreadState.marks && !unreadState.chats) {
  2895. return;
  2896. }
  2897. auto callback = [=] {
  2898. if (unreadState.messages > kMaxUnreadWithoutConfirmation) {
  2899. auto boxCallback = [=](Fn<void()> &&close) {
  2900. MarkAsReadChatList(list());
  2901. close();
  2902. };
  2903. controller->show(
  2904. Ui::MakeConfirmBox({
  2905. tr::lng_context_mark_read_sure(),
  2906. std::move(boxCallback)
  2907. }),
  2908. Ui::LayerOption::CloseOther);
  2909. } else {
  2910. MarkAsReadChatList(list());
  2911. }
  2912. };
  2913. addAction(
  2914. tr::lng_context_mark_read(tr::now),
  2915. std::move(callback),
  2916. &st::menuIconMarkRead);
  2917. }
  2918. void ToggleHistoryArchived(
  2919. std::shared_ptr<ChatHelpers::Show> show,
  2920. not_null<History*> history,
  2921. bool archived) {
  2922. const auto callback = [=] {
  2923. show->showToast(Ui::Toast::Config{
  2924. .text = { (archived
  2925. ? tr::lng_archived_added(tr::now)
  2926. : tr::lng_archived_removed(tr::now)) },
  2927. .st = &st::windowArchiveToast,
  2928. .duration = (archived
  2929. ? kArchivedToastDuration
  2930. : Ui::Toast::kDefaultDuration),
  2931. });
  2932. };
  2933. history->session().api().toggleHistoryArchived(
  2934. history,
  2935. archived,
  2936. callback);
  2937. }
  2938. Fn<void()> ClearHistoryHandler(
  2939. not_null<Window::SessionController*> controller,
  2940. not_null<PeerData*> peer) {
  2941. return [=] {
  2942. controller->show(Box<DeleteMessagesBox>(peer, true));
  2943. };
  2944. }
  2945. Fn<void()> DeleteAndLeaveHandler(
  2946. not_null<Window::SessionController*> controller,
  2947. not_null<PeerData*> peer) {
  2948. return [=] { controller->show(Box(DeleteChatBox, peer)); };
  2949. }
  2950. void FillDialogsEntryMenu(
  2951. not_null<SessionController*> controller,
  2952. Dialogs::EntryState request,
  2953. const PeerMenuCallback &callback) {
  2954. Filler(controller, request, callback).fill();
  2955. }
  2956. bool FillVideoChatMenu(
  2957. not_null<SessionController*> controller,
  2958. Dialogs::EntryState request,
  2959. const PeerMenuCallback &addAction) {
  2960. const auto peer = request.key.peer();
  2961. if (!peer || peer->isUser()) {
  2962. return false;
  2963. }
  2964. const auto callback = [=](Calls::StartGroupCallArgs &&args) {
  2965. controller->startOrJoinGroupCall(peer, std::move(args));
  2966. };
  2967. const auto rtmpCallback = [=] {
  2968. Core::App().calls().showStartWithRtmp(controller->uiShow(), peer);
  2969. };
  2970. const auto livestream = !peer->isMegagroup() && peer->isChannel();
  2971. const auto has = (peer->groupCall() != nullptr);
  2972. const auto manager = peer->canManageGroupCall();
  2973. if (has) {
  2974. addAction(
  2975. tr::lng_menu_start_group_call_join(tr::now),
  2976. [=] { callback({}); },
  2977. &st::menuIconVideoChat);
  2978. } else if (manager) {
  2979. addAction(
  2980. (livestream
  2981. ? tr::lng_menu_start_group_call_channel
  2982. : tr::lng_menu_start_group_call)(tr::now),
  2983. [=] { callback({}); },
  2984. &st::menuIconStartStream);
  2985. }
  2986. if (!has && manager) {
  2987. addAction(
  2988. (livestream
  2989. ? tr::lng_menu_start_group_call_scheduled_channel
  2990. : tr::lng_menu_start_group_call_scheduled)(tr::now),
  2991. [=] { callback({ .scheduleNeeded = true }); },
  2992. &st::menuIconReschedule);
  2993. addAction(
  2994. (livestream
  2995. ? tr::lng_menu_start_group_call_with_channel
  2996. : tr::lng_menu_start_group_call_with)(tr::now),
  2997. rtmpCallback,
  2998. &st::menuIconStartStreamWith);
  2999. }
  3000. return has || manager;
  3001. }
  3002. void FillSenderUserpicMenu(
  3003. not_null<SessionController*> controller,
  3004. not_null<PeerData*> peer,
  3005. Ui::InputField *fieldForMention,
  3006. Dialogs::Key searchInEntry,
  3007. const PeerMenuCallback &addAction) {
  3008. const auto group = (peer->isChat() || peer->isMegagroup());
  3009. const auto channel = peer->isChannel();
  3010. const auto viewProfileText = group
  3011. ? tr::lng_context_view_group(tr::now)
  3012. : channel
  3013. ? tr::lng_context_view_channel(tr::now)
  3014. : tr::lng_context_view_profile(tr::now);
  3015. addAction(viewProfileText, [=] {
  3016. controller->showPeerInfo(peer, Window::SectionShow::Way::Forward);
  3017. }, channel ? &st::menuIconInfo : &st::menuIconProfile);
  3018. const auto showHistoryText = group
  3019. ? tr::lng_context_open_group(tr::now)
  3020. : channel
  3021. ? tr::lng_context_open_channel(tr::now)
  3022. : tr::lng_profile_send_message(tr::now);
  3023. addAction(showHistoryText, [=] {
  3024. controller->showPeerHistory(peer, Window::SectionShow::Way::Forward);
  3025. }, channel ? &st::menuIconChannel : &st::menuIconChatBubble);
  3026. const auto username = peer->username();
  3027. const auto mention = !username.isEmpty() || peer->isUser();
  3028. if (const auto guard = mention ? fieldForMention : nullptr) {
  3029. addAction(tr::lng_context_mention(tr::now), crl::guard(guard, [=] {
  3030. if (!username.isEmpty()) {
  3031. fieldForMention->insertTag('@' + username);
  3032. } else {
  3033. fieldForMention->insertTag(
  3034. peer->shortName(),
  3035. PrepareMentionTag(peer->asUser()));
  3036. }
  3037. }), &st::menuIconUsername);
  3038. }
  3039. if (searchInEntry) {
  3040. addAction(tr::lng_context_search_from(tr::now), [=] {
  3041. controller->searchInChat(searchInEntry, peer);
  3042. }, &st::menuIconSearch);
  3043. }
  3044. }
  3045. bool IsUnreadThread(not_null<Data::Thread*> thread) {
  3046. return thread->chatListBadgesState().unread;
  3047. }
  3048. void MarkAsReadThread(not_null<Data::Thread*> thread) {
  3049. const auto readHistory = [&](not_null<History*> history) {
  3050. history->owner().histories().readInbox(history);
  3051. };
  3052. if (!IsUnreadThread(thread)) {
  3053. return;
  3054. } else if (const auto forum = thread->asForum()) {
  3055. forum->enumerateTopics([](
  3056. not_null<Data::ForumTopic*> topic) {
  3057. MarkAsReadThread(topic);
  3058. });
  3059. } else if (const auto history = thread->asHistory()) {
  3060. readHistory(history);
  3061. if (const auto migrated = history->migrateSibling()) {
  3062. readHistory(migrated);
  3063. }
  3064. } else if (const auto topic = thread->asTopic()) {
  3065. topic->readTillEnd();
  3066. }
  3067. }
  3068. void AddSeparatorAndShiftUp(const PeerMenuCallback &addAction) {
  3069. addAction({
  3070. .separatorSt = &st::popupMenuExpandedSeparator.menu.separator,
  3071. });
  3072. const auto &st = st::popupMenuExpandedSeparator.menu;
  3073. const auto shift = st::popupMenuExpandedSeparator.scrollPadding.top()
  3074. + st.itemPadding.top()
  3075. + st.itemStyle.font->height
  3076. + st.itemPadding.bottom()
  3077. + st.separator.padding.top()
  3078. + st.separator.width / 2;
  3079. addAction({ .addTopShift = -shift });
  3080. }
  3081. void TogglePinnedThread(
  3082. not_null<Window::SessionController*> controller,
  3083. not_null<Dialogs::Entry*> entry,
  3084. FilterId filterId) {
  3085. if (!filterId) {
  3086. return TogglePinnedThread(controller, entry);
  3087. }
  3088. const auto history = entry->asHistory();
  3089. if (!history) {
  3090. return;
  3091. }
  3092. const auto owner = &history->owner();
  3093. // This can happen when you remove this filter from another client.
  3094. if (!ranges::contains(
  3095. (&owner->session())->data().chatsFilters().list(),
  3096. filterId,
  3097. &Data::ChatFilter::id)) {
  3098. controller->showToast(tr::lng_cant_do_this(tr::now));
  3099. return;
  3100. }
  3101. const auto isPinned = !history->isPinnedDialog(filterId);
  3102. if (isPinned && PinnedLimitReached(controller, history, filterId)) {
  3103. return;
  3104. }
  3105. owner->setChatPinned(history, filterId, isPinned);
  3106. Api::SaveNewFilterPinned(&owner->session(), filterId);
  3107. if (isPinned) {
  3108. controller->content()->dialogsToUp();
  3109. }
  3110. }
  3111. bool IsArchived(not_null<History*> history) {
  3112. return (history->folder() != nullptr);
  3113. }
  3114. } // namespace Window