share_box.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  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 "boxes/share_box.h"
  8. #include "api/api_premium.h"
  9. #include "base/random.h"
  10. #include "lang/lang_keys.h"
  11. #include "base/qthelp_url.h"
  12. #include "storage/storage_account.h"
  13. #include "ui/boxes/confirm_box.h"
  14. #include "apiwrap.h"
  15. #include "ui/widgets/chat_filters_tabs_strip.h"
  16. #include "ui/widgets/checkbox.h"
  17. #include "ui/widgets/multi_select.h"
  18. #include "ui/widgets/scroll_area.h"
  19. #include "ui/widgets/fields/input_field.h"
  20. #include "ui/widgets/popup_menu.h"
  21. #include "ui/wrap/slide_wrap.h"
  22. #include "ui/text/text_options.h"
  23. #include "ui/text/text_utilities.h"
  24. #include "ui/painter.h"
  25. #include "ui/ui_utility.h"
  26. #include "chat_helpers/message_field.h"
  27. #include "menu/menu_check_item.h"
  28. #include "menu/menu_send.h"
  29. #include "history/history.h"
  30. #include "history/history_item.h"
  31. #include "history/history_item_helpers.h"
  32. #include "history/view/history_view_element.h"
  33. #include "history/view/history_view_context_menu.h" // CopyPostLink.
  34. #include "settings/settings_premium.h"
  35. #include "window/window_session_controller.h"
  36. #include "boxes/peer_list_controllers.h"
  37. #include "chat_helpers/emoji_suggestions_widget.h"
  38. #include "chat_helpers/share_message_phrase_factory.h"
  39. #include "data/business/data_shortcut_messages.h"
  40. #include "data/data_channel.h"
  41. #include "data/data_chat_filters.h"
  42. #include "data/data_game.h"
  43. #include "data/data_histories.h"
  44. #include "data/data_user.h"
  45. #include "data/data_peer_values.h"
  46. #include "data/data_session.h"
  47. #include "data/data_folder.h"
  48. #include "data/data_forum.h"
  49. #include "data/data_forum_topic.h"
  50. #include "data/data_changes.h"
  51. #include "main/main_session.h"
  52. #include "core/application.h"
  53. #include "core/core_settings.h"
  54. #include "styles/style_calls.h"
  55. #include "styles/style_layers.h"
  56. #include "styles/style_boxes.h"
  57. #include "styles/style_menu_icons.h"
  58. #include <QtGui/QGuiApplication>
  59. #include <QtGui/QClipboard>
  60. class ShareBox::Inner final : public Ui::RpWidget {
  61. public:
  62. Inner(
  63. QWidget *parent,
  64. const Descriptor &descriptor,
  65. std::shared_ptr<Ui::Show> show);
  66. void setPeerSelectedChangedCallback(
  67. Fn<void(not_null<Data::Thread*> thread, bool selected)> callback);
  68. void peerUnselected(not_null<PeerData*> peer);
  69. [[nodiscard]] std::vector<not_null<Data::Thread*>> selected() const;
  70. [[nodiscard]] bool hasSelected() const;
  71. void peopleReceived(
  72. const QString &query,
  73. const QVector<MTPPeer> &my,
  74. const QVector<MTPPeer> &people);
  75. void activateSkipRow(int direction);
  76. void activateSkipColumn(int direction);
  77. void activateSkipPage(int pageHeight, int direction);
  78. void updateFilter(QString filter = QString());
  79. [[nodiscard]] bool isFilterEmpty() const;
  80. void selectActive();
  81. rpl::producer<Ui::ScrollToRequest> scrollToRequests() const;
  82. rpl::producer<> searchRequests() const;
  83. void applyChatFilter(FilterId id);
  84. protected:
  85. void visibleTopBottomUpdated(
  86. int visibleTop,
  87. int visibleBottom) override;
  88. void paintEvent(QPaintEvent *e) override;
  89. void enterEventHook(QEnterEvent *e) override;
  90. void leaveEventHook(QEvent *e) override;
  91. void mouseMoveEvent(QMouseEvent *e) override;
  92. void mousePressEvent(QMouseEvent *e) override;
  93. void resizeEvent(QResizeEvent *e) override;
  94. private:
  95. struct Chat {
  96. Chat(
  97. not_null<History*> history,
  98. const style::PeerListItem &st,
  99. Fn<void()> updateCallback);
  100. not_null<History*> history;
  101. not_null<PeerData*> peer;
  102. Data::ForumTopic *topic = nullptr;
  103. rpl::lifetime topicLifetime;
  104. Ui::RoundImageCheckbox checkbox;
  105. Ui::Text::String name;
  106. Ui::Animations::Simple nameActive;
  107. Api::MessageMoneyRestriction restriction;
  108. RestrictionBadgeCache badgeCache;
  109. };
  110. void invalidateCache();
  111. bool showLockedError(not_null<Chat*> chat);
  112. void refreshRestrictedRows();
  113. [[nodiscard]] int displayedChatsCount() const;
  114. [[nodiscard]] not_null<Data::Thread*> chatThread(
  115. not_null<Chat*> chat) const;
  116. void paintChat(Painter &p, not_null<Chat*> chat, int index);
  117. void updateChat(not_null<PeerData*> peer);
  118. void updateChatName(not_null<Chat*> chat);
  119. void initChatRestriction(not_null<Chat*> chat);
  120. void repaintChat(not_null<PeerData*> peer);
  121. int chatIndex(not_null<PeerData*> peer) const;
  122. void repaintChatAtIndex(int index);
  123. Chat *getChatAtIndex(int index);
  124. void loadProfilePhotos();
  125. void preloadUserpic(not_null<Dialogs::Entry*> entry);
  126. void changeCheckState(Chat *chat);
  127. void chooseForumTopic(not_null<Data::Forum*> forum);
  128. enum class ChangeStateWay {
  129. Default,
  130. SkipCallback,
  131. };
  132. void changePeerCheckState(
  133. not_null<Chat*> chat,
  134. bool checked,
  135. ChangeStateWay useCallback = ChangeStateWay::Default);
  136. not_null<Chat*> getChat(not_null<Dialogs::Row*> row);
  137. void setActive(int active);
  138. void updateUpon(const QPoint &pos);
  139. void refresh();
  140. const Descriptor &_descriptor;
  141. const std::shared_ptr<Ui::Show> _show;
  142. const style::PeerList &_st;
  143. float64 _columnSkip = 0.;
  144. float64 _rowWidthReal = 0.;
  145. int _rowsLeft = 0;
  146. int _rowsTop = 0;
  147. int _rowWidth = 0;
  148. int _rowHeight = 0;
  149. int _columnCount = 4;
  150. int _active = -1;
  151. int _upon = -1;
  152. int _visibleTop = 0;
  153. std::unique_ptr<Dialogs::IndexedList> _defaultChatsIndexed;
  154. std::unique_ptr<Dialogs::IndexedList> _customChatsIndexed;
  155. not_null<Dialogs::IndexedList*> _chatsIndexed;
  156. QString _filter;
  157. std::vector<not_null<Dialogs::Row*>> _filtered;
  158. std::map<not_null<PeerData*>, std::unique_ptr<Chat>> _dataMap;
  159. base::flat_set<not_null<Data::Thread*>> _selected;
  160. Fn<void(not_null<Data::Thread*>, bool)> _peerSelectedChangedCallback;
  161. bool _searching = false;
  162. QString _lastQuery;
  163. std::vector<PeerData*> _byUsernameFiltered;
  164. std::vector<std::unique_ptr<Chat>> d_byUsernameFiltered;
  165. rpl::event_stream<Ui::ScrollToRequest> _scrollToRequests;
  166. rpl::event_stream<> _searchRequests;
  167. };
  168. ShareBox::ShareBox(QWidget*, Descriptor &&descriptor)
  169. : _descriptor(std::move(descriptor))
  170. , _api(&_descriptor.session->mtp())
  171. , _select(
  172. this,
  173. (_descriptor.st.multiSelect
  174. ? *_descriptor.st.multiSelect
  175. : st::defaultMultiSelect),
  176. tr::lng_participant_filter())
  177. , _comment(
  178. this,
  179. object_ptr<Ui::InputField>(
  180. this,
  181. (_descriptor.st.comment
  182. ? *_descriptor.st.comment
  183. : st::shareComment),
  184. Ui::InputField::Mode::MultiLine,
  185. tr::lng_photos_comment()),
  186. st::shareCommentPadding)
  187. , _bottomWidget(std::move(_descriptor.bottomWidget))
  188. , _copyLinkText(_descriptor.copyLinkText
  189. ? std::move(_descriptor.copyLinkText)
  190. : tr::lng_share_copy_link())
  191. , _searchTimer([=] { searchByUsername(); }) {
  192. if (_bottomWidget) {
  193. _bottomWidget->setParent(this);
  194. _bottomWidget->resizeToWidth(st::boxWideWidth);
  195. _bottomWidget->show();
  196. }
  197. }
  198. void ShareBox::prepareCommentField() {
  199. _comment->hide(anim::type::instant);
  200. rpl::combine(
  201. heightValue(),
  202. _comment->heightValue(),
  203. (_bottomWidget
  204. ? _bottomWidget->heightValue()
  205. : (rpl::single(0) | rpl::type_erased()))
  206. ) | rpl::start_with_next([=](int height, int comment, int bottom) {
  207. _comment->moveToLeft(0, height - bottom - comment);
  208. if (_bottomWidget) {
  209. _bottomWidget->moveToLeft(0, height - bottom);
  210. }
  211. }, _comment->lifetime());
  212. const auto field = _comment->entity();
  213. field->submits(
  214. ) | rpl::start_with_next([=] {
  215. submit({});
  216. }, field->lifetime());
  217. if (const auto show = uiShow(); show->valid()) {
  218. InitMessageFieldHandlers({
  219. .session = _descriptor.session,
  220. .show = Main::MakeSessionShow(show, _descriptor.session),
  221. .field = field,
  222. .fieldStyle = _descriptor.st.label,
  223. });
  224. }
  225. field->setSubmitSettings(Core::App().settings().sendSubmitWay());
  226. field->changes() | rpl::start_with_next([=] {
  227. if (!field->getLastText().isEmpty()) {
  228. setCloseByOutsideClick(false);
  229. } else if (_inner->selected().empty()) {
  230. setCloseByOutsideClick(true);
  231. }
  232. }, field->lifetime());
  233. Ui::SendPendingMoveResizeEvents(_comment);
  234. if (_bottomWidget) {
  235. Ui::SendPendingMoveResizeEvents(_bottomWidget);
  236. }
  237. }
  238. void ShareBox::prepare() {
  239. prepareCommentField();
  240. _select->resizeToWidth(st::boxWideWidth);
  241. Ui::SendPendingMoveResizeEvents(_select);
  242. setTitle(_descriptor.titleOverride
  243. ? std::move(_descriptor.titleOverride)
  244. : tr::lng_share_title());
  245. _inner = setInnerWidget(
  246. object_ptr<Inner>(this, _descriptor, uiShow()),
  247. getTopScrollSkip(),
  248. getBottomScrollSkip());
  249. createButtons();
  250. setDimensions(st::boxWideWidth, st::boxMaxListHeight);
  251. _select->setQueryChangedCallback([=](const QString &query) {
  252. applyFilterUpdate(query);
  253. if (_chatsFilters) {
  254. updateScrollSkips();
  255. scrollToY(0);
  256. }
  257. });
  258. _select->setItemRemovedCallback([=](uint64 itemId) {
  259. if (const auto peer = _descriptor.session->data().peerLoaded(PeerId(itemId))) {
  260. _inner->peerUnselected(peer);
  261. selectedChanged();
  262. update();
  263. }
  264. });
  265. _select->setResizedCallback([=] { updateScrollSkips(); });
  266. _select->setSubmittedCallback([=](Qt::KeyboardModifiers modifiers) {
  267. if (modifiers.testFlag(Qt::ControlModifier)
  268. || modifiers.testFlag(Qt::MetaModifier)) {
  269. submit({});
  270. } else {
  271. _inner->selectActive();
  272. }
  273. });
  274. rpl::combine(
  275. _comment->heightValue(),
  276. (_bottomWidget
  277. ? _bottomWidget->heightValue()
  278. : rpl::single(0) | rpl::type_erased())
  279. ) | rpl::start_with_next([=] {
  280. updateScrollSkips();
  281. }, _comment->lifetime());
  282. _inner->searchRequests(
  283. ) | rpl::start_with_next([=] {
  284. needSearchByUsername();
  285. }, _inner->lifetime());
  286. _inner->scrollToRequests(
  287. ) | rpl::start_with_next([=](const Ui::ScrollToRequest &request) {
  288. scrollTo(request);
  289. }, _inner->lifetime());
  290. _inner->setPeerSelectedChangedCallback([=](
  291. not_null<Data::Thread*> thread,
  292. bool checked) {
  293. innerSelectedChanged(thread, checked);
  294. if (checked) {
  295. setCloseByOutsideClick(false);
  296. } else if (_inner->selected().empty()
  297. && _comment->entity()->getLastText().isEmpty()) {
  298. setCloseByOutsideClick(true);
  299. }
  300. });
  301. Ui::Emoji::SuggestionsController::Init(
  302. getDelegate()->outerContainer(),
  303. _comment->entity(),
  304. _descriptor.session,
  305. { .suggestCustomEmoji = true });
  306. _select->raise();
  307. {
  308. const auto chatsFilters = AddChatFiltersTabsStrip(
  309. this,
  310. _descriptor.session,
  311. [this](FilterId id) {
  312. _inner->applyChatFilter(id);
  313. scrollToY(0);
  314. },
  315. Window::GifPauseReason::Layer);
  316. chatsFilters->lower();
  317. chatsFilters->heightValue() | rpl::start_with_next([this](int h) {
  318. updateScrollSkips();
  319. scrollToY(0);
  320. }, lifetime());
  321. _select->heightValue() | rpl::start_with_next([=](int h) {
  322. chatsFilters->moveToLeft(0, h);
  323. }, chatsFilters->lifetime());
  324. _chatsFilters = chatsFilters;
  325. }
  326. }
  327. int ShareBox::getTopScrollSkip() const {
  328. return (_select->isHidden() ? 0 : _select->height())
  329. + ((_chatsFilters && _inner && _inner->isFilterEmpty())
  330. ? _chatsFilters->height()
  331. : 0);
  332. }
  333. int ShareBox::getBottomScrollSkip() const {
  334. return (_comment->isHidden() ? 0 : _comment->height())
  335. + (_bottomWidget ? _bottomWidget->height() : 0);
  336. }
  337. int ShareBox::contentHeight() const {
  338. return height() - getTopScrollSkip() - getBottomScrollSkip();
  339. }
  340. void ShareBox::updateScrollSkips() {
  341. setInnerTopSkip(getTopScrollSkip(), true);
  342. setInnerBottomSkip(getBottomScrollSkip());
  343. }
  344. bool ShareBox::searchByUsername(bool searchCache) {
  345. auto query = _select->getQuery();
  346. if (query.isEmpty()) {
  347. if (_peopleRequest) {
  348. _peopleRequest = 0;
  349. }
  350. return true;
  351. }
  352. if (!query.isEmpty()) {
  353. if (searchCache) {
  354. auto i = _peopleCache.constFind(query);
  355. if (i != _peopleCache.cend()) {
  356. _peopleQuery = query;
  357. _peopleRequest = 0;
  358. peopleDone(i.value(), 0);
  359. return true;
  360. }
  361. } else if (_peopleQuery != query) {
  362. _peopleQuery = query;
  363. _peopleFull = false;
  364. _peopleRequest = _api.request(MTPcontacts_Search(
  365. MTP_string(_peopleQuery),
  366. MTP_int(SearchPeopleLimit)
  367. )).done([=](const MTPcontacts_Found &result, mtpRequestId requestId) {
  368. peopleDone(result, requestId);
  369. }).fail([=](const MTP::Error &error, mtpRequestId requestId) {
  370. peopleFail(error, requestId);
  371. }).send();
  372. _peopleQueries.insert(_peopleRequest, _peopleQuery);
  373. }
  374. }
  375. return false;
  376. }
  377. void ShareBox::needSearchByUsername() {
  378. if (!searchByUsername(true)) {
  379. _searchTimer.callOnce(AutoSearchTimeout);
  380. }
  381. }
  382. void ShareBox::peopleDone(
  383. const MTPcontacts_Found &result,
  384. mtpRequestId requestId) {
  385. Expects(result.type() == mtpc_contacts_found);
  386. auto query = _peopleQuery;
  387. auto i = _peopleQueries.find(requestId);
  388. if (i != _peopleQueries.cend()) {
  389. query = i.value();
  390. _peopleCache[query] = result;
  391. _peopleQueries.erase(i);
  392. }
  393. if (_peopleRequest == requestId) {
  394. switch (result.type()) {
  395. case mtpc_contacts_found: {
  396. auto &found = result.c_contacts_found();
  397. _descriptor.session->data().processUsers(found.vusers());
  398. _descriptor.session->data().processChats(found.vchats());
  399. _inner->peopleReceived(
  400. query,
  401. found.vmy_results().v,
  402. found.vresults().v);
  403. } break;
  404. }
  405. _peopleRequest = 0;
  406. }
  407. }
  408. void ShareBox::peopleFail(const MTP::Error &error, mtpRequestId requestId) {
  409. if (_peopleRequest == requestId) {
  410. _peopleRequest = 0;
  411. _peopleFull = true;
  412. }
  413. }
  414. void ShareBox::setInnerFocus() {
  415. if (_comment->isHidden()) {
  416. _select->setInnerFocus();
  417. } else {
  418. _comment->entity()->setFocusFast();
  419. }
  420. }
  421. void ShareBox::resizeEvent(QResizeEvent *e) {
  422. BoxContent::resizeEvent(e);
  423. _select->resizeToWidth(width());
  424. _select->moveToLeft(0, 0);
  425. updateScrollSkips();
  426. _inner->resizeToWidth(width());
  427. }
  428. void ShareBox::keyPressEvent(QKeyEvent *e) {
  429. auto focused = focusWidget();
  430. if (_select == focused || _select->isAncestorOf(focusWidget())) {
  431. if (e->key() == Qt::Key_Up) {
  432. _inner->activateSkipColumn(-1);
  433. } else if (e->key() == Qt::Key_Down) {
  434. _inner->activateSkipColumn(1);
  435. } else if (e->key() == Qt::Key_PageUp) {
  436. _inner->activateSkipPage(contentHeight(), -1);
  437. } else if (e->key() == Qt::Key_PageDown) {
  438. _inner->activateSkipPage(contentHeight(), 1);
  439. } else {
  440. BoxContent::keyPressEvent(e);
  441. }
  442. } else {
  443. BoxContent::keyPressEvent(e);
  444. }
  445. }
  446. SendMenu::Details ShareBox::sendMenuDetails() const {
  447. const auto selected = _inner->selected();
  448. const auto hasPaid = [&] {
  449. for (const auto &thread : selected) {
  450. if (thread->peer()->starsPerMessageChecked()) {
  451. return true;
  452. }
  453. }
  454. return false;
  455. }();
  456. const auto type = hasPaid
  457. ? SendMenu::Type::SilentOnly
  458. : ranges::all_of(
  459. selected | ranges::views::transform(&Data::Thread::peer),
  460. HistoryView::CanScheduleUntilOnline)
  461. ? SendMenu::Type::ScheduledToUser
  462. : (selected.size() == 1 && selected.front()->peer()->isSelf())
  463. ? SendMenu::Type::Reminder
  464. : SendMenu::Type::Scheduled;
  465. // We can't support effect here because we don't have ChatHelpers::Show.
  466. return { .type = type, .effectAllowed = false };
  467. }
  468. void ShareBox::showMenu(not_null<Ui::RpWidget*> parent) {
  469. if (_menu) {
  470. _menu = nullptr;
  471. return;
  472. }
  473. _menu.emplace(parent, st::popupMenuWithIcons);
  474. if (_descriptor.forwardOptions.show) {
  475. auto createView = [&](rpl::producer<QString> &&text, bool checked) {
  476. auto item = base::make_unique_q<Menu::ItemWithCheck>(
  477. _menu->menu(),
  478. st::popupMenuWithIcons.menu,
  479. Ui::CreateChild<QAction>(_menu->menu().get()),
  480. nullptr,
  481. nullptr);
  482. std::move(
  483. text
  484. ) | rpl::start_with_next([action = item->action()](QString text) {
  485. action->setText(text);
  486. }, item->lifetime());
  487. item->init(checked);
  488. const auto view = item->checkView();
  489. _menu->addAction(std::move(item));
  490. return view;
  491. };
  492. Ui::FillForwardOptions(
  493. std::move(createView),
  494. _forwardOptions,
  495. [=](Ui::ForwardOptions value) { _forwardOptions = value; },
  496. _menu->lifetime());
  497. _menu->addSeparator();
  498. }
  499. using namespace SendMenu;
  500. const auto sendAction = crl::guard(this, [=](Action action, Details) {
  501. if (action.type == ActionType::Send) {
  502. submit(action.options);
  503. return;
  504. }
  505. const auto st = _descriptor.st.scheduleBox
  506. ? *_descriptor.st.scheduleBox
  507. : HistoryView::ScheduleBoxStyleArgs();
  508. uiShow()->showBox(
  509. HistoryView::PrepareScheduleBox(
  510. this,
  511. nullptr, // ChatHelpers::Show for effect attachment.
  512. sendMenuDetails(),
  513. [=](Api::SendOptions options) { submit(options); },
  514. action.options,
  515. HistoryView::DefaultScheduleTime(),
  516. st));
  517. });
  518. _menu->setForcedVerticalOrigin(Ui::PopupMenu::VerticalOrigin::Bottom);
  519. const auto result = FillSendMenu(
  520. _menu.get(),
  521. nullptr, // showForEffect.
  522. sendMenuDetails(),
  523. sendAction);
  524. if (result == SendMenu::FillMenuResult::Prepared) {
  525. _menu->popupPrepared();
  526. } else if (_descriptor.forwardOptions.show
  527. && result != SendMenu::FillMenuResult::Failed) {
  528. _menu->popup(QCursor::pos());
  529. }
  530. }
  531. void ShareBox::createButtons() {
  532. clearButtons();
  533. if (_hasSelected) {
  534. const auto send = addButton(tr::lng_share_confirm(), [=] {
  535. submit({});
  536. });
  537. _forwardOptions.sendersCount
  538. = _descriptor.forwardOptions.sendersCount;
  539. _forwardOptions.captionsCount
  540. = _descriptor.forwardOptions.captionsCount;
  541. send->setAcceptBoth();
  542. send->clicks(
  543. ) | rpl::start_with_next([=](Qt::MouseButton button) {
  544. if (button == Qt::RightButton) {
  545. showMenu(send);
  546. }
  547. }, send->lifetime());
  548. send->setText(PaidSendButtonText(
  549. _starsToSend.value(),
  550. tr::lng_share_confirm()));
  551. } else if (_descriptor.copyCallback) {
  552. addButton(_copyLinkText.value(), [=] { copyLink(); });
  553. }
  554. addButton(tr::lng_cancel(), [=] { closeBox(); });
  555. }
  556. void ShareBox::applyFilterUpdate(const QString &query) {
  557. scrollToY(0);
  558. _inner->updateFilter(query);
  559. }
  560. void ShareBox::addPeerToMultiSelect(not_null<Data::Thread*> thread) {
  561. auto addItemWay = Ui::MultiSelect::AddItemWay::Default;
  562. const auto peer = thread->peer();
  563. const auto topic = thread->asTopic();
  564. _select->addItem(
  565. peer->id.value,
  566. (topic
  567. ? topic->title()
  568. : peer->isSelf()
  569. ? tr::lng_saved_short(tr::now)
  570. : peer->shortName()),
  571. st::activeButtonBg,
  572. (topic
  573. ? ForceRoundUserpicCallback(peer)
  574. : PaintUserpicCallback(peer, true)),
  575. addItemWay);
  576. }
  577. void ShareBox::innerSelectedChanged(
  578. not_null<Data::Thread*> thread,
  579. bool checked) {
  580. if (checked) {
  581. addPeerToMultiSelect(thread);
  582. _select->clearQuery();
  583. } else {
  584. _select->removeItem(thread->peer()->id.value);
  585. }
  586. selectedChanged();
  587. update();
  588. }
  589. void ShareBox::submit(Api::SendOptions options) {
  590. _submitLifetime.destroy();
  591. auto threads = _inner->selected();
  592. const auto weak = Ui::MakeWeak(this);
  593. const auto field = _comment->entity();
  594. auto comment = field->getTextWithAppliedMarkdown();
  595. const auto checkPaid = [=] {
  596. if (!_descriptor.countMessagesCallback) {
  597. return true;
  598. }
  599. const auto withPaymentApproved = crl::guard(weak, [=](int approved) {
  600. auto copy = options;
  601. copy.starsApproved = approved;
  602. submit(copy);
  603. });
  604. const auto messagesCount = _descriptor.countMessagesCallback(
  605. comment);
  606. const auto alreadyApproved = options.starsApproved;
  607. auto paid = std::vector<not_null<PeerData*>>();
  608. auto waiting = base::flat_set<not_null<PeerData*>>();
  609. auto totalStars = 0;
  610. for (const auto &thread : threads) {
  611. const auto peer = thread->peer();
  612. const auto details = ComputePaymentDetails(peer, messagesCount);
  613. if (!details) {
  614. waiting.emplace(peer);
  615. } else if (details->stars > 0) {
  616. totalStars += details->stars;
  617. paid.push_back(peer);
  618. }
  619. }
  620. if (!waiting.empty()) {
  621. _descriptor.session->changes().peerUpdates(
  622. Data::PeerUpdate::Flag::FullInfo
  623. ) | rpl::start_with_next([=](const Data::PeerUpdate &update) {
  624. if (waiting.contains(update.peer)) {
  625. withPaymentApproved(alreadyApproved);
  626. }
  627. }, _submitLifetime);
  628. if (!_descriptor.session->credits().loaded()) {
  629. _descriptor.session->credits().loadedValue(
  630. ) | rpl::filter(
  631. rpl::mappers::_1
  632. ) | rpl::take(1) | rpl::start_with_next([=] {
  633. withPaymentApproved(alreadyApproved);
  634. }, _submitLifetime);
  635. }
  636. return false;
  637. } else if (totalStars > alreadyApproved) {
  638. const auto show = uiShow();
  639. const auto session = _descriptor.session;
  640. const auto sessionShow = Main::MakeSessionShow(show, session);
  641. const auto scheduleBoxSt = _descriptor.st.scheduleBox.get();
  642. ShowSendPaidConfirm(sessionShow, paid, SendPaymentDetails{
  643. .messages = messagesCount,
  644. .stars = totalStars,
  645. }, [=] { withPaymentApproved(totalStars); }, PaidConfirmStyles{
  646. .label = (scheduleBoxSt
  647. ? scheduleBoxSt->chooseDateTimeArgs.labelStyle
  648. : nullptr),
  649. .checkbox = _descriptor.st.checkbox,
  650. });
  651. return false;
  652. }
  653. return true;
  654. };
  655. if (const auto onstack = _descriptor.submitCallback) {
  656. const auto forwardOptions = (_forwardOptions.captionsCount
  657. && _forwardOptions.dropCaptions)
  658. ? Data::ForwardOptions::NoNamesAndCaptions
  659. : _forwardOptions.dropNames
  660. ? Data::ForwardOptions::NoSenderNames
  661. : Data::ForwardOptions::PreserveInfo;
  662. onstack(
  663. std::move(threads),
  664. checkPaid,
  665. std::move(comment),
  666. options,
  667. forwardOptions);
  668. }
  669. }
  670. void ShareBox::copyLink() const {
  671. if (const auto onstack = _descriptor.copyCallback) {
  672. onstack();
  673. }
  674. }
  675. void ShareBox::selectedChanged() {
  676. auto hasSelected = _inner->hasSelected();
  677. if (_hasSelected != hasSelected) {
  678. _hasSelected = hasSelected;
  679. createButtons();
  680. _comment->toggle(_hasSelected, anim::type::normal);
  681. _comment->resizeToWidth(st::boxWideWidth);
  682. }
  683. computeStarsCount();
  684. update();
  685. }
  686. void ShareBox::computeStarsCount() {
  687. auto perMessage = 0;
  688. for (const auto &thread : _inner->selected()) {
  689. perMessage += thread->peer()->starsPerMessageChecked();
  690. }
  691. const auto messagesCount = _descriptor.countMessagesCallback
  692. ? _descriptor.countMessagesCallback(_comment
  693. ? _comment->entity()->getTextWithTags()
  694. : TextWithTags())
  695. : 0;
  696. _starsToSend = perMessage * messagesCount;
  697. }
  698. void ShareBox::scrollTo(Ui::ScrollToRequest request) {
  699. scrollToY(request.ymin, request.ymax);
  700. //auto scrollTop = scrollArea()->scrollTop(), scrollBottom = scrollTop + scrollArea()->height();
  701. //auto from = scrollTop, to = scrollTop;
  702. //if (scrollTop > top) {
  703. // to = top;
  704. //} else if (scrollBottom < bottom) {
  705. // to = bottom - (scrollBottom - scrollTop);
  706. //}
  707. //if (from != to) {
  708. // _scrollAnimation.start([this]() { scrollAnimationCallback(); }, from, to, st::shareScrollDuration, anim::sineInOut);
  709. //}
  710. }
  711. void ShareBox::scrollAnimationCallback() {
  712. //auto scrollTop = qRound(_scrollAnimation.current(scrollArea()->scrollTop()));
  713. //scrollArea()->scrollToY(scrollTop);
  714. }
  715. ShareBox::Inner::Inner(
  716. QWidget *parent,
  717. const Descriptor &descriptor,
  718. std::shared_ptr<Ui::Show> show)
  719. : RpWidget(parent)
  720. , _descriptor(descriptor)
  721. , _show(std::move(show))
  722. , _st(_descriptor.st.peerList
  723. ? *_descriptor.st.peerList
  724. : st::shareBoxList)
  725. , _defaultChatsIndexed(
  726. std::make_unique<Dialogs::IndexedList>(
  727. Dialogs::SortMode::Add))
  728. , _chatsIndexed(_defaultChatsIndexed.get()) {
  729. _rowsTop = st::shareRowsTop;
  730. _rowHeight = st::shareRowHeight;
  731. setAttribute(Qt::WA_OpaquePaintEvent);
  732. if (_descriptor.moneyRestrictionError) {
  733. const auto session = _descriptor.session;
  734. rpl::merge(
  735. Data::AmPremiumValue(session) | rpl::to_empty,
  736. session->api().premium().someMessageMoneyRestrictionsResolved()
  737. ) | rpl::start_with_next([=] {
  738. refreshRestrictedRows();
  739. }, lifetime());
  740. }
  741. const auto self = _descriptor.session->user();
  742. const auto selfHistory = self->owner().history(self);
  743. if (_descriptor.filterCallback(selfHistory)) {
  744. _defaultChatsIndexed->addToEnd(selfHistory);
  745. }
  746. const auto addList = [&](not_null<Dialogs::IndexedList*> list) {
  747. for (const auto &row : list->all()) {
  748. if (const auto history = row->history()) {
  749. if (!history->peer->isSelf()
  750. && (history->asForum()
  751. || _descriptor.filterCallback(history))) {
  752. _defaultChatsIndexed->addToEnd(history);
  753. }
  754. }
  755. }
  756. };
  757. addList(_descriptor.session->data().chatsList()->indexed());
  758. const auto id = Data::Folder::kId;
  759. if (const auto folder = _descriptor.session->data().folderLoaded(id)) {
  760. addList(folder->chatsList()->indexed());
  761. }
  762. addList(_descriptor.session->data().contactsNoChatsList());
  763. _filter = u"a"_q;
  764. updateFilter();
  765. _descriptor.session->changes().peerUpdates(
  766. Data::PeerUpdate::Flag::Photo
  767. ) | rpl::start_with_next([=](const Data::PeerUpdate &update) {
  768. updateChat(update.peer);
  769. }, lifetime());
  770. _descriptor.session->changes().realtimeNameUpdates(
  771. ) | rpl::start_with_next([=](const Data::NameUpdate &update) {
  772. _defaultChatsIndexed->peerNameChanged(
  773. update.peer,
  774. update.oldFirstLetters);
  775. }, lifetime());
  776. _descriptor.session->downloaderTaskFinished(
  777. ) | rpl::start_with_next([=] {
  778. update();
  779. }, lifetime());
  780. style::PaletteChanged(
  781. ) | rpl::start_with_next([=] {
  782. invalidateCache();
  783. }, lifetime());
  784. }
  785. void ShareBox::Inner::invalidateCache() {
  786. for (const auto &[peer, data] : _dataMap) {
  787. data->checkbox.invalidateCache();
  788. }
  789. }
  790. bool ShareBox::Inner::showLockedError(not_null<Chat*> chat) {
  791. if (!chat->restriction.premiumRequired) {
  792. return false;
  793. }
  794. ::Settings::ShowPremiumPromoToast(
  795. Main::MakeSessionShow(_show, _descriptor.session),
  796. ChatHelpers::ResolveWindowDefault(),
  797. _descriptor.moneyRestrictionError(chat->peer->asUser()).text,
  798. u"require_premium"_q);
  799. return true;
  800. }
  801. void ShareBox::Inner::refreshRestrictedRows() {
  802. auto changed = false;
  803. for (const auto &[peer, data] : _dataMap) {
  804. const auto history = data->history;
  805. const auto restriction = Api::ResolveMessageMoneyRestrictions(
  806. history->peer,
  807. history);
  808. if (data->restriction != restriction) {
  809. data->restriction = restriction;
  810. changed = true;
  811. }
  812. }
  813. for (const auto &data : d_byUsernameFiltered) {
  814. const auto history = data->history;
  815. const auto restriction = Api::ResolveMessageMoneyRestrictions(
  816. history->peer,
  817. history);
  818. if (data->restriction != restriction) {
  819. data->restriction = restriction;
  820. changed = true;
  821. }
  822. }
  823. if (changed) {
  824. update();
  825. }
  826. }
  827. void ShareBox::Inner::visibleTopBottomUpdated(
  828. int visibleTop,
  829. int visibleBottom) {
  830. _visibleTop = visibleTop;
  831. loadProfilePhotos();
  832. }
  833. void ShareBox::Inner::activateSkipRow(int direction) {
  834. activateSkipColumn(direction * _columnCount);
  835. }
  836. int ShareBox::Inner::displayedChatsCount() const {
  837. return _filter.isEmpty() ? _chatsIndexed->size() : (_filtered.size() + d_byUsernameFiltered.size());
  838. }
  839. void ShareBox::Inner::activateSkipColumn(int direction) {
  840. if (_active < 0) {
  841. if (direction > 0) {
  842. setActive(0);
  843. }
  844. return;
  845. }
  846. auto count = displayedChatsCount();
  847. auto active = _active + direction;
  848. if (active < 0) {
  849. active = (_active > 0) ? 0 : -1;
  850. }
  851. if (active >= count) {
  852. active = count - 1;
  853. }
  854. setActive(active);
  855. }
  856. void ShareBox::Inner::activateSkipPage(int pageHeight, int direction) {
  857. activateSkipRow(direction * (pageHeight / _rowHeight));
  858. }
  859. void ShareBox::Inner::updateChat(not_null<PeerData*> peer) {
  860. if (const auto i = _dataMap.find(peer); i != end(_dataMap)) {
  861. updateChatName(i->second.get());
  862. repaintChat(peer);
  863. }
  864. }
  865. void ShareBox::Inner::updateChatName(not_null<Chat*> chat) {
  866. const auto peer = chat->peer;
  867. const auto text = chat->topic
  868. ? chat->topic->title()
  869. : peer->isSelf()
  870. ? tr::lng_saved_messages(tr::now)
  871. : peer->isRepliesChat()
  872. ? tr::lng_replies_messages(tr::now)
  873. : peer->isVerifyCodes()
  874. ? tr::lng_verification_codes(tr::now)
  875. : peer->name();
  876. chat->name.setText(_st.item.nameStyle, text, Ui::NameTextOptions());
  877. }
  878. void ShareBox::Inner::initChatRestriction(not_null<Chat*> chat) {
  879. if (_descriptor.moneyRestrictionError) {
  880. const auto history = chat->history;
  881. const auto restriction = Api::ResolveMessageMoneyRestrictions(
  882. history->peer,
  883. history);
  884. if (restriction || restriction.known) {
  885. chat->restriction = restriction;
  886. }
  887. }
  888. }
  889. void ShareBox::Inner::repaintChatAtIndex(int index) {
  890. if (index < 0) return;
  891. auto row = index / _columnCount;
  892. auto column = index % _columnCount;
  893. update(style::rtlrect(_rowsLeft + qFloor(column * _rowWidthReal), row * _rowHeight, _rowWidth, _rowHeight, width()));
  894. }
  895. ShareBox::Inner::Chat *ShareBox::Inner::getChatAtIndex(int index) {
  896. if (index < 0) {
  897. return nullptr;
  898. }
  899. const auto row = [=] {
  900. if (_filter.isEmpty()) {
  901. return (index < _chatsIndexed->size())
  902. ? (_chatsIndexed->begin() + index)->get()
  903. : nullptr;
  904. }
  905. return (index < _filtered.size())
  906. ? _filtered[index].get()
  907. : nullptr;
  908. }();
  909. if (row) {
  910. return static_cast<Chat*>(row->attached);
  911. }
  912. if (!_filter.isEmpty()) {
  913. index -= _filtered.size();
  914. if (index >= 0 && index < d_byUsernameFiltered.size()) {
  915. return d_byUsernameFiltered[index].get();
  916. }
  917. }
  918. return nullptr;
  919. }
  920. void ShareBox::Inner::repaintChat(not_null<PeerData*> peer) {
  921. repaintChatAtIndex(chatIndex(peer));
  922. }
  923. int ShareBox::Inner::chatIndex(not_null<PeerData*> peer) const {
  924. int index = 0;
  925. if (_filter.isEmpty()) {
  926. for (const auto &row : _chatsIndexed->all()) {
  927. if (const auto history = row->history()) {
  928. if (history->peer == peer) {
  929. return index;
  930. }
  931. }
  932. ++index;
  933. }
  934. } else {
  935. for (const auto &row : _filtered) {
  936. if (const auto history = row->history()) {
  937. if (history->peer == peer) {
  938. return index;
  939. }
  940. }
  941. ++index;
  942. }
  943. for (const auto &row : d_byUsernameFiltered) {
  944. if (row->peer == peer) {
  945. return index;
  946. }
  947. ++index;
  948. }
  949. }
  950. return -1;
  951. }
  952. void ShareBox::Inner::loadProfilePhotos() {
  953. if (!parentWidget()) {
  954. return;
  955. }
  956. auto yFrom = std::max(_visibleTop, 0);
  957. if (auto part = (yFrom % _rowHeight)) {
  958. yFrom -= part;
  959. }
  960. int yTo = yFrom + parentWidget()->height() * 5 * _columnCount;
  961. if (!yTo) {
  962. return;
  963. }
  964. yFrom *= _columnCount;
  965. yTo *= _columnCount;
  966. if (_filter.isEmpty()) {
  967. if (!_chatsIndexed->empty()) {
  968. const auto index = yFrom / _rowHeight;
  969. auto i = _chatsIndexed->begin()
  970. + std::min(index, _chatsIndexed->size());
  971. for (auto end = _chatsIndexed->cend(); i != end; ++i) {
  972. if (((*i)->index() * _rowHeight) >= yTo) {
  973. break;
  974. }
  975. preloadUserpic((*i)->entry());
  976. }
  977. }
  978. } else {
  979. const auto from = std::max(yFrom / _rowHeight, 0);
  980. const auto to = std::max((yTo / _rowHeight) + 1, from);
  981. const auto fto = std::min(to, int(_filtered.size()));
  982. const auto ffrom = std::min(from, fto);
  983. for (auto i = ffrom; i != fto; ++i) {
  984. preloadUserpic(_filtered[i]->entry());
  985. }
  986. const auto uto = std::min(
  987. to - int(_filtered.size()),
  988. int(d_byUsernameFiltered.size()));
  989. const auto ufrom = std::min(
  990. std::max(from - int(_filtered.size()), 0),
  991. uto);
  992. for (auto i = ufrom; i != uto; ++i) {
  993. preloadUserpic(d_byUsernameFiltered[i]->history);
  994. }
  995. }
  996. }
  997. void ShareBox::Inner::preloadUserpic(not_null<Dialogs::Entry*> entry) {
  998. entry->chatListPreloadData();
  999. const auto history = entry->asHistory();
  1000. if (!_descriptor.moneyRestrictionError || !history) {
  1001. return;
  1002. } else if (!Api::ResolveMessageMoneyRestrictions(
  1003. history->peer,
  1004. history).known) {
  1005. if (const auto user = history->peer->asUser()) {
  1006. const auto api = &_descriptor.session->api();
  1007. api->premium().resolveMessageMoneyRestrictions(user);
  1008. }
  1009. }
  1010. }
  1011. auto ShareBox::Inner::getChat(not_null<Dialogs::Row*> row)
  1012. -> not_null<Chat*> {
  1013. Expects(row->history() != nullptr);
  1014. if (const auto data = static_cast<Chat*>(row->attached)) {
  1015. return data;
  1016. }
  1017. const auto history = row->history();
  1018. const auto peer = history->peer;
  1019. if (const auto i = _dataMap.find(peer); i != end(_dataMap)) {
  1020. row->attached = i->second.get();
  1021. return i->second.get();
  1022. }
  1023. const auto &[i, ok] = _dataMap.emplace(
  1024. peer,
  1025. std::make_unique<Chat>(history, _st.item, [=] {
  1026. repaintChat(peer);
  1027. }));
  1028. updateChatName(i->second.get());
  1029. initChatRestriction(i->second.get());
  1030. row->attached = i->second.get();
  1031. return i->second.get();
  1032. }
  1033. void ShareBox::Inner::setActive(int active) {
  1034. if (active != _active) {
  1035. auto changeNameFg = [this](int index, float64 from, float64 to) {
  1036. if (auto chat = getChatAtIndex(index)) {
  1037. chat->nameActive.start([this, peer = chat->peer] {
  1038. repaintChat(peer);
  1039. }, from, to, st::shareActivateDuration);
  1040. }
  1041. };
  1042. changeNameFg(_active, 1., 0.);
  1043. _active = active;
  1044. changeNameFg(_active, 0., 1.);
  1045. }
  1046. auto y = (_active < _columnCount) ? 0 : (_rowsTop + ((_active / _columnCount) * _rowHeight));
  1047. _scrollToRequests.fire({ y, y + _rowHeight });
  1048. }
  1049. void ShareBox::Inner::paintChat(
  1050. Painter &p,
  1051. not_null<Chat*> chat,
  1052. int index) {
  1053. auto x = _rowsLeft + qFloor((index % _columnCount) * _rowWidthReal);
  1054. auto y = _rowsTop + (index / _columnCount) * _rowHeight;
  1055. auto outerWidth = width();
  1056. auto photoLeft = (_rowWidth - (_st.item.checkbox.imageRadius * 2)) / 2;
  1057. auto photoTop = st::sharePhotoTop;
  1058. chat->checkbox.paint(p, x + photoLeft, y + photoTop, outerWidth);
  1059. if (chat->restriction) {
  1060. PaintRestrictionBadge(
  1061. p,
  1062. &_st.item,
  1063. chat->restriction.starsPerMessage,
  1064. chat->badgeCache,
  1065. x + photoLeft,
  1066. y + photoTop,
  1067. outerWidth,
  1068. _st.item.checkbox.imageRadius * 2);
  1069. }
  1070. auto nameActive = chat->nameActive.value((index == _active) ? 1. : 0.);
  1071. p.setPen(anim::pen(_st.item.nameFg, _st.item.nameFgChecked, nameActive));
  1072. auto nameWidth = (_rowWidth - st::shareColumnSkip);
  1073. auto nameLeft = st::shareColumnSkip / 2;
  1074. auto nameTop = photoTop + _st.item.checkbox.imageRadius * 2 + st::shareNameTop;
  1075. chat->name.drawLeftElided(p, x + nameLeft, y + nameTop, nameWidth, outerWidth, 2, style::al_top, 0, -1, 0, true);
  1076. }
  1077. ShareBox::Inner::Chat::Chat(
  1078. not_null<History*> history,
  1079. const style::PeerListItem &st,
  1080. Fn<void()> updateCallback)
  1081. : history(history)
  1082. , peer(history->peer)
  1083. , checkbox(
  1084. st.checkbox,
  1085. updateCallback,
  1086. PaintUserpicCallback(peer, true),
  1087. [=](int size) { return peer->isForum()
  1088. ? int(size * Ui::ForumUserpicRadiusMultiplier())
  1089. : std::optional<int>(); })
  1090. , name(st.checkbox.imageRadius * 2) {
  1091. }
  1092. void ShareBox::Inner::paintEvent(QPaintEvent *e) {
  1093. Painter p(this);
  1094. auto r = e->rect();
  1095. p.setClipRect(r);
  1096. p.fillRect(r, _st.bg);
  1097. auto yFrom = r.y(), yTo = r.y() + r.height();
  1098. auto rowFrom = yFrom / _rowHeight;
  1099. auto rowTo = (yTo + _rowHeight - 1) / _rowHeight;
  1100. auto indexFrom = rowFrom * _columnCount;
  1101. auto indexTo = rowTo * _columnCount;
  1102. if (_filter.isEmpty()) {
  1103. if (!_chatsIndexed->empty()) {
  1104. auto i = _chatsIndexed->begin()
  1105. + std::min(indexFrom, _chatsIndexed->size());
  1106. for (auto end = _chatsIndexed->cend(); i != end; ++i) {
  1107. if (indexFrom >= indexTo) {
  1108. break;
  1109. }
  1110. paintChat(p, getChat(*i), indexFrom);
  1111. ++indexFrom;
  1112. }
  1113. } else {
  1114. p.setFont(st::noContactsFont);
  1115. p.setPen(_st.about.textFg);
  1116. p.drawText(
  1117. rect().marginsRemoved(st::boxPadding),
  1118. tr::lng_bot_no_chats(tr::now),
  1119. style::al_center);
  1120. }
  1121. } else {
  1122. if (_filtered.empty()
  1123. && _byUsernameFiltered.empty()
  1124. && !_searching) {
  1125. p.setFont(st::noContactsFont);
  1126. p.setPen(_st.about.textFg);
  1127. p.drawText(
  1128. rect().marginsRemoved(st::boxPadding),
  1129. tr::lng_bot_chats_not_found(tr::now),
  1130. style::al_center);
  1131. } else {
  1132. auto filteredSize = _filtered.size();
  1133. if (filteredSize) {
  1134. if (indexFrom < 0) indexFrom = 0;
  1135. while (indexFrom < indexTo) {
  1136. if (indexFrom >= _filtered.size()) {
  1137. break;
  1138. }
  1139. paintChat(p, getChat(_filtered[indexFrom]), indexFrom);
  1140. ++indexFrom;
  1141. }
  1142. indexFrom -= filteredSize;
  1143. indexTo -= filteredSize;
  1144. }
  1145. if (!_byUsernameFiltered.empty()) {
  1146. if (indexFrom < 0) indexFrom = 0;
  1147. while (indexFrom < indexTo) {
  1148. if (indexFrom >= d_byUsernameFiltered.size()) {
  1149. break;
  1150. }
  1151. paintChat(
  1152. p,
  1153. d_byUsernameFiltered[indexFrom].get(),
  1154. filteredSize + indexFrom);
  1155. ++indexFrom;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. }
  1161. void ShareBox::Inner::enterEventHook(QEnterEvent *e) {
  1162. setMouseTracking(true);
  1163. }
  1164. void ShareBox::Inner::leaveEventHook(QEvent *e) {
  1165. setMouseTracking(false);
  1166. }
  1167. void ShareBox::Inner::mouseMoveEvent(QMouseEvent *e) {
  1168. updateUpon(e->pos());
  1169. setCursor((_upon >= 0) ? style::cur_pointer : style::cur_default);
  1170. }
  1171. void ShareBox::Inner::updateUpon(const QPoint &pos) {
  1172. auto x = pos.x(), y = pos.y();
  1173. auto row = (y - _rowsTop) / _rowHeight;
  1174. auto column = qFloor((x - _rowsLeft) / _rowWidthReal);
  1175. auto left = _rowsLeft + qFloor(column * _rowWidthReal) + st::shareColumnSkip / 2;
  1176. auto top = _rowsTop + row * _rowHeight + st::sharePhotoTop;
  1177. auto xupon = (x >= left) && (x < left + (_rowWidth - st::shareColumnSkip));
  1178. auto yupon = (y >= top) && (y < top + _st.item.checkbox.imageRadius * 2 + st::shareNameTop + _st.item.nameStyle.font->height * 2);
  1179. auto upon = (xupon && yupon) ? (row * _columnCount + column) : -1;
  1180. if (upon >= displayedChatsCount()) {
  1181. upon = -1;
  1182. }
  1183. _upon = upon;
  1184. }
  1185. void ShareBox::Inner::mousePressEvent(QMouseEvent *e) {
  1186. if (e->button() == Qt::LeftButton) {
  1187. updateUpon(e->pos());
  1188. changeCheckState(getChatAtIndex(_upon));
  1189. }
  1190. }
  1191. void ShareBox::Inner::selectActive() {
  1192. changeCheckState(getChatAtIndex(_active > 0 ? _active : 0));
  1193. }
  1194. void ShareBox::Inner::resizeEvent(QResizeEvent *e) {
  1195. _columnSkip = (width() - _columnCount * _st.item.checkbox.imageRadius * 2) / float64(_columnCount + 1);
  1196. _rowWidthReal = _st.item.checkbox.imageRadius * 2 + _columnSkip;
  1197. _rowsLeft = qFloor(_columnSkip / 2);
  1198. _rowWidth = qFloor(_rowWidthReal);
  1199. update();
  1200. }
  1201. void ShareBox::Inner::changeCheckState(Chat *chat) {
  1202. if (!chat || showLockedError(chat)) {
  1203. return;
  1204. } else if (!_filter.isEmpty()) {
  1205. const auto history = chat->peer->owner().history(chat->peer);
  1206. auto row = _chatsIndexed->getRow(history);
  1207. if (!row) {
  1208. row = _chatsIndexed->addToEnd(history).main;
  1209. }
  1210. chat = getChat(row);
  1211. if (!chat->checkbox.checked()) {
  1212. _chatsIndexed->moveToTop(history);
  1213. }
  1214. }
  1215. const auto checked = chat->checkbox.checked();
  1216. const auto forum = chat->peer->forum();
  1217. if (checked || !forum) {
  1218. changePeerCheckState(chat, !checked);
  1219. } else {
  1220. chooseForumTopic(chat->peer->forum());
  1221. }
  1222. }
  1223. void ShareBox::Inner::chooseForumTopic(not_null<Data::Forum*> forum) {
  1224. const auto guard = Ui::MakeWeak(this);
  1225. const auto weak = std::make_shared<QPointer<Ui::BoxContent>>();
  1226. auto chosen = [=](not_null<Data::ForumTopic*> topic) {
  1227. if (const auto strong = *weak) {
  1228. strong->closeBox();
  1229. }
  1230. if (!guard) {
  1231. return;
  1232. }
  1233. const auto row = _chatsIndexed->getRow(topic->owningHistory());
  1234. if (!row) {
  1235. return;
  1236. }
  1237. const auto chat = getChat(row);
  1238. Assert(!chat->topic);
  1239. chat->topic = topic;
  1240. chat->topic->destroyed(
  1241. ) | rpl::start_with_next([=] {
  1242. changePeerCheckState(chat, false);
  1243. }, chat->topicLifetime);
  1244. updateChatName(chat);
  1245. changePeerCheckState(chat, true);
  1246. };
  1247. auto initBox = [=](not_null<PeerListBox*> box) {
  1248. box->addButton(tr::lng_cancel(), [=] {
  1249. box->closeBox();
  1250. });
  1251. forum->destroyed(
  1252. ) | rpl::start_with_next([=] {
  1253. box->closeBox();
  1254. }, box->lifetime());
  1255. };
  1256. auto filter = [=](not_null<Data::ForumTopic*> topic) {
  1257. return guard && _descriptor.filterCallback(topic);
  1258. };
  1259. auto box = Box<PeerListBox>(
  1260. std::make_unique<ChooseTopicBoxController>(
  1261. forum,
  1262. std::move(chosen),
  1263. std::move(filter)),
  1264. std::move(initBox));
  1265. *weak = box.data();
  1266. _show->showBox(std::move(box));
  1267. }
  1268. void ShareBox::Inner::peerUnselected(not_null<PeerData*> peer) {
  1269. if (const auto i = _dataMap.find(peer); i != end(_dataMap)) {
  1270. changePeerCheckState(
  1271. i->second.get(),
  1272. false,
  1273. ChangeStateWay::SkipCallback);
  1274. }
  1275. }
  1276. void ShareBox::Inner::setPeerSelectedChangedCallback(
  1277. Fn<void(not_null<Data::Thread*> thread, bool selected)> callback) {
  1278. _peerSelectedChangedCallback = std::move(callback);
  1279. }
  1280. void ShareBox::Inner::changePeerCheckState(
  1281. not_null<Chat*> chat,
  1282. bool checked,
  1283. ChangeStateWay useCallback) {
  1284. chat->checkbox.setChecked(checked);
  1285. const auto thread = chatThread(chat);
  1286. if (checked) {
  1287. _selected.emplace(thread);
  1288. setActive(chatIndex(chat->peer));
  1289. } else {
  1290. _selected.remove(thread);
  1291. if (chat->topic) {
  1292. chat->topicLifetime.destroy();
  1293. chat->topic = nullptr;
  1294. updateChatName(chat);
  1295. }
  1296. }
  1297. if (useCallback != ChangeStateWay::SkipCallback
  1298. && _peerSelectedChangedCallback) {
  1299. _peerSelectedChangedCallback(thread, checked);
  1300. }
  1301. }
  1302. bool ShareBox::Inner::hasSelected() const {
  1303. return _selected.size();
  1304. }
  1305. void ShareBox::Inner::updateFilter(QString filter) {
  1306. _lastQuery = filter.toLower().trimmed();
  1307. auto words = TextUtilities::PrepareSearchWords(_lastQuery);
  1308. filter = words.isEmpty() ? QString() : words.join(' ');
  1309. if (_filter != filter) {
  1310. _filter = filter;
  1311. _byUsernameFiltered.clear();
  1312. d_byUsernameFiltered.clear();
  1313. if (_filter.isEmpty()) {
  1314. refresh();
  1315. } else {
  1316. _filtered = _chatsIndexed->filtered(words);
  1317. refresh();
  1318. _searching = true;
  1319. _searchRequests.fire({});
  1320. }
  1321. setActive(-1);
  1322. loadProfilePhotos();
  1323. update();
  1324. }
  1325. }
  1326. bool ShareBox::Inner::isFilterEmpty() const {
  1327. return _filter.isEmpty();
  1328. }
  1329. rpl::producer<Ui::ScrollToRequest> ShareBox::Inner::scrollToRequests() const {
  1330. return _scrollToRequests.events();
  1331. }
  1332. rpl::producer<> ShareBox::Inner::searchRequests() const {
  1333. return _searchRequests.events();
  1334. }
  1335. void ShareBox::Inner::applyChatFilter(FilterId id) {
  1336. if (!id) {
  1337. _chatsIndexed = _defaultChatsIndexed.get();
  1338. } else {
  1339. _customChatsIndexed = std::make_unique<Dialogs::IndexedList>(
  1340. Dialogs::SortMode::Add);
  1341. _chatsIndexed = _customChatsIndexed.get();
  1342. const auto addList = [&](not_null<Dialogs::IndexedList*> list) {
  1343. for (const auto &row : list->all()) {
  1344. if (const auto history = row->history()) {
  1345. if (history->asForum()
  1346. || _descriptor.filterCallback(history)) {
  1347. _customChatsIndexed->addToEnd(history);
  1348. }
  1349. }
  1350. }
  1351. };
  1352. const auto &data = _descriptor.session->data();
  1353. addList(data.chatsFilters().chatsList(id)->indexed());
  1354. }
  1355. update();
  1356. }
  1357. void ShareBox::Inner::peopleReceived(
  1358. const QString &query,
  1359. const QVector<MTPPeer> &my,
  1360. const QVector<MTPPeer> &people) {
  1361. _lastQuery = query.toLower().trimmed();
  1362. if (_lastQuery.at(0) == '@') {
  1363. _lastQuery = _lastQuery.mid(1);
  1364. }
  1365. int32 already = _byUsernameFiltered.size();
  1366. _byUsernameFiltered.reserve(already + my.size() + people.size());
  1367. d_byUsernameFiltered.reserve(already + my.size() + people.size());
  1368. const auto feedList = [&](const QVector<MTPPeer> &list) {
  1369. for (const auto &data : list) {
  1370. if (const auto peer = _descriptor.session->data().peerLoaded(
  1371. peerFromMTP(data))) {
  1372. const auto history = _descriptor.session->data().history(
  1373. peer);
  1374. if (!history->asForum()
  1375. && !_descriptor.filterCallback(history)) {
  1376. continue;
  1377. } else if (history && _chatsIndexed->getRow(history)) {
  1378. continue;
  1379. } else if (base::contains(_byUsernameFiltered, peer)) {
  1380. continue;
  1381. }
  1382. _byUsernameFiltered.push_back(peer);
  1383. d_byUsernameFiltered.push_back(std::make_unique<Chat>(
  1384. history,
  1385. _st.item,
  1386. [=] { repaintChat(peer); }));
  1387. updateChatName(d_byUsernameFiltered.back().get());
  1388. initChatRestriction(d_byUsernameFiltered.back().get());
  1389. }
  1390. }
  1391. };
  1392. feedList(my);
  1393. feedList(people);
  1394. _searching = false;
  1395. refresh();
  1396. }
  1397. void ShareBox::Inner::refresh() {
  1398. auto count = displayedChatsCount();
  1399. if (count) {
  1400. auto rows = (count / _columnCount) + (count % _columnCount ? 1 : 0);
  1401. resize(width(), _rowsTop + rows * _rowHeight);
  1402. } else {
  1403. resize(width(), st::noContactsHeight);
  1404. }
  1405. loadProfilePhotos();
  1406. update();
  1407. }
  1408. not_null<Data::Thread*> ShareBox::Inner::chatThread(
  1409. not_null<Chat*> chat) const {
  1410. return chat->topic
  1411. ? (Data::Thread*)chat->topic
  1412. : chat->peer->owner().history(chat->peer).get();
  1413. }
  1414. std::vector<not_null<Data::Thread*>> ShareBox::Inner::selected() const {
  1415. auto result = std::vector<not_null<Data::Thread*>>();
  1416. result.reserve(_dataMap.size());
  1417. for (const auto &[peer, chat] : _dataMap) {
  1418. if (chat->checkbox.checked()) {
  1419. result.push_back(chatThread(chat.get()));
  1420. }
  1421. }
  1422. return result;
  1423. }
  1424. ChatHelpers::ForwardedMessagePhraseArgs CreateForwardedMessagePhraseArgs(
  1425. const std::vector<not_null<Data::Thread*>> &result,
  1426. const MessageIdsList &msgIds) {
  1427. const auto toCount = result.size();
  1428. return {
  1429. .toCount = result.size(),
  1430. .singleMessage = (msgIds.size() <= 1),
  1431. .to1 = (toCount > 0) ? result.front()->peer().get() : nullptr,
  1432. .to2 = (toCount > 1) ? result[1]->peer().get() : nullptr,
  1433. };
  1434. }
  1435. ShareBox::CountMessagesCallback ShareBox::DefaultForwardCountMessages(
  1436. not_null<History*> history,
  1437. MessageIdsList msgIds) {
  1438. return [=](const TextWithTags &comment) {
  1439. const auto items = history->owner().idsToItems(msgIds);
  1440. return int(items.size()) + (comment.empty() ? 0 : 1);
  1441. };
  1442. }
  1443. ShareBox::SubmitCallback ShareBox::DefaultForwardCallback(
  1444. std::shared_ptr<Ui::Show> show,
  1445. not_null<History*> history,
  1446. MessageIdsList msgIds,
  1447. std::optional<TimeId> videoTimestamp) {
  1448. struct State final {
  1449. base::flat_set<mtpRequestId> requests;
  1450. };
  1451. const auto state = std::make_shared<State>();
  1452. return [=](
  1453. std::vector<not_null<Data::Thread*>> &&result,
  1454. Fn<bool()> checkPaid,
  1455. TextWithTags comment,
  1456. Api::SendOptions options,
  1457. Data::ForwardOptions forwardOptions) {
  1458. if (!state->requests.empty()) {
  1459. return; // Share clicked already.
  1460. }
  1461. const auto items = history->owner().idsToItems(msgIds);
  1462. const auto existingIds = history->owner().itemsToIds(items);
  1463. if (existingIds.empty() || result.empty()) {
  1464. return;
  1465. }
  1466. const auto error = GetErrorForSending(
  1467. result,
  1468. { .forward = &items, .text = &comment });
  1469. if (error.error) {
  1470. show->showBox(MakeSendErrorBox(error, result.size() > 1));
  1471. return;
  1472. } else if (!checkPaid()) {
  1473. return;
  1474. }
  1475. using Flag = MTPmessages_ForwardMessages::Flag;
  1476. const auto commonSendFlags = Flag(0)
  1477. | Flag::f_with_my_score
  1478. | (options.scheduled ? Flag::f_schedule_date : Flag(0))
  1479. | ((forwardOptions != Data::ForwardOptions::PreserveInfo)
  1480. ? Flag::f_drop_author
  1481. : Flag(0))
  1482. | ((forwardOptions == Data::ForwardOptions::NoNamesAndCaptions)
  1483. ? Flag::f_drop_media_captions
  1484. : Flag(0))
  1485. | (videoTimestamp.has_value()
  1486. ? Flag::f_video_timestamp
  1487. : Flag(0));
  1488. auto mtpMsgIds = QVector<MTPint>();
  1489. mtpMsgIds.reserve(existingIds.size());
  1490. for (const auto &fullId : existingIds) {
  1491. mtpMsgIds.push_back(MTP_int(fullId.msg));
  1492. }
  1493. const auto generateRandom = [&] {
  1494. auto result = QVector<MTPlong>(existingIds.size());
  1495. for (auto &value : result) {
  1496. value = base::RandomValue<MTPlong>();
  1497. }
  1498. return result;
  1499. };
  1500. auto &api = history->owner().session().api();
  1501. auto &histories = history->owner().histories();
  1502. const auto donePhraseArgs = CreateForwardedMessagePhraseArgs(
  1503. result,
  1504. msgIds);
  1505. const auto requestType = Data::Histories::RequestType::Send;
  1506. for (const auto thread : result) {
  1507. if (!comment.text.isEmpty()) {
  1508. auto message = Api::MessageToSend(
  1509. Api::SendAction(thread, options));
  1510. message.textWithTags = comment;
  1511. message.action.clearDraft = false;
  1512. api.sendMessage(std::move(message));
  1513. }
  1514. const auto topicRootId = thread->topicRootId();
  1515. const auto kGeneralId = Data::ForumTopic::kGeneralId;
  1516. const auto topMsgId = (topicRootId == kGeneralId)
  1517. ? MsgId(0)
  1518. : topicRootId;
  1519. const auto peer = thread->peer();
  1520. const auto threadHistory = thread->owningHistory();
  1521. const auto starsPaid = std::min(
  1522. peer->starsPerMessageChecked(),
  1523. options.starsApproved);
  1524. if (starsPaid) {
  1525. options.starsApproved -= starsPaid;
  1526. }
  1527. histories.sendRequest(threadHistory, requestType, [=](
  1528. Fn<void()> finish) {
  1529. const auto session = &threadHistory->session();
  1530. auto &api = session->api();
  1531. const auto sendFlags = commonSendFlags
  1532. | (topMsgId ? Flag::f_top_msg_id : Flag(0))
  1533. | (ShouldSendSilent(peer, options)
  1534. ? Flag::f_silent
  1535. : Flag(0))
  1536. | (options.shortcutId
  1537. ? Flag::f_quick_reply_shortcut
  1538. : Flag(0))
  1539. | (starsPaid ? Flag::f_allow_paid_stars : Flag());
  1540. threadHistory->sendRequestId = api.request(
  1541. MTPmessages_ForwardMessages(
  1542. MTP_flags(sendFlags),
  1543. history->peer->input,
  1544. MTP_vector<MTPint>(mtpMsgIds),
  1545. MTP_vector<MTPlong>(generateRandom()),
  1546. peer->input,
  1547. MTP_int(topMsgId),
  1548. MTP_int(options.scheduled),
  1549. MTP_inputPeerEmpty(), // send_as
  1550. Data::ShortcutIdToMTP(session, options.shortcutId),
  1551. MTP_int(videoTimestamp.value_or(0)),
  1552. MTP_long(starsPaid)
  1553. )).done([=](const MTPUpdates &updates, mtpRequestId reqId) {
  1554. threadHistory->session().api().applyUpdates(updates);
  1555. state->requests.remove(reqId);
  1556. if (state->requests.empty()) {
  1557. if (show->valid()) {
  1558. auto phrase = rpl::variable<TextWithEntities>(
  1559. ChatHelpers::ForwardedMessagePhrase(
  1560. donePhraseArgs)).current();
  1561. show->showToast(std::move(phrase));
  1562. show->hideLayer();
  1563. }
  1564. }
  1565. finish();
  1566. }).fail([=](const MTP::Error &error) {
  1567. const auto type = error.type();
  1568. if (type.startsWith(u"ALLOW_PAYMENT_REQUIRED_"_q)) {
  1569. show->showToast(u"Payment requirements changed. "
  1570. "Please, try again."_q);
  1571. } else if (type == u"VOICE_MESSAGES_FORBIDDEN"_q) {
  1572. show->showToast(
  1573. tr::lng_restricted_send_voice_messages(
  1574. tr::now,
  1575. lt_user,
  1576. peer->name()));
  1577. }
  1578. finish();
  1579. }).afterRequest(threadHistory->sendRequestId).send();
  1580. return threadHistory->sendRequestId;
  1581. });
  1582. state->requests.insert(threadHistory->sendRequestId);
  1583. }
  1584. };
  1585. }
  1586. ShareBoxStyleOverrides DarkShareBoxStyle() {
  1587. using namespace HistoryView;
  1588. const auto schedule = [&] {
  1589. auto date = Ui::ChooseDateTimeStyleArgs();
  1590. date.labelStyle = &st::groupCallBoxLabel;
  1591. date.dateFieldStyle = &st::groupCallScheduleDateField;
  1592. date.timeFieldStyle = &st::groupCallScheduleTimeField;
  1593. date.separatorStyle = &st::callMuteButtonLabel;
  1594. date.atStyle = &st::callMuteButtonLabel;
  1595. date.calendarStyle = &st::groupCallCalendarColors;
  1596. auto st = ScheduleBoxStyleArgs();
  1597. st.topButtonStyle = &st::groupCallMenuToggle;
  1598. st.popupMenuStyle = &st::groupCallPopupMenu;
  1599. st.chooseDateTimeArgs = std::move(date);
  1600. return st;
  1601. };
  1602. return {
  1603. .multiSelect = &st::groupCallMultiSelect,
  1604. .comment = &st::groupCallShareBoxComment,
  1605. .peerList = &st::groupCallShareBoxList,
  1606. .label = &st::groupCallField,
  1607. .checkbox = &st::groupCallCheckbox,
  1608. .scheduleBox = std::make_shared<ScheduleBoxStyleArgs>(schedule()),
  1609. };
  1610. }
  1611. void FastShareMessage(
  1612. std::shared_ptr<Main::SessionShow> show,
  1613. not_null<HistoryItem*> item,
  1614. ShareBoxStyleOverrides st) {
  1615. const auto history = item->history();
  1616. const auto owner = &history->owner();
  1617. const auto session = &history->session();
  1618. const auto msgIds = owner->itemOrItsGroup(item);
  1619. const auto isGame = item->getMessageBot()
  1620. && item->media()
  1621. && (item->media()->game() != nullptr);
  1622. const auto canCopyLink = item->hasDirectLink() || isGame;
  1623. const auto items = owner->idsToItems(msgIds);
  1624. const auto hasCaptions = ranges::any_of(items, [](auto item) {
  1625. return item->media()
  1626. && !item->originalText().text.isEmpty()
  1627. && item->media()->allowsEditCaption();
  1628. });
  1629. const auto hasOnlyForcedForwardedInfo = hasCaptions
  1630. ? false
  1631. : ranges::all_of(items, [](auto item) {
  1632. return item->media() && item->media()->forceForwardedInfo();
  1633. });
  1634. auto copyCallback = [=] {
  1635. const auto item = owner->message(msgIds[0]);
  1636. if (!item) {
  1637. return;
  1638. }
  1639. if (item->hasDirectLink()) {
  1640. using namespace HistoryView;
  1641. CopyPostLink(show, item->fullId(), Context::History);
  1642. } else if (const auto bot = item->getMessageBot()) {
  1643. if (const auto media = item->media()) {
  1644. if (const auto game = media->game()) {
  1645. const auto link = session->createInternalLinkFull(
  1646. bot->username() + u"?game="_q + game->shortName);
  1647. QGuiApplication::clipboard()->setText(link);
  1648. show->showToast(
  1649. tr::lng_share_game_link_copied(tr::now));
  1650. }
  1651. }
  1652. }
  1653. };
  1654. const auto requiredRight = item->requiredSendRight();
  1655. const auto requiresInline = item->requiresSendInlineRight();
  1656. auto filterCallback = [=](not_null<Data::Thread*> thread) {
  1657. if (const auto user = thread->peer()->asUser()) {
  1658. if (user->canSendIgnoreMoneyRestrictions()) {
  1659. return true;
  1660. }
  1661. }
  1662. return Data::CanSend(thread, requiredRight)
  1663. && (!requiresInline
  1664. || Data::CanSend(thread, ChatRestriction::SendInline))
  1665. && (!isGame || !thread->peer()->isBroadcast());
  1666. };
  1667. auto copyLinkCallback = canCopyLink
  1668. ? Fn<void()>(std::move(copyCallback))
  1669. : Fn<void()>();
  1670. show->show(Box<ShareBox>(ShareBox::Descriptor{
  1671. .session = session,
  1672. .copyCallback = std::move(copyLinkCallback),
  1673. .countMessagesCallback = ShareBox::DefaultForwardCountMessages(
  1674. history,
  1675. msgIds),
  1676. .submitCallback = ShareBox::DefaultForwardCallback(
  1677. show,
  1678. history,
  1679. msgIds),
  1680. .filterCallback = std::move(filterCallback),
  1681. .st = st,
  1682. .forwardOptions = {
  1683. .sendersCount = ItemsForwardSendersCount(items),
  1684. .captionsCount = ItemsForwardCaptionsCount(items),
  1685. .show = !hasOnlyForcedForwardedInfo,
  1686. },
  1687. .moneyRestrictionError = ShareMessageMoneyRestrictionError(),
  1688. }), Ui::LayerOption::CloseOther);
  1689. }
  1690. void FastShareMessage(
  1691. not_null<Window::SessionController*> controller,
  1692. not_null<HistoryItem*> item,
  1693. ShareBoxStyleOverrides st) {
  1694. FastShareMessage(controller->uiShow(), item, st);
  1695. }
  1696. void FastShareLink(
  1697. not_null<Window::SessionController*> controller,
  1698. const QString &url,
  1699. ShareBoxStyleOverrides st) {
  1700. FastShareLink(controller->uiShow(), url, st);
  1701. }
  1702. void FastShareLink(
  1703. std::shared_ptr<Main::SessionShow> show,
  1704. const QString &url,
  1705. ShareBoxStyleOverrides st) {
  1706. const auto box = std::make_shared<QPointer<Ui::BoxContent>>();
  1707. const auto sending = std::make_shared<bool>();
  1708. auto copyCallback = [=] {
  1709. QGuiApplication::clipboard()->setText(url);
  1710. show->showToast(tr::lng_background_link_copied(tr::now));
  1711. };
  1712. auto countMessagesCallback = [=](const TextWithTags &comment) {
  1713. return 1;
  1714. };
  1715. auto submitCallback = [=](
  1716. std::vector<not_null<::Data::Thread*>> &&result,
  1717. Fn<bool()> checkPaid,
  1718. TextWithTags &&comment,
  1719. Api::SendOptions options,
  1720. ::Data::ForwardOptions) {
  1721. if (*sending || result.empty()) {
  1722. return;
  1723. }
  1724. const auto error = GetErrorForSending(
  1725. result,
  1726. { .text = &comment });
  1727. if (error.error) {
  1728. if (const auto weak = *box) {
  1729. weak->getDelegate()->show(
  1730. MakeSendErrorBox(error, result.size() > 1));
  1731. }
  1732. return;
  1733. } else if (!checkPaid()) {
  1734. return;
  1735. }
  1736. *sending = true;
  1737. if (!comment.text.isEmpty()) {
  1738. comment.text = url + "\n" + comment.text;
  1739. const auto add = url.size() + 1;
  1740. for (auto &tag : comment.tags) {
  1741. tag.offset += add;
  1742. }
  1743. } else {
  1744. comment.text = url;
  1745. }
  1746. auto &api = show->session().api();
  1747. for (const auto thread : result) {
  1748. auto message = Api::MessageToSend(
  1749. Api::SendAction(thread, options));
  1750. message.textWithTags = comment;
  1751. message.action.clearDraft = false;
  1752. api.sendMessage(std::move(message));
  1753. }
  1754. if (*box) {
  1755. (*box)->closeBox();
  1756. }
  1757. show->showToast(tr::lng_share_done(tr::now));
  1758. };
  1759. auto filterCallback = [](not_null<::Data::Thread*> thread) {
  1760. if (const auto user = thread->peer()->asUser()) {
  1761. if (user->canSendIgnoreMoneyRestrictions()) {
  1762. return true;
  1763. }
  1764. }
  1765. return ::Data::CanSend(thread, ChatRestriction::SendOther);
  1766. };
  1767. *box = show->show(
  1768. Box<ShareBox>(ShareBox::Descriptor{
  1769. .session = &show->session(),
  1770. .copyCallback = std::move(copyCallback),
  1771. .countMessagesCallback = std::move(countMessagesCallback),
  1772. .submitCallback = std::move(submitCallback),
  1773. .filterCallback = std::move(filterCallback),
  1774. .st = st,
  1775. .moneyRestrictionError = ShareMessageMoneyRestrictionError(),
  1776. }),
  1777. Ui::LayerOption::KeepOther,
  1778. anim::type::normal);
  1779. }
  1780. auto ShareMessageMoneyRestrictionError()
  1781. -> Fn<RecipientMoneyRestrictionError(not_null<UserData*>)> {
  1782. return WriteMoneyRestrictionError;
  1783. }