field_autocomplete.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819
  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 "chat_helpers/field_autocomplete.h"
  8. #include "data/business/data_shortcut_messages.h"
  9. #include "data/data_document.h"
  10. #include "data/data_document_media.h"
  11. #include "data/data_changes.h"
  12. #include "data/data_channel.h"
  13. #include "data/data_chat.h"
  14. #include "data/data_user.h"
  15. #include "data/data_peer_values.h"
  16. #include "data/data_file_origin.h"
  17. #include "data/data_session.h"
  18. #include "data/stickers/data_stickers.h"
  19. #include "menu/menu_send.h" // SendMenu::FillSendMenu
  20. #include "chat_helpers/stickers_lottie.h"
  21. #include "chat_helpers/message_field.h" // PrepareMentionTag.
  22. #include "chat_helpers/tabbed_selector.h" // ChatHelpers::FileChosen.
  23. #include "mainwindow.h"
  24. #include "apiwrap.h"
  25. #include "api/api_chat_participants.h"
  26. #include "main/main_session.h"
  27. #include "storage/storage_account.h"
  28. #include "core/application.h"
  29. #include "core/core_settings.h"
  30. #include "lang/lang_keys.h"
  31. #include "lottie/lottie_single_player.h"
  32. #include "media/clip/media_clip_reader.h"
  33. #include "ui/widgets/popup_menu.h"
  34. #include "ui/widgets/scroll_area.h"
  35. #include "ui/widgets/fields/input_field.h"
  36. #include "ui/text/text_options.h"
  37. #include "ui/image/image.h"
  38. #include "ui/effects/path_shift_gradient.h"
  39. #include "ui/painter.h"
  40. #include "ui/ui_utility.h"
  41. #include "ui/cached_round_corners.h"
  42. #include "base/unixtime.h"
  43. #include "base/random.h"
  44. #include "base/qt/qt_common_adapters.h"
  45. #include "boxes/sticker_set_box.h"
  46. #include "window/window_adaptive.h"
  47. #include "window/window_session_controller.h"
  48. #include "styles/style_chat.h"
  49. #include "styles/style_widgets.h"
  50. #include "styles/style_chat_helpers.h"
  51. #include "styles/style_menu_icons.h"
  52. #include <QtWidgets/QApplication>
  53. namespace ChatHelpers {
  54. namespace {
  55. [[nodiscard]] QString PrimaryUsername(not_null<UserData*> user) {
  56. const auto &usernames = user->usernames();
  57. return usernames.empty() ? user->username() : usernames.front();
  58. }
  59. template <typename T, typename U>
  60. inline int indexOfInFirstN(const T &v, const U &elem, int last) {
  61. for (auto b = v.cbegin(), i = b, e = b + std::max(int(v.size()), last)
  62. ; i != e
  63. ; ++i) {
  64. if (i->user == elem) {
  65. return (i - b);
  66. }
  67. }
  68. return -1;
  69. }
  70. } // namespace
  71. class FieldAutocomplete::Inner final : public Ui::RpWidget {
  72. public:
  73. struct ScrollTo {
  74. int top;
  75. int bottom;
  76. };
  77. Inner(
  78. std::shared_ptr<Show> show,
  79. const style::EmojiPan &st,
  80. not_null<FieldAutocomplete*> parent,
  81. not_null<MentionRows*> mrows,
  82. not_null<HashtagRows*> hrows,
  83. not_null<BotCommandRows*> brows,
  84. not_null<StickerRows*> srows);
  85. void clearSel(bool hidden = false);
  86. bool moveSel(int key);
  87. bool chooseSelected(FieldAutocomplete::ChooseMethod method) const;
  88. bool chooseAtIndex(
  89. FieldAutocomplete::ChooseMethod method,
  90. int index,
  91. Api::SendOptions options = {}) const;
  92. void setRecentInlineBotsInRows(int32 bots);
  93. void setSendMenuDetails(Fn<SendMenu::Details()> &&callback);
  94. void rowsUpdated();
  95. rpl::producer<FieldAutocomplete::MentionChosen> mentionChosen() const;
  96. rpl::producer<FieldAutocomplete::HashtagChosen> hashtagChosen() const;
  97. rpl::producer<FieldAutocomplete::BotCommandChosen>
  98. botCommandChosen() const;
  99. rpl::producer<FieldAutocomplete::StickerChosen> stickerChosen() const;
  100. rpl::producer<ScrollTo> scrollToRequested() const;
  101. void onParentGeometryChanged();
  102. private:
  103. void paintEvent(QPaintEvent *e) override;
  104. void resizeEvent(QResizeEvent *e) override;
  105. void enterEventHook(QEnterEvent *e) override;
  106. void leaveEventHook(QEvent *e) override;
  107. void mousePressEvent(QMouseEvent *e) override;
  108. void mouseMoveEvent(QMouseEvent *e) override;
  109. void mouseReleaseEvent(QMouseEvent *e) override;
  110. void contextMenuEvent(QContextMenuEvent *e) override;
  111. QRect selectedRect(int index) const;
  112. void updateSelectedRow();
  113. void setSel(int sel, bool scroll = false);
  114. void showPreview();
  115. void selectByMouse(QPoint global);
  116. QSize stickerBoundingBox() const;
  117. void setupLottie(StickerSuggestion &suggestion);
  118. void setupWebm(StickerSuggestion &suggestion);
  119. void repaintSticker(not_null<DocumentData*> document);
  120. void repaintStickerAtIndex(int index);
  121. std::shared_ptr<Lottie::FrameRenderer> getLottieRenderer();
  122. void clipCallback(
  123. Media::Clip::Notification notification,
  124. not_null<DocumentData*> document);
  125. const std::shared_ptr<Show> _show;
  126. const not_null<Main::Session*> _session;
  127. const style::EmojiPan &_st;
  128. const not_null<FieldAutocomplete*> _parent;
  129. const not_null<MentionRows*> _mrows;
  130. const not_null<HashtagRows*> _hrows;
  131. const not_null<BotCommandRows*> _brows;
  132. const not_null<StickerRows*> _srows;
  133. Ui::RoundRect _overBg;
  134. rpl::lifetime _stickersLifetime;
  135. std::weak_ptr<Lottie::FrameRenderer> _lottieRenderer;
  136. base::unique_qptr<Ui::PopupMenu> _menu;
  137. int _stickersPerRow = 1;
  138. int _recentInlineBotsInRows = 0;
  139. int _sel = -1;
  140. int _down = -1;
  141. std::optional<QPoint> _lastMousePosition;
  142. bool _mouseSelection = false;
  143. bool _overDelete = false;
  144. bool _previewShown = false;
  145. bool _adjustShadowLeft = false;
  146. const std::unique_ptr<Ui::PathShiftGradient> _pathGradient;
  147. StickerPremiumMark _premiumMark;
  148. Fn<SendMenu::Details()> _sendMenuDetails;
  149. rpl::event_stream<FieldAutocomplete::MentionChosen> _mentionChosen;
  150. rpl::event_stream<FieldAutocomplete::HashtagChosen> _hashtagChosen;
  151. rpl::event_stream<FieldAutocomplete::BotCommandChosen> _botCommandChosen;
  152. rpl::event_stream<FieldAutocomplete::StickerChosen> _stickerChosen;
  153. rpl::event_stream<ScrollTo> _scrollToRequested;
  154. base::Timer _previewTimer;
  155. };
  156. struct FieldAutocomplete::StickerSuggestion {
  157. not_null<DocumentData*> document;
  158. std::shared_ptr<Data::DocumentMedia> documentMedia;
  159. std::unique_ptr<Lottie::SinglePlayer> lottie;
  160. Media::Clip::ReaderPointer webm;
  161. QImage premiumLock;
  162. };
  163. struct FieldAutocomplete::MentionRow {
  164. not_null<UserData*> user;
  165. Ui::Text::String name;
  166. Ui::PeerUserpicView userpic;
  167. };
  168. struct FieldAutocomplete::BotCommandRow {
  169. not_null<UserData*> user;
  170. QString command;
  171. QString description;
  172. Ui::PeerUserpicView userpic;
  173. Ui::Text::String descriptionText;
  174. };
  175. FieldAutocomplete::FieldAutocomplete(
  176. QWidget *parent,
  177. std::shared_ptr<Show> show,
  178. const style::EmojiPan *stOverride)
  179. : RpWidget(parent)
  180. , _show(std::move(show))
  181. , _session(&_show->session())
  182. , _st(stOverride ? *stOverride : st::defaultEmojiPan)
  183. , _scroll(this) {
  184. hide();
  185. _scroll->setGeometry(rect());
  186. _inner = _scroll->setOwnedWidget(
  187. object_ptr<Inner>(
  188. _show,
  189. _st,
  190. this,
  191. &_mrows,
  192. &_hrows,
  193. &_brows,
  194. &_srows));
  195. _inner->setGeometry(rect());
  196. _inner->scrollToRequested(
  197. ) | rpl::start_with_next([=](Inner::ScrollTo data) {
  198. _scroll->scrollToY(data.top, data.bottom);
  199. }, lifetime());
  200. _scroll->show();
  201. _inner->show();
  202. hide();
  203. _scroll->geometryChanged(
  204. ) | rpl::start_with_next(crl::guard(_inner, [=] {
  205. _inner->onParentGeometryChanged();
  206. }), lifetime());
  207. }
  208. std::shared_ptr<Show> FieldAutocomplete::uiShow() const {
  209. return _show;
  210. }
  211. void FieldAutocomplete::requestRefresh() {
  212. _refreshRequests.fire({});
  213. }
  214. rpl::producer<> FieldAutocomplete::refreshRequests() const {
  215. return _refreshRequests.events();
  216. }
  217. void FieldAutocomplete::requestStickersUpdate() {
  218. _stickersUpdateRequests.fire({});
  219. }
  220. rpl::producer<> FieldAutocomplete::stickersUpdateRequests() const {
  221. return _stickersUpdateRequests.events();
  222. }
  223. auto FieldAutocomplete::mentionChosen() const
  224. -> rpl::producer<FieldAutocomplete::MentionChosen> {
  225. return _inner->mentionChosen();
  226. }
  227. auto FieldAutocomplete::hashtagChosen() const
  228. -> rpl::producer<FieldAutocomplete::HashtagChosen> {
  229. return _inner->hashtagChosen();
  230. }
  231. auto FieldAutocomplete::botCommandChosen() const
  232. -> rpl::producer<FieldAutocomplete::BotCommandChosen> {
  233. return _inner->botCommandChosen();
  234. }
  235. auto FieldAutocomplete::stickerChosen() const
  236. -> rpl::producer<FieldAutocomplete::StickerChosen> {
  237. return _inner->stickerChosen();
  238. }
  239. auto FieldAutocomplete::choosingProcesses() const
  240. -> rpl::producer<FieldAutocomplete::Type> {
  241. return _scroll->scrollTopChanges(
  242. ) | rpl::filter([](int top) {
  243. return top != 0;
  244. }) | rpl::map([=] {
  245. return !_mrows.empty()
  246. ? Type::Mentions
  247. : !_hrows.empty()
  248. ? Type::Hashtags
  249. : !_brows.empty()
  250. ? Type::BotCommands
  251. : !_srows.empty()
  252. ? Type::Stickers
  253. : _type;
  254. });
  255. }
  256. FieldAutocomplete::~FieldAutocomplete() = default;
  257. void FieldAutocomplete::paintEvent(QPaintEvent *e) {
  258. Painter p(this);
  259. auto opacity = _a_opacity.value(_hiding ? 0. : 1.);
  260. if (opacity < 1.) {
  261. if (opacity > 0.) {
  262. p.setOpacity(opacity);
  263. p.drawPixmap(0, 0, _cache);
  264. } else if (_hiding) {
  265. }
  266. return;
  267. }
  268. p.fillRect(rect(), _st.bg);
  269. }
  270. void FieldAutocomplete::showFiltered(
  271. not_null<PeerData*> peer,
  272. QString query,
  273. bool addInlineBots) {
  274. _chat = peer->asChat();
  275. _user = peer->asUser();
  276. _channel = peer->asChannel();
  277. if (query.isEmpty()) {
  278. _type = Type::Mentions;
  279. rowsUpdated(
  280. MentionRows(),
  281. HashtagRows(),
  282. BotCommandRows(),
  283. base::take(_srows),
  284. false);
  285. return;
  286. }
  287. _emoji = nullptr;
  288. query = query.toLower();
  289. auto type = Type::Stickers;
  290. auto plainQuery = QStringView(query);
  291. switch (query.at(0).unicode()) {
  292. case '@':
  293. type = Type::Mentions;
  294. plainQuery = base::StringViewMid(query, 1);
  295. break;
  296. case '#':
  297. type = Type::Hashtags;
  298. plainQuery = base::StringViewMid(query, 1);
  299. break;
  300. case '/':
  301. type = Type::BotCommands;
  302. plainQuery = base::StringViewMid(query, 1);
  303. break;
  304. }
  305. const auto resetScroll = (_type != type || _filter != plainQuery);
  306. if (resetScroll) {
  307. _type = type;
  308. _filter = TextUtilities::RemoveAccents(plainQuery.toString());
  309. }
  310. _addInlineBots = addInlineBots;
  311. updateFiltered(resetScroll);
  312. }
  313. void FieldAutocomplete::showStickers(EmojiPtr emoji) {
  314. const auto resetScroll = (_emoji != emoji);
  315. if (resetScroll || emoji) {
  316. _emoji = emoji;
  317. _type = Type::Stickers;
  318. } else if (!emoji) {
  319. rowsUpdated(
  320. base::take(_mrows),
  321. base::take(_hrows),
  322. base::take(_brows),
  323. StickerRows(),
  324. false);
  325. return;
  326. }
  327. _chat = nullptr;
  328. _user = nullptr;
  329. _channel = nullptr;
  330. updateFiltered(resetScroll);
  331. }
  332. EmojiPtr FieldAutocomplete::stickersEmoji() const {
  333. return _emoji;
  334. }
  335. bool FieldAutocomplete::clearFilteredBotCommands() {
  336. if (_brows.empty()) {
  337. return false;
  338. }
  339. _brows.clear();
  340. return true;
  341. }
  342. FieldAutocomplete::StickerRows FieldAutocomplete::getStickerSuggestions() {
  343. const auto data = &_session->data().stickers();
  344. const auto list = data->getListByEmoji({ _emoji }, _stickersSeed);
  345. auto result = ranges::views::all(
  346. list
  347. ) | ranges::views::transform([](not_null<DocumentData*> sticker) {
  348. return StickerSuggestion{
  349. sticker,
  350. sticker->createMediaView()
  351. };
  352. }) | ranges::to_vector;
  353. for (auto &suggestion : _srows) {
  354. if (!suggestion.lottie && !suggestion.webm) {
  355. continue;
  356. }
  357. const auto i = ranges::find(
  358. result,
  359. suggestion.document,
  360. &StickerSuggestion::document);
  361. if (i != end(result)) {
  362. i->lottie = std::move(suggestion.lottie);
  363. i->webm = std::move(suggestion.webm);
  364. }
  365. }
  366. return result;
  367. }
  368. void FieldAutocomplete::updateFiltered(bool resetScroll) {
  369. int32 now = base::unixtime::now(), recentInlineBots = 0;
  370. MentionRows mrows;
  371. HashtagRows hrows;
  372. BotCommandRows brows;
  373. StickerRows srows;
  374. if (_emoji) {
  375. srows = getStickerSuggestions();
  376. } else if (_type == Type::Mentions) {
  377. int maxListSize = _addInlineBots ? cRecentInlineBots().size() : 0;
  378. if (_chat) {
  379. maxListSize += (_chat->participants.empty() ? _chat->lastAuthors.size() : _chat->participants.size());
  380. } else if (_channel && _channel->isMegagroup()) {
  381. if (!_channel->canViewMembers()) {
  382. maxListSize += _channel->mgInfo->admins.size();
  383. } else if (!_channel->lastParticipantsRequestNeeded()) {
  384. maxListSize += _channel->mgInfo->lastParticipants.size();
  385. }
  386. }
  387. if (maxListSize) {
  388. mrows.reserve(maxListSize);
  389. }
  390. auto filterNotPassedByUsername = [this](UserData *user) -> bool {
  391. if (PrimaryUsername(user).startsWith(_filter, Qt::CaseInsensitive)) {
  392. const auto exactUsername
  393. = (PrimaryUsername(user).size() == _filter.size());
  394. return exactUsername;
  395. }
  396. return true;
  397. };
  398. auto filterNotPassedByName = [&](UserData *user) -> bool {
  399. for (const auto &nameWord : user->nameWords()) {
  400. if (nameWord.startsWith(_filter, Qt::CaseInsensitive)) {
  401. const auto exactUsername = PrimaryUsername(user).compare(
  402. _filter,
  403. Qt::CaseInsensitive) == 0;
  404. return exactUsername;
  405. }
  406. }
  407. return filterNotPassedByUsername(user);
  408. };
  409. bool listAllSuggestions = _filter.isEmpty();
  410. if (_addInlineBots) {
  411. for (const auto user : cRecentInlineBots()) {
  412. if (user->isInaccessible()
  413. || (!listAllSuggestions
  414. && filterNotPassedByUsername(user))) {
  415. continue;
  416. }
  417. mrows.push_back({ user });
  418. ++recentInlineBots;
  419. }
  420. }
  421. if (_chat) {
  422. auto sorted = base::flat_multi_map<TimeId, not_null<UserData*>>();
  423. const auto byOnline = [&](not_null<UserData*> user) {
  424. return Data::SortByOnlineValue(user, now);
  425. };
  426. mrows.reserve(mrows.size() + (_chat->participants.empty() ? _chat->lastAuthors.size() : _chat->participants.size()));
  427. if (_chat->noParticipantInfo()) {
  428. _chat->session().api().requestFullPeer(_chat);
  429. } else if (!_chat->participants.empty()) {
  430. for (const auto &user : _chat->participants) {
  431. if (user->isInaccessible()) continue;
  432. if (!listAllSuggestions && filterNotPassedByName(user)) continue;
  433. if (indexOfInFirstN(mrows, user, recentInlineBots) >= 0) continue;
  434. sorted.emplace(byOnline(user), user);
  435. }
  436. }
  437. for (const auto user : _chat->lastAuthors) {
  438. if (user->isInaccessible()) continue;
  439. if (!listAllSuggestions && filterNotPassedByName(user)) continue;
  440. if (indexOfInFirstN(mrows, user, recentInlineBots) >= 0) continue;
  441. mrows.push_back({ user });
  442. sorted.remove(byOnline(user), user);
  443. }
  444. for (auto i = sorted.cend(), b = sorted.cbegin(); i != b;) {
  445. --i;
  446. mrows.push_back({ i->second });
  447. }
  448. } else if (_channel && _channel->isMegagroup()) {
  449. if (!_channel->canViewMembers()) {
  450. if (!_channel->mgInfo->adminsLoaded) {
  451. _channel->session().api().chatParticipants().requestAdmins(_channel);
  452. } else {
  453. mrows.reserve(mrows.size() + _channel->mgInfo->admins.size());
  454. for (const auto &[userId, rank] : _channel->mgInfo->admins) {
  455. if (const auto user = _channel->owner().userLoaded(userId)) {
  456. if (user->isInaccessible()) continue;
  457. if (!listAllSuggestions && filterNotPassedByName(user)) continue;
  458. if (indexOfInFirstN(mrows, user, recentInlineBots) >= 0) continue;
  459. mrows.push_back({ user });
  460. }
  461. }
  462. }
  463. } else if (_channel->lastParticipantsRequestNeeded()) {
  464. _channel->session().api().chatParticipants().requestLast(
  465. _channel);
  466. } else {
  467. mrows.reserve(mrows.size() + _channel->mgInfo->lastParticipants.size());
  468. for (const auto user : _channel->mgInfo->lastParticipants) {
  469. if (user->isInaccessible()) continue;
  470. if (!listAllSuggestions && filterNotPassedByName(user)) continue;
  471. if (indexOfInFirstN(mrows, user, recentInlineBots) >= 0) continue;
  472. mrows.push_back({ user });
  473. }
  474. }
  475. }
  476. } else if (_type == Type::Hashtags) {
  477. bool listAllSuggestions = _filter.isEmpty();
  478. auto &recent(cRecentWriteHashtags());
  479. hrows.reserve(recent.size());
  480. for (const auto &item : recent) {
  481. const auto &tag = item.first;
  482. if (!listAllSuggestions
  483. && (tag.size() == _filter.size()
  484. || !TextUtilities::RemoveAccents(tag).startsWith(
  485. _filter,
  486. Qt::CaseInsensitive))) {
  487. continue;
  488. }
  489. hrows.push_back(tag);
  490. }
  491. } else if (_type == Type::BotCommands) {
  492. bool listAllSuggestions = _filter.isEmpty();
  493. bool hasUsername = _filter.indexOf('@') > 0;
  494. base::flat_map<
  495. not_null<UserData*>,
  496. not_null<const std::vector<Data::BotCommand>*>> bots;
  497. int32 cnt = 0;
  498. if (_chat) {
  499. if (_chat->noParticipantInfo()) {
  500. _chat->session().api().requestFullPeer(_chat);
  501. } else if (!_chat->participants.empty()) {
  502. const auto &commands = _chat->botCommands();
  503. for (const auto &user : _chat->participants) {
  504. if (!user->isBot()) {
  505. continue;
  506. }
  507. const auto i = commands.find(peerToUser(user->id));
  508. if (i != end(commands)) {
  509. bots.emplace(user, &i->second);
  510. cnt += i->second.size();
  511. }
  512. }
  513. }
  514. } else if (_user && _user->isBot()) {
  515. if (!_user->botInfo->inited) {
  516. _user->session().api().requestFullPeer(_user);
  517. }
  518. cnt = _user->botInfo->commands.size();
  519. bots.emplace(_user, &_user->botInfo->commands);
  520. } else if (_channel && _channel->isMegagroup()) {
  521. if (_channel->mgInfo->bots.empty()) {
  522. if (!_channel->mgInfo->botStatus) {
  523. _channel->session().api().chatParticipants().requestBots(
  524. _channel);
  525. }
  526. } else {
  527. const auto &commands = _channel->mgInfo->botCommands();
  528. for (const auto &user : _channel->mgInfo->bots) {
  529. if (!user->isBot()) {
  530. continue;
  531. }
  532. const auto i = commands.find(peerToUser(user->id));
  533. if (i != end(commands)) {
  534. bots.emplace(user, &i->second);
  535. cnt += i->second.size();
  536. }
  537. }
  538. }
  539. }
  540. if (cnt) {
  541. const auto make = [&](
  542. not_null<UserData*> user,
  543. const Data::BotCommand &command) {
  544. return BotCommandRow{
  545. user,
  546. command.command,
  547. command.description,
  548. user->activeUserpicView()
  549. };
  550. };
  551. brows.reserve(cnt);
  552. int32 botStatus = _chat ? _chat->botStatus : ((_channel && _channel->isMegagroup()) ? _channel->mgInfo->botStatus : -1);
  553. if (_chat) {
  554. for (const auto &user : _chat->lastAuthors) {
  555. if (!user->isBot()) {
  556. continue;
  557. }
  558. const auto i = bots.find(user);
  559. if (i == end(bots)) {
  560. continue;
  561. }
  562. for (const auto &command : *i->second) {
  563. if (!listAllSuggestions) {
  564. auto toFilter = (hasUsername || botStatus == 0 || botStatus == 2)
  565. ? command.command + '@' + PrimaryUsername(user)
  566. : command.command;
  567. if (!toFilter.startsWith(_filter, Qt::CaseInsensitive)/* || toFilter.size() == _filter.size()*/) {
  568. continue;
  569. }
  570. }
  571. brows.push_back(make(user, command));
  572. }
  573. bots.erase(i);
  574. }
  575. }
  576. if (!bots.empty()) {
  577. for (auto i = bots.cbegin(), e = bots.cend(); i != e; ++i) {
  578. const auto user = i->first;
  579. for (const auto &command : *i->second) {
  580. if (!listAllSuggestions) {
  581. const auto toFilter = (hasUsername
  582. || botStatus == 0
  583. || botStatus == 2)
  584. ? command.command + '@' + PrimaryUsername(user)
  585. : command.command;
  586. if (!toFilter.startsWith(_filter, Qt::CaseInsensitive)/* || toFilter.size() == _filter.size()*/) continue;
  587. }
  588. brows.push_back(make(user, command));
  589. }
  590. }
  591. }
  592. }
  593. const auto shortcuts = (_user && !_user->isBot())
  594. ? _user->owner().shortcutMessages().shortcuts().list
  595. : base::flat_map<BusinessShortcutId, Data::Shortcut>();
  596. if (!hasUsername && brows.empty() && !shortcuts.empty()) {
  597. const auto self = _user->session().user();
  598. for (const auto &[id, shortcut] : shortcuts) {
  599. if (shortcut.count < 1) {
  600. continue;
  601. } else if (!listAllSuggestions) {
  602. if (!shortcut.name.startsWith(_filter, Qt::CaseInsensitive)) {
  603. continue;
  604. }
  605. }
  606. brows.push_back(BotCommandRow{
  607. self,
  608. shortcut.name,
  609. tr::lng_forum_messages(tr::now, lt_count, shortcut.count),
  610. self->activeUserpicView()
  611. });
  612. }
  613. if (!brows.empty()) {
  614. brows.insert(begin(brows), BotCommandRow{ self }); // Edit.
  615. }
  616. }
  617. }
  618. rowsUpdated(
  619. std::move(mrows),
  620. std::move(hrows),
  621. std::move(brows),
  622. std::move(srows),
  623. resetScroll);
  624. _inner->setRecentInlineBotsInRows(recentInlineBots);
  625. }
  626. void FieldAutocomplete::rowsUpdated(
  627. MentionRows &&mrows,
  628. HashtagRows &&hrows,
  629. BotCommandRows &&brows,
  630. StickerRows &&srows,
  631. bool resetScroll) {
  632. if (mrows.empty() && hrows.empty() && brows.empty() && srows.empty()) {
  633. if (!isHidden()) {
  634. hideAnimated();
  635. }
  636. _scroll->scrollToY(0);
  637. _mrows.clear();
  638. _hrows.clear();
  639. _brows.clear();
  640. _srows.clear();
  641. } else {
  642. _mrows = std::move(mrows);
  643. _hrows = std::move(hrows);
  644. _brows = std::move(brows);
  645. _srows = std::move(srows);
  646. bool hidden = _hiding || isHidden();
  647. if (hidden) {
  648. show();
  649. _scroll->show();
  650. }
  651. recount(resetScroll);
  652. update();
  653. if (hidden) {
  654. hide();
  655. showAnimated();
  656. }
  657. }
  658. _inner->rowsUpdated();
  659. }
  660. void FieldAutocomplete::setBoundings(QRect boundings) {
  661. _boundings = boundings;
  662. recount();
  663. }
  664. void FieldAutocomplete::recount(bool resetScroll) {
  665. int32 h = 0, oldst = _scroll->scrollTop(), st = oldst, maxh = 4.5 * st::mentionHeight;
  666. if (!_srows.empty()) {
  667. int32 stickersPerRow = qMax(1, int32(_boundings.width() - 2 * st::stickerPanPadding) / int32(st::stickerPanSize.width()));
  668. int32 rows = rowscount(_srows.size(), stickersPerRow);
  669. h = st::stickerPanPadding + rows * st::stickerPanSize.height();
  670. } else if (!_mrows.empty()) {
  671. h = _mrows.size() * st::mentionHeight;
  672. } else if (!_hrows.empty()) {
  673. h = _hrows.size() * st::mentionHeight;
  674. } else if (!_brows.empty()) {
  675. h = _brows.size() * st::mentionHeight;
  676. }
  677. h += _st.autocompleteBottomSkip;
  678. if (_inner->width() != _boundings.width() || _inner->height() != h) {
  679. _inner->resize(_boundings.width(), h);
  680. }
  681. if (h > _boundings.height()) h = _boundings.height();
  682. if (h > maxh) h = maxh;
  683. if (width() != _boundings.width() || height() != h) {
  684. setGeometry(
  685. _boundings.x(),
  686. _boundings.y() + _boundings.height() - h,
  687. _boundings.width(),
  688. h);
  689. _scroll->resize(_boundings.width(), h);
  690. } else if (x() != _boundings.x()
  691. || y() != _boundings.y() + _boundings.height() - h) {
  692. move(_boundings.x(), _boundings.y() + _boundings.height() - h);
  693. }
  694. if (resetScroll) st = 0;
  695. if (st != oldst) _scroll->scrollToY(st);
  696. if (resetScroll) _inner->clearSel();
  697. }
  698. void FieldAutocomplete::hideFast() {
  699. _a_opacity.stop();
  700. hideFinish();
  701. }
  702. void FieldAutocomplete::hideAnimated() {
  703. if (isHidden() || _hiding) {
  704. return;
  705. }
  706. if (_cache.isNull()) {
  707. _scroll->show();
  708. _cache = Ui::GrabWidget(this);
  709. }
  710. _scroll->hide();
  711. _hiding = true;
  712. _a_opacity.start([this] { animationCallback(); }, 1., 0., st::emojiPanDuration);
  713. setAttribute(Qt::WA_OpaquePaintEvent, false);
  714. }
  715. void FieldAutocomplete::hideFinish() {
  716. hide();
  717. _hiding = false;
  718. _filter = u"-"_q;
  719. _inner->clearSel(true);
  720. }
  721. void FieldAutocomplete::showAnimated() {
  722. if (!isHidden() && !_hiding) {
  723. return;
  724. }
  725. if (_cache.isNull()) {
  726. _stickersSeed = base::RandomValue<uint64>();
  727. _scroll->show();
  728. _cache = Ui::GrabWidget(this);
  729. }
  730. _scroll->hide();
  731. _hiding = false;
  732. show();
  733. _a_opacity.start([this] { animationCallback(); }, 0., 1., st::emojiPanDuration);
  734. setAttribute(Qt::WA_OpaquePaintEvent, false);
  735. }
  736. void FieldAutocomplete::animationCallback() {
  737. update();
  738. if (!_a_opacity.animating()) {
  739. _cache = QPixmap();
  740. setAttribute(Qt::WA_OpaquePaintEvent);
  741. if (_hiding) {
  742. hideFinish();
  743. } else {
  744. _scroll->show();
  745. _inner->clearSel();
  746. }
  747. }
  748. }
  749. const QString &FieldAutocomplete::filter() const {
  750. return _filter;
  751. }
  752. ChatData *FieldAutocomplete::chat() const {
  753. return _chat;
  754. }
  755. ChannelData *FieldAutocomplete::channel() const {
  756. return _channel;
  757. }
  758. UserData *FieldAutocomplete::user() const {
  759. return _user;
  760. }
  761. int32 FieldAutocomplete::innerTop() {
  762. return _scroll->scrollTop();
  763. }
  764. int32 FieldAutocomplete::innerBottom() {
  765. return _scroll->scrollTop() + _scroll->height();
  766. }
  767. bool FieldAutocomplete::chooseSelected(ChooseMethod method) const {
  768. return _inner->chooseSelected(method);
  769. }
  770. void FieldAutocomplete::setSendMenuDetails(
  771. Fn<SendMenu::Details()> &&callback) {
  772. _inner->setSendMenuDetails(std::move(callback));
  773. }
  774. bool FieldAutocomplete::eventFilter(QObject *obj, QEvent *e) {
  775. auto hidden = isHidden();
  776. auto moderate = Core::App().settings().moderateModeEnabled();
  777. if (hidden && !moderate) return QWidget::eventFilter(obj, e);
  778. if (e->type() == QEvent::KeyPress) {
  779. QKeyEvent *ev = static_cast<QKeyEvent*>(e);
  780. if (!(ev->modifiers() & (Qt::AltModifier | Qt::ControlModifier | Qt::ShiftModifier | Qt::MetaModifier))) {
  781. const auto key = ev->key();
  782. if (!hidden) {
  783. if (key == Qt::Key_Up || key == Qt::Key_Down || (!_srows.empty() && (key == Qt::Key_Left || key == Qt::Key_Right))) {
  784. return _inner->moveSel(key);
  785. } else if (key == Qt::Key_Enter || key == Qt::Key_Return) {
  786. return _inner->chooseSelected(ChooseMethod::ByEnter);
  787. }
  788. }
  789. if (moderate
  790. && ((key >= Qt::Key_1 && key <= Qt::Key_9)
  791. || key == Qt::Key_Q
  792. || key == Qt::Key_W)) {
  793. return _moderateKeyActivateCallback
  794. ? _moderateKeyActivateCallback(key)
  795. : false;
  796. }
  797. }
  798. }
  799. return QWidget::eventFilter(obj, e);
  800. }
  801. FieldAutocomplete::Inner::Inner(
  802. std::shared_ptr<Show> show,
  803. const style::EmojiPan &st,
  804. not_null<FieldAutocomplete*> parent,
  805. not_null<MentionRows*> mrows,
  806. not_null<HashtagRows*> hrows,
  807. not_null<BotCommandRows*> brows,
  808. not_null<StickerRows*> srows)
  809. : _show(std::move(show))
  810. , _session(&_show->session())
  811. , _st(st)
  812. , _parent(parent)
  813. , _mrows(mrows)
  814. , _hrows(hrows)
  815. , _brows(brows)
  816. , _srows(srows)
  817. , _overBg(st::roundRadiusSmall, _st.overBg)
  818. , _pathGradient(std::make_unique<Ui::PathShiftGradient>(
  819. _st.pathBg,
  820. _st.pathFg,
  821. [=] { update(); }))
  822. , _premiumMark(_session, st::stickersPremiumLock)
  823. , _previewTimer([=] { showPreview(); }) {
  824. _session->downloaderTaskFinished(
  825. ) | rpl::start_with_next([=] {
  826. update();
  827. }, lifetime());
  828. _show->adjustShadowLeft(
  829. ) | rpl::start_with_next([=](bool adjust) {
  830. _adjustShadowLeft = adjust;
  831. update();
  832. }, lifetime());
  833. }
  834. void FieldAutocomplete::Inner::paintEvent(QPaintEvent *e) {
  835. Painter p(this);
  836. QRect r(e->rect());
  837. if (r != rect()) p.setClipRect(r);
  838. auto mentionleft = 2 * st::mentionPadding.left() + st::mentionPhotoSize;
  839. auto mentionwidth = width()
  840. - mentionleft
  841. - 2 * st::mentionPadding.right();
  842. auto htagleft = st::historyAttach.width
  843. + st::historyComposeField.textMargins.left()
  844. - st::lineWidth;
  845. auto htagwidth = width()
  846. - st::mentionPadding.right()
  847. - htagleft
  848. - st::defaultScrollArea.width;
  849. if (!_srows->empty()) {
  850. _pathGradient->startFrame(
  851. 0,
  852. width(),
  853. std::min(st::msgMaxWidth / 2, width() / 2));
  854. const auto now = crl::now();
  855. int32 rows = rowscount(_srows->size(), _stickersPerRow);
  856. int32 fromrow = floorclamp(r.y() - st::stickerPanPadding, st::stickerPanSize.height(), 0, rows);
  857. int32 torow = ceilclamp(r.y() + r.height() - st::stickerPanPadding, st::stickerPanSize.height(), 0, rows);
  858. int32 fromcol = floorclamp(r.x() - st::stickerPanPadding, st::stickerPanSize.width(), 0, _stickersPerRow);
  859. int32 tocol = ceilclamp(r.x() + r.width() - st::stickerPanPadding, st::stickerPanSize.width(), 0, _stickersPerRow);
  860. for (int32 row = fromrow; row < torow; ++row) {
  861. for (int32 col = fromcol; col < tocol; ++col) {
  862. int32 index = row * _stickersPerRow + col;
  863. if (index >= _srows->size()) break;
  864. auto &sticker = (*_srows)[index];
  865. const auto document = sticker.document;
  866. const auto &media = sticker.documentMedia;
  867. const auto info = document->sticker();
  868. if (!info) continue;
  869. if (media->loaded()) {
  870. if (info->isLottie() && !sticker.lottie) {
  871. setupLottie(sticker);
  872. } else if (info->isWebm() && !sticker.webm) {
  873. setupWebm(sticker);
  874. }
  875. }
  876. QPoint pos(st::stickerPanPadding + col * st::stickerPanSize.width(), st::stickerPanPadding + row * st::stickerPanSize.height());
  877. if (_sel == index) {
  878. QPoint tl(pos);
  879. if (rtl()) tl.setX(width() - tl.x() - st::stickerPanSize.width());
  880. _overBg.paint(p, QRect(tl, st::stickerPanSize));
  881. }
  882. media->checkStickerSmall();
  883. const auto paused = _show->paused(
  884. PauseReason::TabbedPanel);
  885. const auto size = ComputeStickerSize(
  886. document,
  887. stickerBoundingBox());
  888. const auto ppos = pos + QPoint(
  889. (st::stickerPanSize.width() - size.width()) / 2,
  890. (st::stickerPanSize.height() - size.height()) / 2);
  891. auto lottieFrame = QImage();
  892. if (sticker.lottie && sticker.lottie->ready()) {
  893. lottieFrame = sticker.lottie->frame();
  894. p.drawImage(
  895. QRect(
  896. ppos,
  897. lottieFrame.size() / style::DevicePixelRatio()),
  898. lottieFrame);
  899. if (!paused) {
  900. sticker.lottie->markFrameShown();
  901. }
  902. } else if (sticker.webm && sticker.webm->started()) {
  903. p.drawImage(ppos, sticker.webm->current({
  904. .frame = size,
  905. .keepAlpha = true,
  906. }, paused ? 0 : now));
  907. } else if (const auto image = media->getStickerSmall()) {
  908. p.drawPixmapLeft(ppos, width(), image->pix(size));
  909. } else {
  910. PaintStickerThumbnailPath(
  911. p,
  912. media.get(),
  913. QRect(ppos, size),
  914. _pathGradient.get());
  915. }
  916. if (document->isPremiumSticker()) {
  917. _premiumMark.paint(
  918. p,
  919. lottieFrame,
  920. sticker.premiumLock,
  921. pos,
  922. st::stickerPanSize,
  923. width());
  924. }
  925. }
  926. }
  927. } else {
  928. int32 from = qFloor(e->rect().top() / st::mentionHeight), to = qFloor(e->rect().bottom() / st::mentionHeight) + 1;
  929. int32 last = !_mrows->empty()
  930. ? _mrows->size()
  931. : !_hrows->empty()
  932. ? _hrows->size()
  933. : _brows->size();
  934. auto filter = _parent->filter();
  935. bool hasUsername = filter.indexOf('@') > 0;
  936. int filterSize = filter.size();
  937. bool filterIsEmpty = filter.isEmpty();
  938. for (int32 i = from; i < to; ++i) {
  939. if (i >= last) break;
  940. bool selected = (i == _sel);
  941. if (selected) {
  942. p.fillRect(0, i * st::mentionHeight, width(), st::mentionHeight, st::mentionBgOver);
  943. int skip = (st::mentionHeight - st::smallCloseIconOver.height()) / 2;
  944. if (!_hrows->empty() || (!_mrows->empty() && i < _recentInlineBotsInRows)) {
  945. st::smallCloseIconOver.paint(p, QPoint(width() - st::smallCloseIconOver.width() - skip, i * st::mentionHeight + skip), width());
  946. }
  947. }
  948. if (!_mrows->empty()) {
  949. auto &row = _mrows->at(i);
  950. const auto user = row.user;
  951. auto first = (!filterIsEmpty
  952. && PrimaryUsername(user).startsWith(
  953. filter,
  954. Qt::CaseInsensitive))
  955. ? ('@' + PrimaryUsername(user).mid(0, filterSize))
  956. : QString();
  957. auto second = first.isEmpty()
  958. ? (PrimaryUsername(user).isEmpty()
  959. ? QString()
  960. : ('@' + PrimaryUsername(user)))
  961. : PrimaryUsername(user).mid(filterSize);
  962. auto firstwidth = st::mentionFont->width(first);
  963. auto secondwidth = st::mentionFont->width(second);
  964. auto unamewidth = firstwidth + secondwidth;
  965. if (row.name.isEmpty()) {
  966. row.name.setText(st::msgNameStyle, user->name(), Ui::NameTextOptions());
  967. }
  968. auto namewidth = row.name.maxWidth();
  969. if (mentionwidth < unamewidth + namewidth) {
  970. namewidth = (mentionwidth * namewidth) / (namewidth + unamewidth);
  971. unamewidth = mentionwidth - namewidth;
  972. if (firstwidth < unamewidth + st::mentionFont->elidew) {
  973. if (firstwidth < unamewidth) {
  974. first = st::mentionFont->elided(first, unamewidth);
  975. } else if (!second.isEmpty()) {
  976. first = st::mentionFont->elided(first + second, unamewidth);
  977. second = QString();
  978. }
  979. } else {
  980. second = st::mentionFont->elided(second, unamewidth - firstwidth);
  981. }
  982. }
  983. user->loadUserpic();
  984. user->paintUserpicLeft(p, row.userpic, st::mentionPadding.left(), i * st::mentionHeight + st::mentionPadding.top(), width(), st::mentionPhotoSize);
  985. p.setPen(selected ? st::mentionNameFgOver : st::mentionNameFg);
  986. row.name.drawElided(p, 2 * st::mentionPadding.left() + st::mentionPhotoSize, i * st::mentionHeight + st::mentionTop, namewidth);
  987. p.setFont(st::mentionFont);
  988. p.setPen(selected ? st::mentionFgOverActive : st::mentionFgActive);
  989. p.drawText(mentionleft + namewidth + st::mentionPadding.right(), i * st::mentionHeight + st::mentionTop + st::mentionFont->ascent, first);
  990. if (!second.isEmpty()) {
  991. p.setPen(selected ? st::mentionFgOver : st::mentionFg);
  992. p.drawText(mentionleft + namewidth + st::mentionPadding.right() + firstwidth, i * st::mentionHeight + st::mentionTop + st::mentionFont->ascent, second);
  993. }
  994. } else if (!_hrows->empty()) {
  995. QString hrow = _hrows->at(i);
  996. QString first = filterIsEmpty ? QString() : ('#' + hrow.mid(0, filterSize));
  997. QString second = filterIsEmpty ? ('#' + hrow) : hrow.mid(filterSize);
  998. int32 firstwidth = st::mentionFont->width(first), secondwidth = st::mentionFont->width(second);
  999. if (htagwidth < firstwidth + secondwidth) {
  1000. if (htagwidth < firstwidth + st::mentionFont->elidew) {
  1001. first = st::mentionFont->elided(first + second, htagwidth);
  1002. second = QString();
  1003. } else {
  1004. second = st::mentionFont->elided(second, htagwidth - firstwidth);
  1005. }
  1006. }
  1007. p.setFont(st::mentionFont);
  1008. if (!first.isEmpty()) {
  1009. p.setPen((selected ? st::mentionFgOverActive : st::mentionFgActive)->p);
  1010. p.drawText(htagleft, i * st::mentionHeight + st::mentionTop + st::mentionFont->ascent, first);
  1011. }
  1012. if (!second.isEmpty()) {
  1013. p.setPen((selected ? st::mentionFgOver : st::mentionFg)->p);
  1014. p.drawText(htagleft + firstwidth, i * st::mentionHeight + st::mentionTop + st::mentionFont->ascent, second);
  1015. }
  1016. } else {
  1017. auto &row = _brows->at(i);
  1018. const auto user = row.user;
  1019. if (user->isSelf() && row.command.isEmpty()) {
  1020. p.setPen(st::windowActiveTextFg);
  1021. p.setFont(st::semiboldFont);
  1022. p.drawText(
  1023. QRect(0, i * st::mentionHeight, width(), st::mentionHeight),
  1024. tr::lng_replies_edit_button(tr::now),
  1025. style::al_center);
  1026. continue;
  1027. }
  1028. auto toHighlight = row.command;
  1029. int32 botStatus = _parent->chat() ? _parent->chat()->botStatus : ((_parent->channel() && _parent->channel()->isMegagroup()) ? _parent->channel()->mgInfo->botStatus : -1);
  1030. if (hasUsername || botStatus == 0 || botStatus == 2) {
  1031. toHighlight += '@' + PrimaryUsername(user);
  1032. }
  1033. user->loadUserpic();
  1034. user->paintUserpicLeft(p, row.userpic, st::mentionPadding.left(), i * st::mentionHeight + st::mentionPadding.top(), width(), st::mentionPhotoSize);
  1035. auto commandText = '/' + toHighlight;
  1036. p.setPen(selected ? st::mentionNameFgOver : st::mentionNameFg);
  1037. p.setFont(st::semiboldFont);
  1038. p.drawText(2 * st::mentionPadding.left() + st::mentionPhotoSize, i * st::mentionHeight + st::mentionTop + st::semiboldFont->ascent, commandText);
  1039. auto commandTextWidth = st::semiboldFont->width(commandText);
  1040. auto addleft = commandTextWidth + st::mentionPadding.left();
  1041. auto widthleft = mentionwidth - addleft;
  1042. if (!row.description.isEmpty()
  1043. && row.descriptionText.isEmpty()) {
  1044. row.descriptionText.setText(
  1045. st::defaultTextStyle,
  1046. row.description,
  1047. Ui::NameTextOptions());
  1048. }
  1049. if (widthleft > st::mentionFont->elidew && !row.descriptionText.isEmpty()) {
  1050. p.setPen((selected ? st::mentionFgOver : st::mentionFg)->p);
  1051. row.descriptionText.drawElided(p, mentionleft + addleft, i * st::mentionHeight + st::mentionTop, widthleft);
  1052. }
  1053. }
  1054. }
  1055. p.fillRect(
  1056. _adjustShadowLeft ? st::lineWidth : 0,
  1057. _parent->innerBottom() - st::lineWidth,
  1058. width() - (_adjustShadowLeft ? st::lineWidth : 0),
  1059. st::lineWidth,
  1060. st::shadowFg);
  1061. }
  1062. p.fillRect(
  1063. _adjustShadowLeft ? st::lineWidth : 0,
  1064. _parent->innerTop(),
  1065. width() - (_adjustShadowLeft ? st::lineWidth : 0),
  1066. st::lineWidth,
  1067. st::shadowFg);
  1068. }
  1069. void FieldAutocomplete::Inner::resizeEvent(QResizeEvent *e) {
  1070. _stickersPerRow = qMax(1, int32(width() - 2 * st::stickerPanPadding) / int32(st::stickerPanSize.width()));
  1071. }
  1072. void FieldAutocomplete::Inner::mouseMoveEvent(QMouseEvent *e) {
  1073. const auto globalPosition = e->globalPos();
  1074. if (!_lastMousePosition) {
  1075. _lastMousePosition = globalPosition;
  1076. return;
  1077. } else if (!_mouseSelection
  1078. && *_lastMousePosition == globalPosition) {
  1079. return;
  1080. }
  1081. selectByMouse(globalPosition);
  1082. }
  1083. void FieldAutocomplete::Inner::clearSel(bool hidden) {
  1084. _overDelete = false;
  1085. _mouseSelection = false;
  1086. _lastMousePosition = std::nullopt;
  1087. setSel((_mrows->empty() && _brows->empty() && _hrows->empty())
  1088. ? -1
  1089. : (_brows->size() > 1
  1090. && _brows->front().user->isSelf()
  1091. && _brows->front().command.isEmpty())
  1092. ? 1
  1093. : 0);
  1094. if (hidden) {
  1095. _down = -1;
  1096. _previewShown = false;
  1097. }
  1098. }
  1099. bool FieldAutocomplete::Inner::moveSel(int key) {
  1100. _mouseSelection = false;
  1101. _lastMousePosition = std::nullopt;
  1102. int32 maxSel = !_mrows->empty()
  1103. ? _mrows->size()
  1104. : !_hrows->empty()
  1105. ? _hrows->size()
  1106. : !_brows->empty()
  1107. ? _brows->size()
  1108. : _srows->size();
  1109. int32 direction = (key == Qt::Key_Up) ? -1 : (key == Qt::Key_Down ? 1 : 0);
  1110. if (!_srows->empty()) {
  1111. if (key == Qt::Key_Left) {
  1112. direction = -1;
  1113. } else if (key == Qt::Key_Right) {
  1114. direction = 1;
  1115. } else {
  1116. direction *= _stickersPerRow;
  1117. }
  1118. }
  1119. if (_sel >= maxSel || _sel < 0) {
  1120. if (direction < -1) {
  1121. setSel(((maxSel - 1) / _stickersPerRow) * _stickersPerRow, true);
  1122. } else if (direction < 0) {
  1123. setSel(maxSel - 1, true);
  1124. } else {
  1125. setSel(0, true);
  1126. }
  1127. return (_sel >= 0 && _sel < maxSel);
  1128. }
  1129. setSel((_sel + direction >= maxSel || _sel + direction < 0) ? -1 : (_sel + direction), true);
  1130. return true;
  1131. }
  1132. bool FieldAutocomplete::Inner::chooseSelected(
  1133. FieldAutocomplete::ChooseMethod method) const {
  1134. return chooseAtIndex(method, _sel);
  1135. }
  1136. bool FieldAutocomplete::Inner::chooseAtIndex(
  1137. FieldAutocomplete::ChooseMethod method,
  1138. int index,
  1139. Api::SendOptions options) const {
  1140. if (index < 0 || (method == ChooseMethod::ByEnter && _mouseSelection)) {
  1141. return false;
  1142. }
  1143. if (!_srows->empty()) {
  1144. if (index < _srows->size()) {
  1145. const auto document = (*_srows)[index].document;
  1146. const auto from = [&]() -> Ui::MessageSendingAnimationFrom {
  1147. if (options.scheduled) {
  1148. return {};
  1149. }
  1150. const auto bounding = selectedRect(index);
  1151. auto contentRect = QRect(
  1152. QPoint(),
  1153. ComputeStickerSize(
  1154. document,
  1155. stickerBoundingBox()));
  1156. contentRect.moveCenter(bounding.center());
  1157. return {
  1158. Ui::MessageSendingAnimationFrom::Type::Sticker,
  1159. _show->session().data().nextLocalMessageId(),
  1160. mapToGlobal(std::move(contentRect)),
  1161. };
  1162. };
  1163. _stickerChosen.fire({ document, options, from() });
  1164. return true;
  1165. }
  1166. } else if (!_mrows->empty()) {
  1167. if (index < _mrows->size()) {
  1168. const auto user = _mrows->at(index).user;
  1169. _mentionChosen.fire({ user, PrimaryUsername(user), method });
  1170. return true;
  1171. }
  1172. } else if (!_hrows->empty()) {
  1173. if (index < _hrows->size()) {
  1174. _hashtagChosen.fire({ '#' + _hrows->at(index), method });
  1175. return true;
  1176. }
  1177. } else if (!_brows->empty()) {
  1178. if (index < _brows->size()) {
  1179. const auto user = _brows->at(index).user;
  1180. const auto &command = _brows->at(index).command;
  1181. const auto botStatus = _parent->chat()
  1182. ? _parent->chat()->botStatus
  1183. : ((_parent->channel() && _parent->channel()->isMegagroup())
  1184. ? _parent->channel()->mgInfo->botStatus
  1185. : -1);
  1186. const auto insertUsername = (botStatus == 0
  1187. || botStatus == 2
  1188. || _parent->filter().indexOf('@') > 0);
  1189. const auto commandString = QString("/%1%2").arg(
  1190. command,
  1191. insertUsername ? ('@' + PrimaryUsername(user)) : QString());
  1192. _botCommandChosen.fire({ user, commandString, method });
  1193. return true;
  1194. }
  1195. }
  1196. return false;
  1197. }
  1198. void FieldAutocomplete::Inner::setRecentInlineBotsInRows(int32 bots) {
  1199. _recentInlineBotsInRows = bots;
  1200. }
  1201. void FieldAutocomplete::Inner::mousePressEvent(QMouseEvent *e) {
  1202. selectByMouse(e->globalPos());
  1203. if (e->button() == Qt::LeftButton) {
  1204. if (_overDelete && _sel >= 0 && _sel < (_mrows->empty() ? _hrows->size() : _recentInlineBotsInRows)) {
  1205. bool removed = false;
  1206. if (_mrows->empty()) {
  1207. QString toRemove = _hrows->at(_sel);
  1208. RecentHashtagPack &recent(cRefRecentWriteHashtags());
  1209. for (RecentHashtagPack::iterator i = recent.begin(); i != recent.cend();) {
  1210. if (i->first == toRemove) {
  1211. i = recent.erase(i);
  1212. removed = true;
  1213. } else {
  1214. ++i;
  1215. }
  1216. }
  1217. } else {
  1218. UserData *toRemove = _mrows->at(_sel).user;
  1219. RecentInlineBots &recent(cRefRecentInlineBots());
  1220. int32 index = recent.indexOf(toRemove);
  1221. if (index >= 0) {
  1222. recent.remove(index);
  1223. removed = true;
  1224. }
  1225. }
  1226. if (removed) {
  1227. _show->session().local().writeRecentHashtagsAndBots();
  1228. }
  1229. _parent->updateFiltered();
  1230. selectByMouse(e->globalPos());
  1231. } else if (_srows->empty()) {
  1232. chooseSelected(FieldAutocomplete::ChooseMethod::ByClick);
  1233. } else {
  1234. _down = _sel;
  1235. _previewTimer.callOnce(QApplication::startDragTime());
  1236. }
  1237. }
  1238. }
  1239. void FieldAutocomplete::Inner::mouseReleaseEvent(QMouseEvent *e) {
  1240. _previewTimer.cancel();
  1241. int32 pressed = _down;
  1242. _down = -1;
  1243. selectByMouse(e->globalPos());
  1244. if (_previewShown) {
  1245. _previewShown = false;
  1246. return;
  1247. }
  1248. if (_sel < 0 || _sel != pressed || _srows->empty()) return;
  1249. chooseSelected(FieldAutocomplete::ChooseMethod::ByClick);
  1250. }
  1251. void FieldAutocomplete::Inner::contextMenuEvent(QContextMenuEvent *e) {
  1252. if (_sel < 0 || _srows->empty() || _down >= 0) {
  1253. return;
  1254. }
  1255. const auto index = _sel;
  1256. const auto details = _sendMenuDetails
  1257. ? _sendMenuDetails()
  1258. : SendMenu::Details();
  1259. const auto method = FieldAutocomplete::ChooseMethod::ByClick;
  1260. _menu = base::make_unique_q<Ui::PopupMenu>(
  1261. this,
  1262. st::popupMenuWithIcons);
  1263. const auto send = crl::guard(this, [=](Api::SendOptions options) {
  1264. chooseAtIndex(method, index, options);
  1265. });
  1266. SendMenu::FillSendMenu(
  1267. _menu,
  1268. _show,
  1269. details,
  1270. SendMenu::DefaultCallback(_show, send));
  1271. if (!_menu->empty()) {
  1272. _menu->popup(QCursor::pos());
  1273. }
  1274. }
  1275. void FieldAutocomplete::Inner::enterEventHook(QEnterEvent *e) {
  1276. setMouseTracking(true);
  1277. }
  1278. void FieldAutocomplete::Inner::leaveEventHook(QEvent *e) {
  1279. setMouseTracking(false);
  1280. if (_mouseSelection) {
  1281. setSel(-1);
  1282. _mouseSelection = false;
  1283. _lastMousePosition = std::nullopt;
  1284. }
  1285. }
  1286. QRect FieldAutocomplete::Inner::selectedRect(int index) const {
  1287. if (index < 0) {
  1288. return QRect();
  1289. }
  1290. if (_srows->empty()) {
  1291. return { 0, index * st::mentionHeight, width(), st::mentionHeight };
  1292. } else {
  1293. const auto row = int(index / _stickersPerRow);
  1294. const auto col = int(index % _stickersPerRow);
  1295. return {
  1296. st::stickerPanPadding + col * st::stickerPanSize.width(),
  1297. st::stickerPanPadding + row * st::stickerPanSize.height(),
  1298. st::stickerPanSize.width(),
  1299. st::stickerPanSize.height()
  1300. };
  1301. }
  1302. }
  1303. void FieldAutocomplete::Inner::updateSelectedRow() {
  1304. const auto rect = selectedRect(_sel);
  1305. if (rect.isValid()) {
  1306. update(rect);
  1307. }
  1308. }
  1309. void FieldAutocomplete::Inner::setSel(int sel, bool scroll) {
  1310. updateSelectedRow();
  1311. _sel = sel;
  1312. updateSelectedRow();
  1313. if (scroll && _sel >= 0) {
  1314. if (_srows->empty()) {
  1315. _scrollToRequested.fire({
  1316. _sel * st::mentionHeight,
  1317. (_sel + 1) * st::mentionHeight });
  1318. } else {
  1319. int32 row = _sel / _stickersPerRow;
  1320. const auto padding = st::stickerPanPadding;
  1321. _scrollToRequested.fire({
  1322. (row ? padding : 0) + row * st::stickerPanSize.height(),
  1323. (padding
  1324. + (row + 1) * st::stickerPanSize.height()
  1325. + _st.autocompleteBottomSkip) });
  1326. }
  1327. }
  1328. }
  1329. void FieldAutocomplete::Inner::rowsUpdated() {
  1330. if (_srows->empty()) {
  1331. _stickersLifetime.destroy();
  1332. }
  1333. }
  1334. auto FieldAutocomplete::Inner::getLottieRenderer()
  1335. -> std::shared_ptr<Lottie::FrameRenderer> {
  1336. if (auto result = _lottieRenderer.lock()) {
  1337. return result;
  1338. }
  1339. auto result = Lottie::MakeFrameRenderer();
  1340. _lottieRenderer = result;
  1341. return result;
  1342. }
  1343. void FieldAutocomplete::Inner::setupLottie(StickerSuggestion &suggestion) {
  1344. const auto document = suggestion.document;
  1345. suggestion.lottie = LottiePlayerFromDocument(
  1346. suggestion.documentMedia.get(),
  1347. StickerLottieSize::InlineResults,
  1348. stickerBoundingBox() * style::DevicePixelRatio(),
  1349. Lottie::Quality::Default,
  1350. getLottieRenderer());
  1351. suggestion.lottie->updates(
  1352. ) | rpl::start_with_next([=] {
  1353. repaintSticker(document);
  1354. }, _stickersLifetime);
  1355. }
  1356. void FieldAutocomplete::Inner::setupWebm(StickerSuggestion &suggestion) {
  1357. const auto document = suggestion.document;
  1358. auto callback = [=](Media::Clip::Notification notification) {
  1359. clipCallback(notification, document);
  1360. };
  1361. suggestion.webm = Media::Clip::MakeReader(
  1362. suggestion.documentMedia->owner()->location(),
  1363. suggestion.documentMedia->bytes(),
  1364. std::move(callback));
  1365. }
  1366. QSize FieldAutocomplete::Inner::stickerBoundingBox() const {
  1367. return QSize(
  1368. st::stickerPanSize.width() - st::roundRadiusSmall * 2,
  1369. st::stickerPanSize.height() - st::roundRadiusSmall * 2);
  1370. }
  1371. void FieldAutocomplete::Inner::repaintSticker(
  1372. not_null<DocumentData*> document) {
  1373. const auto i = ranges::find(
  1374. *_srows,
  1375. document,
  1376. &StickerSuggestion::document);
  1377. if (i == end(*_srows)) {
  1378. return;
  1379. }
  1380. repaintStickerAtIndex(i - begin(*_srows));
  1381. }
  1382. void FieldAutocomplete::Inner::repaintStickerAtIndex(int index) {
  1383. const auto row = (index / _stickersPerRow);
  1384. const auto col = (index % _stickersPerRow);
  1385. update(
  1386. st::stickerPanPadding + col * st::stickerPanSize.width(),
  1387. st::stickerPanPadding + row * st::stickerPanSize.height(),
  1388. st::stickerPanSize.width(),
  1389. st::stickerPanSize.height());
  1390. }
  1391. void FieldAutocomplete::Inner::clipCallback(
  1392. Media::Clip::Notification notification,
  1393. not_null<DocumentData*> document) {
  1394. const auto i = ranges::find(
  1395. *_srows,
  1396. document,
  1397. &StickerSuggestion::document);
  1398. if (i == end(*_srows)) {
  1399. return;
  1400. }
  1401. using namespace Media::Clip;
  1402. switch (notification) {
  1403. case Notification::Reinit: {
  1404. if (!i->webm) {
  1405. break;
  1406. } else if (i->webm->state() == State::Error) {
  1407. i->webm.setBad();
  1408. } else if (i->webm->ready() && !i->webm->started()) {
  1409. const auto size = ComputeStickerSize(
  1410. i->document,
  1411. stickerBoundingBox());
  1412. i->webm->start({ .frame = size, .keepAlpha = true });
  1413. }
  1414. } break;
  1415. case Notification::Repaint: break;
  1416. }
  1417. repaintStickerAtIndex(i - begin(*_srows));
  1418. }
  1419. void FieldAutocomplete::Inner::selectByMouse(QPoint globalPosition) {
  1420. _mouseSelection = true;
  1421. _lastMousePosition = globalPosition;
  1422. const auto mouse = mapFromGlobal(globalPosition);
  1423. if (_down >= 0 && !_previewShown) {
  1424. return;
  1425. }
  1426. int32 sel = -1, maxSel = 0;
  1427. if (!_srows->empty()) {
  1428. int32 row = (mouse.y() >= st::stickerPanPadding) ? ((mouse.y() - st::stickerPanPadding) / st::stickerPanSize.height()) : -1;
  1429. int32 col = (mouse.x() >= st::stickerPanPadding) ? ((mouse.x() - st::stickerPanPadding) / st::stickerPanSize.width()) : -1;
  1430. if (row >= 0 && col >= 0) {
  1431. sel = row * _stickersPerRow + col;
  1432. }
  1433. maxSel = _srows->size();
  1434. _overDelete = false;
  1435. } else {
  1436. sel = mouse.y() / int32(st::mentionHeight);
  1437. maxSel = !_mrows->empty()
  1438. ? _mrows->size()
  1439. : !_hrows->empty()
  1440. ? _hrows->size()
  1441. : _brows->size();
  1442. _overDelete = (!_hrows->empty() || (!_mrows->empty() && sel < _recentInlineBotsInRows)) ? (mouse.x() >= width() - st::mentionHeight) : false;
  1443. }
  1444. if (sel < 0 || sel >= maxSel) {
  1445. sel = -1;
  1446. }
  1447. if (sel != _sel) {
  1448. setSel(sel);
  1449. if (_down >= 0 && _sel >= 0 && _down != _sel) {
  1450. _down = _sel;
  1451. showPreview();
  1452. }
  1453. }
  1454. }
  1455. void FieldAutocomplete::Inner::onParentGeometryChanged() {
  1456. const auto globalPosition = QCursor::pos();
  1457. if (rect().contains(mapFromGlobal(globalPosition))) {
  1458. setMouseTracking(true);
  1459. if (_mouseSelection) {
  1460. selectByMouse(globalPosition);
  1461. }
  1462. }
  1463. }
  1464. void FieldAutocomplete::Inner::showPreview() {
  1465. if (_down >= 0 && _down < _srows->size()) {
  1466. const auto document = (*_srows)[_down].document;
  1467. _show->showMediaPreview(document->stickerSetOrigin(), document);
  1468. _previewShown = true;
  1469. }
  1470. }
  1471. void FieldAutocomplete::Inner::setSendMenuDetails(
  1472. Fn<SendMenu::Details()> &&callback) {
  1473. _sendMenuDetails = std::move(callback);
  1474. }
  1475. auto FieldAutocomplete::Inner::mentionChosen() const
  1476. -> rpl::producer<FieldAutocomplete::MentionChosen> {
  1477. return _mentionChosen.events();
  1478. }
  1479. auto FieldAutocomplete::Inner::hashtagChosen() const
  1480. -> rpl::producer<FieldAutocomplete::HashtagChosen> {
  1481. return _hashtagChosen.events();
  1482. }
  1483. auto FieldAutocomplete::Inner::botCommandChosen() const
  1484. -> rpl::producer<FieldAutocomplete::BotCommandChosen> {
  1485. return _botCommandChosen.events();
  1486. }
  1487. auto FieldAutocomplete::Inner::stickerChosen() const
  1488. -> rpl::producer<FieldAutocomplete::StickerChosen> {
  1489. return _stickerChosen.events();
  1490. }
  1491. auto FieldAutocomplete::Inner::scrollToRequested() const
  1492. -> rpl::producer<ScrollTo> {
  1493. return _scrollToRequested.events();
  1494. }
  1495. void InitFieldAutocomplete(
  1496. std::unique_ptr<FieldAutocomplete> &autocomplete,
  1497. FieldAutocompleteDescriptor &&descriptor) {
  1498. Expects(!autocomplete);
  1499. autocomplete = std::make_unique<FieldAutocomplete>(
  1500. descriptor.parent,
  1501. descriptor.show,
  1502. descriptor.stOverride);
  1503. const auto raw = autocomplete.get();
  1504. const auto field = descriptor.field;
  1505. field->rawTextEdit()->installEventFilter(raw);
  1506. field->customTab(true);
  1507. raw->mentionChosen(
  1508. ) | rpl::start_with_next([=](FieldAutocomplete::MentionChosen data) {
  1509. const auto user = data.user;
  1510. if (data.mention.isEmpty()) {
  1511. field->insertTag(
  1512. user->firstName.isEmpty() ? user->name() : user->firstName,
  1513. PrepareMentionTag(user));
  1514. } else {
  1515. field->insertTag('@' + data.mention);
  1516. }
  1517. }, raw->lifetime());
  1518. const auto sendCommand = descriptor.sendBotCommand;
  1519. const auto setText = descriptor.setText;
  1520. raw->hashtagChosen(
  1521. ) | rpl::start_with_next([=](FieldAutocomplete::HashtagChosen data) {
  1522. field->insertTag(data.hashtag);
  1523. }, raw->lifetime());
  1524. const auto peer = descriptor.peer;
  1525. const auto features = descriptor.features;
  1526. const auto processShortcut = descriptor.processShortcut;
  1527. const auto shortcutMessages = (processShortcut != nullptr)
  1528. ? &peer->owner().shortcutMessages()
  1529. : nullptr;
  1530. raw->botCommandChosen(
  1531. ) | rpl::start_with_next([=](FieldAutocomplete::BotCommandChosen data) {
  1532. if (!features().autocompleteCommands) {
  1533. return;
  1534. }
  1535. using Method = FieldAutocompleteChooseMethod;
  1536. const auto byTab = (data.method == Method::ByTab);
  1537. const auto shortcut = data.user->isSelf();
  1538. // Send bot command at once, if it was not inserted by pressing Tab.
  1539. if (byTab && data.command.size() > 1) {
  1540. field->insertTag(data.command);
  1541. } else if (!shortcut) {
  1542. sendCommand(data.command);
  1543. setText(
  1544. field->getTextWithTagsPart(field->textCursor().position()));
  1545. } else if (processShortcut) {
  1546. processShortcut(data.command.mid(1));
  1547. }
  1548. }, raw->lifetime());
  1549. raw->setModerateKeyActivateCallback(std::move(descriptor.moderateKeyActivateCallback));
  1550. if (const auto stickerChoosing = descriptor.stickerChoosing) {
  1551. raw->choosingProcesses(
  1552. ) | rpl::start_with_next([=](FieldAutocomplete::Type type) {
  1553. if (type == FieldAutocomplete::Type::Stickers) {
  1554. stickerChoosing();
  1555. }
  1556. }, raw->lifetime());
  1557. }
  1558. if (const auto chosen = descriptor.stickerChosen) {
  1559. raw->stickerChosen(
  1560. ) | rpl::start_with_next(chosen, raw->lifetime());
  1561. }
  1562. field->tabbed(
  1563. ) | rpl::start_with_next([=] {
  1564. if (!raw->isHidden()) {
  1565. raw->chooseSelected(FieldAutocomplete::ChooseMethod::ByTab);
  1566. }
  1567. }, raw->lifetime());
  1568. const auto check = [=] {
  1569. auto parsed = ParseMentionHashtagBotCommandQuery(field, features());
  1570. if (parsed.query.isEmpty()) {
  1571. } else if (parsed.query[0] == '#'
  1572. && cRecentWriteHashtags().isEmpty()
  1573. && cRecentSearchHashtags().isEmpty()) {
  1574. peer->session().local().readRecentHashtagsAndBots();
  1575. } else if (parsed.query[0] == '@'
  1576. && cRecentInlineBots().isEmpty()) {
  1577. peer->session().local().readRecentHashtagsAndBots();
  1578. } else if (parsed.query[0] == '/'
  1579. && peer->isUser()
  1580. && !peer->asUser()->isBot()
  1581. && (!shortcutMessages
  1582. || shortcutMessages->shortcuts().list.empty()
  1583. || peer->starsPerMessageChecked() != 0)) {
  1584. parsed = {};
  1585. }
  1586. raw->showFiltered(peer, parsed.query, parsed.fromStart);
  1587. };
  1588. const auto updateStickersByEmoji = [=] {
  1589. const auto errorForStickers = Data::RestrictionError(
  1590. peer,
  1591. ChatRestriction::SendStickers);
  1592. if (features().suggestStickersByEmoji && !errorForStickers) {
  1593. const auto &text = field->getTextWithTags().text;
  1594. auto length = 0;
  1595. if (const auto emoji = Ui::Emoji::Find(text, &length)) {
  1596. if (text.size() <= length) {
  1597. raw->showStickers(emoji);
  1598. return;
  1599. }
  1600. }
  1601. }
  1602. raw->showStickers(nullptr);
  1603. };
  1604. raw->refreshRequests(
  1605. ) | rpl::start_with_next(check, raw->lifetime());
  1606. raw->stickersUpdateRequests(
  1607. ) | rpl::start_with_next(updateStickersByEmoji, raw->lifetime());
  1608. peer->owner().botCommandsChanges(
  1609. ) | rpl::filter([=](not_null<PeerData*> changed) {
  1610. return (peer == changed);
  1611. }) | rpl::start_with_next([=] {
  1612. if (raw->clearFilteredBotCommands()) {
  1613. check();
  1614. }
  1615. }, raw->lifetime());
  1616. peer->owner().stickers().updated(
  1617. Data::StickersType::Stickers
  1618. ) | rpl::start_with_next(updateStickersByEmoji, raw->lifetime());
  1619. QObject::connect(
  1620. field->rawTextEdit(),
  1621. &QTextEdit::cursorPositionChanged,
  1622. raw,
  1623. check,
  1624. Qt::QueuedConnection);
  1625. field->changes() | rpl::start_with_next(
  1626. updateStickersByEmoji,
  1627. raw->lifetime());
  1628. peer->session().changes().peerUpdates(
  1629. Data::PeerUpdate::Flag::Rights
  1630. ) | rpl::filter([=](const Data::PeerUpdate &update) {
  1631. return (update.peer == peer);
  1632. }) | rpl::start_with_next(updateStickersByEmoji, raw->lifetime());
  1633. if (shortcutMessages) {
  1634. shortcutMessages->shortcutsChanged(
  1635. ) | rpl::start_with_next(check, raw->lifetime());
  1636. }
  1637. raw->setSendMenuDetails(std::move(descriptor.sendMenuDetails));
  1638. raw->hideFast();
  1639. }
  1640. } // namespace ChatHelpers