emoji_list_widget.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909
  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/emoji_list_widget.h"
  8. #include "api/api_peer_photo.h"
  9. #include "apiwrap.h"
  10. #include "base/unixtime.h"
  11. #include "ui/boxes/confirm_box.h"
  12. #include "ui/controls/tabbed_search.h"
  13. #include "ui/text/format_values.h"
  14. #include "ui/effects/animations.h"
  15. #include "ui/widgets/menu/menu_add_action_callback.h"
  16. #include "ui/widgets/menu/menu_add_action_callback_factory.h"
  17. #include "ui/widgets/buttons.h"
  18. #include "ui/widgets/popup_menu.h"
  19. #include "ui/widgets/shadow.h"
  20. #include "ui/text/custom_emoji_instance.h"
  21. #include "ui/effects/ripple_animation.h"
  22. #include "ui/effects/premium_graphics.h"
  23. #include "ui/emoji_config.h"
  24. #include "ui/painter.h"
  25. #include "ui/power_saving.h"
  26. #include "ui/ui_utility.h"
  27. #include "ui/cached_round_corners.h"
  28. #include "boxes/sticker_set_box.h"
  29. #include "lang/lang_keys.h"
  30. #include "layout/layout_position.h"
  31. #include "data/data_emoji_statuses.h"
  32. #include "data/data_session.h"
  33. #include "data/data_changes.h"
  34. #include "data/data_channel.h"
  35. #include "data/data_document.h"
  36. #include "data/data_file_origin.h"
  37. #include "data/data_peer_values.h"
  38. #include "data/stickers/data_stickers.h"
  39. #include "data/stickers/data_custom_emoji.h"
  40. #include "chat_helpers/emoji_keywords.h"
  41. #include "chat_helpers/stickers_list_widget.h"
  42. #include "chat_helpers/stickers_list_footer.h"
  43. #include "emoji_suggestions_data.h"
  44. #include "emoji_suggestions_helper.h"
  45. #include "main/main_session.h"
  46. #include "main/main_session_settings.h"
  47. #include "core/core_settings.h"
  48. #include "core/application.h"
  49. #include "settings/settings_premium.h"
  50. #include "window/window_session_controller.h"
  51. #include "styles/style_chat_helpers.h"
  52. #include "styles/style_menu_icons.h"
  53. #include <QtWidgets/QApplication>
  54. namespace ChatHelpers {
  55. namespace {
  56. constexpr auto kCollapsedRows = 3;
  57. constexpr auto kAppearDuration = 0.3;
  58. constexpr auto kCustomSearchLimit = 256;
  59. constexpr auto kColorPickerDelay = crl::time(500);
  60. using Core::RecentEmojiId;
  61. using Core::RecentEmojiDocument;
  62. } // namespace
  63. class EmojiColorPicker final : public Ui::RpWidget {
  64. public:
  65. EmojiColorPicker(QWidget *parent, const style::EmojiPan &st);
  66. void showEmoji(EmojiPtr emoji, bool allLabel = false);
  67. void clearSelection();
  68. void handleMouseMove(QPoint globalPos);
  69. void handleMouseRelease(QPoint globalPos);
  70. void setSingleSize(QSize size);
  71. void showAnimated();
  72. void hideAnimated();
  73. void hideFast();
  74. [[nodiscard]] rpl::producer<EmojiChosen> chosen() const;
  75. [[nodiscard]] rpl::producer<> hidden() const;
  76. protected:
  77. void paintEvent(QPaintEvent *e) override;
  78. void mousePressEvent(QMouseEvent *e) override;
  79. void mouseReleaseEvent(QMouseEvent *e) override;
  80. void mouseMoveEvent(QMouseEvent *e) override;
  81. private:
  82. void createAllLabel();
  83. void animationCallback();
  84. void updateSize();
  85. [[nodiscard]] int topColorAllSkip() const;
  86. void drawVariant(QPainter &p, int variant);
  87. void updateSelected();
  88. void setSelected(int newSelected);
  89. const style::EmojiPan &_st;
  90. bool _ignoreShow = false;
  91. QVector<EmojiPtr> _variants;
  92. int _selected = -1;
  93. int _pressedSel = -1;
  94. QPoint _lastMousePos;
  95. QSize _singleSize;
  96. QPoint _areaPosition;
  97. QPoint _innerPosition;
  98. Ui::RoundRect _backgroundRect;
  99. Ui::RoundRect _overBg;
  100. bool _hiding = false;
  101. QPixmap _cache;
  102. Ui::Animations::Simple _a_opacity;
  103. std::unique_ptr<Ui::FlatLabel> _allLabel;
  104. rpl::event_stream<EmojiChosen> _chosen;
  105. rpl::event_stream<> _hidden;
  106. };
  107. struct EmojiListWidget::CustomEmojiInstance {
  108. std::unique_ptr<Ui::Text::CustomEmoji> emoji;
  109. bool recentOnly = false;
  110. };
  111. struct EmojiListWidget::RecentOne {
  112. std::shared_ptr<Data::EmojiStatusCollectible> collectible;
  113. Ui::Text::CustomEmoji *custom = nullptr;
  114. RecentEmojiId id;
  115. mutable QImage premiumLock;
  116. };
  117. EmojiColorPicker::EmojiColorPicker(
  118. QWidget *parent,
  119. const style::EmojiPan &st)
  120. : RpWidget(parent)
  121. , _st(st)
  122. , _backgroundRect(st::emojiPanRadius, _st.bg)
  123. , _overBg(st::emojiPanRadius, _st.overBg) {
  124. setMouseTracking(true);
  125. }
  126. void EmojiColorPicker::showEmoji(EmojiPtr emoji, bool allLabel) {
  127. if (!emoji || !emoji->hasVariants()) {
  128. return;
  129. }
  130. if (!allLabel) {
  131. _allLabel = nullptr;
  132. } else if (!_allLabel) {
  133. createAllLabel();
  134. }
  135. _ignoreShow = false;
  136. _variants.resize(emoji->variantsCount() + 1);
  137. for (auto i = 0, size = int(_variants.size()); i != size; ++i) {
  138. _variants[i] = emoji->variant(i);
  139. }
  140. updateSize();
  141. if (!_cache.isNull()) {
  142. _cache = QPixmap();
  143. }
  144. showAnimated();
  145. }
  146. void EmojiColorPicker::createAllLabel() {
  147. _allLabel = std::make_unique<Ui::FlatLabel>(
  148. this,
  149. tr::lng_emoji_color_all(),
  150. _st.colorAllLabel);
  151. _allLabel->show();
  152. _allLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
  153. }
  154. void EmojiColorPicker::updateSize() {
  155. auto width = st::emojiPanMargins.left()
  156. + _singleSize.width() * _variants.size()
  157. + (_variants.size() - 2) * st::emojiColorsPadding
  158. + st::emojiColorsSep
  159. + st::emojiPanMargins.right();
  160. auto height = st::emojiPanMargins.top()
  161. + 2 * st::emojiColorsPadding
  162. + _singleSize.height()
  163. + st::emojiPanMargins.bottom();
  164. if (_allLabel) {
  165. _allLabel->resizeToWidth(width
  166. - st::emojiPanMargins.left()
  167. - st::emojiPanMargins.right()
  168. - st::emojiPanColorAllPadding.left()
  169. - st::emojiPanColorAllPadding.right());
  170. _allLabel->move(
  171. st::emojiPanMargins.left() + st::emojiPanColorAllPadding.left(),
  172. st::emojiPanMargins.top() + st::emojiPanColorAllPadding.top());
  173. height += topColorAllSkip();
  174. }
  175. resize(width, height);
  176. update();
  177. updateSelected();
  178. }
  179. void EmojiColorPicker::paintEvent(QPaintEvent *e) {
  180. auto p = QPainter(this);
  181. auto opacity = _a_opacity.value(_hiding ? 0. : 1.);
  182. if (opacity < 1.) {
  183. if (opacity > 0.) {
  184. p.setOpacity(opacity);
  185. } else {
  186. return;
  187. }
  188. }
  189. if (e->rect() != rect()) {
  190. p.setClipRect(e->rect());
  191. }
  192. auto inner = rect().marginsRemoved(st::emojiPanMargins);
  193. if (!_cache.isNull()) {
  194. p.drawPixmap(0, 0, _cache);
  195. return;
  196. }
  197. Ui::Shadow::paint(p, inner, width(), _st.showAnimation.shadow);
  198. _backgroundRect.paint(p, inner);
  199. const auto skip = topColorAllSkip();
  200. auto x = st::emojiPanMargins.left() + 2 * st::emojiColorsPadding + _singleSize.width();
  201. if (rtl()) x = width() - x - st::emojiColorsSep;
  202. p.fillRect(x, st::emojiPanMargins.top() + skip + st::emojiColorsPadding, st::emojiColorsSep, inner.height() - st::emojiColorsPadding * 2 - skip, st::emojiColorsSepColor);
  203. if (_variants.isEmpty()) {
  204. return;
  205. }
  206. p.translate(0, skip);
  207. for (auto i = 0, count = int(_variants.size()); i != count; ++i) {
  208. drawVariant(p, i);
  209. }
  210. }
  211. void EmojiColorPicker::mousePressEvent(QMouseEvent *e) {
  212. if (e->button() != Qt::LeftButton) {
  213. return;
  214. }
  215. _lastMousePos = e->globalPos();
  216. updateSelected();
  217. _pressedSel = _selected;
  218. }
  219. void EmojiColorPicker::mouseReleaseEvent(QMouseEvent *e) {
  220. handleMouseRelease(e->globalPos());
  221. }
  222. void EmojiColorPicker::handleMouseRelease(QPoint globalPos) {
  223. _lastMousePos = globalPos;
  224. int32 pressed = _pressedSel;
  225. _pressedSel = -1;
  226. updateSelected();
  227. if (_selected >= 0 && (pressed < 0 || _selected == pressed)) {
  228. _chosen.fire_copy({ .emoji = _variants[_selected] });
  229. }
  230. _ignoreShow = true;
  231. hideAnimated();
  232. }
  233. void EmojiColorPicker::setSingleSize(QSize size) {
  234. const auto area = st::emojiPanArea;
  235. _singleSize = size;
  236. _areaPosition = QPoint(
  237. (_singleSize.width() - area.width()) / 2,
  238. (_singleSize.height() - area.height()) / 2);
  239. const auto esize = Ui::Emoji::GetSizeLarge() / style::DevicePixelRatio();
  240. _innerPosition = QPoint(
  241. (area.width() - esize) / 2,
  242. (area.height() - esize) / 2);
  243. updateSize();
  244. }
  245. void EmojiColorPicker::handleMouseMove(QPoint globalPos) {
  246. _lastMousePos = globalPos;
  247. updateSelected();
  248. }
  249. void EmojiColorPicker::mouseMoveEvent(QMouseEvent *e) {
  250. handleMouseMove(e->globalPos());
  251. }
  252. void EmojiColorPicker::animationCallback() {
  253. update();
  254. if (!_a_opacity.animating()) {
  255. _cache = QPixmap();
  256. if (_allLabel) {
  257. _allLabel->show();
  258. }
  259. if (_hiding) {
  260. hide();
  261. _hidden.fire({});
  262. } else {
  263. _lastMousePos = QCursor::pos();
  264. updateSelected();
  265. }
  266. }
  267. }
  268. void EmojiColorPicker::hideFast() {
  269. clearSelection();
  270. _a_opacity.stop();
  271. _cache = QPixmap();
  272. hide();
  273. _hidden.fire({});
  274. }
  275. rpl::producer<EmojiChosen> EmojiColorPicker::chosen() const {
  276. return _chosen.events();
  277. }
  278. rpl::producer<> EmojiColorPicker::hidden() const {
  279. return _hidden.events();
  280. }
  281. void EmojiColorPicker::hideAnimated() {
  282. if (_cache.isNull()) {
  283. if (_allLabel) {
  284. _allLabel->show();
  285. }
  286. _cache = Ui::GrabWidget(this);
  287. clearSelection();
  288. }
  289. _hiding = true;
  290. if (_allLabel) {
  291. _allLabel->hide();
  292. }
  293. _a_opacity.start([this] { animationCallback(); }, 1., 0., st::emojiPanDuration);
  294. }
  295. void EmojiColorPicker::showAnimated() {
  296. if (_ignoreShow) return;
  297. if (!isHidden() && !_hiding) {
  298. return;
  299. }
  300. _hiding = false;
  301. if (_cache.isNull()) {
  302. if (_allLabel) {
  303. _allLabel->show();
  304. }
  305. _cache = Ui::GrabWidget(this);
  306. clearSelection();
  307. }
  308. show();
  309. if (_allLabel) {
  310. _allLabel->hide();
  311. }
  312. _a_opacity.start([this] { animationCallback(); }, 0., 1., st::emojiPanDuration);
  313. }
  314. void EmojiColorPicker::clearSelection() {
  315. _pressedSel = -1;
  316. setSelected(-1);
  317. _lastMousePos = mapToGlobal(QPoint(-10, -10));
  318. }
  319. int EmojiColorPicker::topColorAllSkip() const {
  320. return _allLabel
  321. ? (st::emojiPanColorAllPadding.top()
  322. + _allLabel->height()
  323. + st::emojiPanColorAllPadding.bottom())
  324. : 0;
  325. }
  326. void EmojiColorPicker::updateSelected() {
  327. auto newSelected = -1;
  328. auto p = mapFromGlobal(_lastMousePos);
  329. auto sx = rtl() ? (width() - p.x()) : p.x(), y = p.y() - st::emojiPanMargins.top() - topColorAllSkip() - st::emojiColorsPadding;
  330. if (y >= 0 && y < _singleSize.height()) {
  331. auto x = sx - st::emojiPanMargins.left() - st::emojiColorsPadding;
  332. if (x >= 0 && x < _singleSize.width()) {
  333. newSelected = 0;
  334. } else {
  335. x -= _singleSize.width() + 2 * st::emojiColorsPadding + st::emojiColorsSep;
  336. if (x >= 0 && x < _singleSize.width() * (_variants.size() - 1)) {
  337. newSelected = (x / _singleSize.width()) + 1;
  338. }
  339. }
  340. }
  341. setSelected(newSelected);
  342. }
  343. void EmojiColorPicker::setSelected(int newSelected) {
  344. if (_selected == newSelected) {
  345. return;
  346. }
  347. const auto skip = topColorAllSkip();
  348. const auto updateSelectedRect = [&] {
  349. if (_selected < 0) return;
  350. auto addedSkip = (_selected > 0)
  351. ? (2 * st::emojiColorsPadding + st::emojiColorsSep)
  352. : 0;
  353. auto left = st::emojiPanMargins.left()
  354. + st::emojiColorsPadding
  355. + _selected * _singleSize.width()
  356. + addedSkip;
  357. rtlupdate(
  358. left,
  359. st::emojiPanMargins.top() + st::emojiColorsPadding + skip,
  360. _singleSize.width(),
  361. _singleSize.height());
  362. };
  363. updateSelectedRect();
  364. _selected = newSelected;
  365. updateSelectedRect();
  366. setCursor((_selected >= 0) ? style::cur_pointer : style::cur_default);
  367. }
  368. void EmojiColorPicker::drawVariant(QPainter &p, int variant) {
  369. const auto w = QPoint(
  370. st::emojiPanMargins.left(),
  371. st::emojiPanMargins.top()
  372. ) + QPoint(
  373. (st::emojiColorsPadding
  374. + variant * _singleSize.width()
  375. + (variant
  376. ? (2 * st::emojiColorsPadding + st::emojiColorsSep)
  377. : 0)),
  378. st::emojiColorsPadding
  379. ) + _areaPosition;
  380. if (variant == _selected) {
  381. QPoint tl(w);
  382. if (rtl()) tl.setX(width() - tl.x() - st::emojiPanArea.width());
  383. _overBg.paint(p, QRect(tl, st::emojiPanArea));
  384. }
  385. Ui::Emoji::Draw(
  386. p,
  387. _variants[variant],
  388. Ui::Emoji::GetSizeLarge(),
  389. w.x() + _innerPosition.x(),
  390. w.y() + _innerPosition.y());
  391. }
  392. std::vector<EmojiStatusId> DocumentListToRecent(
  393. const std::vector<DocumentId> &documents) {
  394. return documents | ranges::views::transform([](DocumentId id) {
  395. return EmojiStatusId{ .documentId = id };
  396. }) | ranges::to_vector;
  397. }
  398. EmojiListWidget::EmojiListWidget(
  399. QWidget *parent,
  400. not_null<Window::SessionController*> controller,
  401. PauseReason level,
  402. Mode mode)
  403. : EmojiListWidget(parent, {
  404. .show = controller->uiShow(),
  405. .mode = mode,
  406. .paused = Window::PausedIn(controller, level),
  407. }) {
  408. }
  409. EmojiListWidget::EmojiListWidget(
  410. QWidget *parent,
  411. EmojiListDescriptor &&descriptor)
  412. : Inner(
  413. parent,
  414. descriptor.st ? *descriptor.st : st::defaultEmojiPan,
  415. descriptor.show,
  416. std::move(descriptor.paused))
  417. , _show(std::move(descriptor.show))
  418. , _features(descriptor.features)
  419. , _onlyUnicodeEmoji(descriptor.mode == Mode::PeerTitle)
  420. , _mode(_onlyUnicodeEmoji ? Mode::Full : descriptor.mode)
  421. , _api(&session().mtp())
  422. , _staticCount(_mode == Mode::Full ? kEmojiSectionCount : 1)
  423. , _premiumIcon(_mode == Mode::EmojiStatus
  424. ? std::make_unique<GradientPremiumStar>()
  425. : nullptr)
  426. , _localSetsManager(
  427. std::make_unique<LocalStickersManager>(&session()))
  428. , _customRecentFactory(std::move(descriptor.customRecentFactory))
  429. , _freeEffects(std::move(descriptor.freeEffects))
  430. , _customTextColor(std::move(descriptor.customTextColor))
  431. , _overBg(st::emojiPanRadius, st().overBg)
  432. , _premiumMark(std::make_unique<StickerPremiumMark>(
  433. &session(),
  434. st::emojiPremiumLock))
  435. , _collapsedBg(st::emojiPanExpand.height / 2, st().headerFg)
  436. , _picker(this, st())
  437. , _showPickerTimer([=] { showPicker(); })
  438. , _previewTimer([=] { showPreview(); }) {
  439. setMouseTracking(true);
  440. if (st().bg->c.alpha() > 0) {
  441. setAttribute(Qt::WA_OpaquePaintEvent);
  442. }
  443. if (_mode != Mode::RecentReactions
  444. && _mode != Mode::BackgroundEmoji
  445. && _mode != Mode::ChannelStatus
  446. && !_onlyUnicodeEmoji) {
  447. setupSearch();
  448. }
  449. if (_mode == Mode::ChannelStatus) {
  450. session().api().peerPhoto().emojiListValue(
  451. Api::PeerPhoto::EmojiListType::NoChannelStatus
  452. ) | rpl::start_with_next([=](const std::vector<DocumentId> &list) {
  453. _restrictedCustomList = { begin(list), end(list) };
  454. if (!_custom.empty()) {
  455. refreshCustom();
  456. }
  457. }, lifetime());
  458. } else if (_mode == Mode::EmojiStatus && _features.collectibleStatus) {
  459. session().data().emojiStatuses().collectiblesUpdates(
  460. ) | rpl::start_with_next([=] {
  461. refreshCustom();
  462. }, lifetime());
  463. }
  464. _customSingleSize = Data::FrameSizeFromTag(
  465. Data::CustomEmojiManager::SizeTag::Large
  466. ) / style::DevicePixelRatio();
  467. _picker->hide();
  468. for (auto i = 1; i != _staticCount; ++i) {
  469. const auto section = static_cast<Section>(i);
  470. _counts[i] = Ui::Emoji::GetSectionCount(section);
  471. }
  472. _picker->chosen(
  473. ) | rpl::start_with_next([=](EmojiChosen data) {
  474. colorChosen(data);
  475. }, lifetime());
  476. _picker->hidden(
  477. ) | rpl::start_with_next([=] {
  478. pickerHidden();
  479. }, lifetime());
  480. session().changes().peerUpdates(
  481. Data::PeerUpdate::Flag::EmojiSet
  482. ) | rpl::filter([=](const Data::PeerUpdate &update) {
  483. return (update.peer.get() == _megagroupSet);
  484. }) | rpl::start_with_next([=] {
  485. refreshCustom();
  486. resizeToWidth(width());
  487. }, lifetime());
  488. session().data().stickers().updated(
  489. Data::StickersType::Emoji
  490. ) | rpl::start_with_next([=] {
  491. refreshCustom();
  492. resizeToWidth(width());
  493. }, lifetime());
  494. rpl::combine(
  495. Data::AmPremiumValue(&session()),
  496. session().premiumPossibleValue()
  497. ) | rpl::skip(1) | rpl::start_with_next([=] {
  498. refreshCustom();
  499. resizeToWidth(width());
  500. }, lifetime());
  501. rpl::single(
  502. rpl::empty
  503. ) | rpl::then(
  504. style::PaletteChanged()
  505. ) | rpl::start_with_next([=] {
  506. initButton(_add, tr::lng_stickers_featured_add(tr::now), false);
  507. initButton(_unlock, tr::lng_emoji_featured_unlock(tr::now), true);
  508. initButton(_restore, tr::lng_emoji_premium_restore(tr::now), true);
  509. }, lifetime());
  510. if (!descriptor.customRecentList.empty()) {
  511. fillRecentFrom(descriptor.customRecentList);
  512. }
  513. }
  514. EmojiListWidget::~EmojiListWidget() {
  515. base::take(_customEmoji);
  516. }
  517. void EmojiListWidget::setupSearch() {
  518. const auto session = &_show->session();
  519. const auto type = (_mode == Mode::EmojiStatus)
  520. ? TabbedSearchType::Status
  521. : (_mode == Mode::UserpicBuilder)
  522. ? TabbedSearchType::ProfilePhoto
  523. : TabbedSearchType::Emoji;
  524. _search = MakeSearch(this, st(), [=](std::vector<QString> &&query) {
  525. _nextSearchQuery = std::move(query);
  526. InvokeQueued(this, [=] {
  527. applyNextSearchQuery();
  528. });
  529. _searchQueries.fire_copy(_nextSearchQuery);
  530. }, session, type);
  531. }
  532. rpl::producer<std::vector<QString>> EmojiListWidget::searchQueries() const {
  533. return _searchQueries.events();
  534. }
  535. rpl::producer<int> EmojiListWidget::recentShownCount() const {
  536. return _recentShownCount.value();
  537. }
  538. void EmojiListWidget::applyNextSearchQuery() {
  539. if (_searchQuery == _nextSearchQuery) {
  540. return;
  541. }
  542. _searchQuery = _nextSearchQuery;
  543. std::swap(_searchEmoji, _searchEmojiPrevious);
  544. _searchEmoji.clear();
  545. const auto finish = [&](bool searching = true) {
  546. if (!_searchMode && !searching) {
  547. return;
  548. }
  549. const auto modeChanged = (_searchMode != searching);
  550. clearSelection();
  551. if (modeChanged) {
  552. if (_picker) {
  553. _picker->hideAnimated();
  554. }
  555. _colorAllRipple = nullptr;
  556. for (auto &set : _custom) {
  557. set.ripple = nullptr;
  558. }
  559. _searchMode = searching;
  560. }
  561. if (!searching) {
  562. _searchResults.clear();
  563. _searchCustomIds.clear();
  564. }
  565. resizeToWidth(width());
  566. _recentShownCount = searching
  567. ? _searchResults.size()
  568. : _recent.size();
  569. update();
  570. if (modeChanged) {
  571. visibleTopBottomUpdated(getVisibleTop(), getVisibleBottom());
  572. }
  573. updateSelected();
  574. };
  575. if (_searchQuery.empty()) {
  576. finish(false);
  577. return;
  578. }
  579. const auto guard = gsl::finally([&] { finish(); });
  580. auto plain = collectPlainSearchResults();
  581. if (_searchEmoji == _searchEmojiPrevious) {
  582. return;
  583. }
  584. _searchResults.clear();
  585. _searchCustomIds.clear();
  586. if (_mode != Mode::Full || session().premium()) {
  587. appendPremiumSearchResults();
  588. }
  589. if (_mode == Mode::Full) {
  590. for (const auto emoji : plain) {
  591. _searchResults.push_back({
  592. .id = { emoji },
  593. });
  594. }
  595. }
  596. }
  597. void EmojiListWidget::showPreview() {
  598. if (const auto over = std::get_if<OverEmoji>(&_pressed)) {
  599. if (const auto custom = lookupCustomEmoji(over)) {
  600. const auto document = custom.document;
  601. _show->showMediaPreview(document->stickerSetOrigin(), document);
  602. _previewShown = true;
  603. }
  604. }
  605. }
  606. std::vector<EmojiPtr> EmojiListWidget::collectPlainSearchResults() {
  607. return SearchEmoji(_searchQuery, _searchEmoji);
  608. }
  609. void EmojiListWidget::appendPremiumSearchResults() {
  610. const auto test = session().isTestMode();
  611. auto &owner = session().data();
  612. const auto checkCustom = [&](EmojiPtr emoji, DocumentId id) {
  613. return emoji
  614. && _searchEmoji.contains(emoji)
  615. && (_searchResults.size() < kCustomSearchLimit)
  616. && _searchCustomIds.emplace(id).second;
  617. };
  618. for (const auto &recent : _recent) {
  619. if (!recent.custom) {
  620. continue;
  621. }
  622. const auto &idData = recent.id.data;
  623. const auto id = std::get_if<Core::RecentEmojiDocument>(&idData);
  624. if (!id || id->test != test) {
  625. continue;
  626. }
  627. const auto sticker = owner.document(id->id)->sticker();
  628. const auto emoji = sticker
  629. ? Ui::Emoji::Find(sticker->alt)
  630. : nullptr;
  631. if (checkCustom(emoji, id->id)) {
  632. _searchResults.push_back(recent);
  633. }
  634. }
  635. for (const auto &set : _custom) {
  636. for (const auto &one : set.list) {
  637. const auto id = one.document->id;
  638. if (checkCustom(one.emoji, id)) {
  639. _searchResults.push_back({
  640. .custom = one.custom,
  641. .id = { RecentEmojiDocument{ .id = id, .test = test } },
  642. });
  643. }
  644. }
  645. }
  646. }
  647. void EmojiListWidget::provideRecent(
  648. const std::vector<EmojiStatusId> &customRecentList) {
  649. clearSelection();
  650. fillRecentFrom(customRecentList);
  651. resizeToWidth(width());
  652. }
  653. void EmojiListWidget::repaintCustom(uint64 setId) {
  654. if (!_repaintsScheduled.emplace(setId).second) {
  655. return;
  656. }
  657. const auto repaintSearch = (setId == SearchEmojiSectionSetId());
  658. if (_searchMode) {
  659. if (repaintSearch) {
  660. update();
  661. }
  662. return;
  663. }
  664. const auto repaintRecent = (setId == RecentEmojiSectionSetId());
  665. enumerateSections([&](const SectionInfo &info) {
  666. const auto repaint1 = repaintRecent
  667. && (info.section == int(Section::Recent));
  668. const auto repaint2 = !repaint1
  669. && (info.section >= _staticCount)
  670. && (setId == _custom[info.section - _staticCount].id);
  671. if (repaint1 || repaint2) {
  672. update(
  673. 0,
  674. info.rowsTop,
  675. width(),
  676. info.rowsBottom - info.rowsTop);
  677. }
  678. return true;
  679. });
  680. }
  681. rpl::producer<EmojiChosen> EmojiListWidget::chosen() const {
  682. return _chosen.events();
  683. }
  684. rpl::producer<FileChosen> EmojiListWidget::customChosen() const {
  685. return _customChosen.events();
  686. }
  687. rpl::producer<> EmojiListWidget::jumpedToPremium() const {
  688. return _jumpedToPremium.events();
  689. }
  690. rpl::producer<> EmojiListWidget::escapes() const {
  691. return _search ? _search->escapes() : rpl::never<>();
  692. }
  693. void EmojiListWidget::prepareExpanding() {
  694. if (_search) {
  695. _searchExpandCache = _search->grab();
  696. }
  697. }
  698. void EmojiListWidget::paintExpanding(
  699. Painter &p,
  700. QRect clip,
  701. int finalBottom,
  702. float64 geometryProgress,
  703. float64 fullProgress,
  704. RectPart origin) {
  705. const auto searchShift = _search
  706. ? anim::interpolate(
  707. st().padding.top() - _search->height(),
  708. 0,
  709. geometryProgress)
  710. : 0;
  711. const auto shift = clip.topLeft() + QPoint(0, searchShift);
  712. const auto adjusted = clip.translated(-shift);
  713. const auto finalHeight = (finalBottom - clip.y());
  714. if (!_searchExpandCache.isNull()) {
  715. p.setClipRect(clip);
  716. p.drawImage(
  717. clip.x() + st().searchMargin.left(),
  718. clip.y() + st().searchMargin.top() + searchShift,
  719. _searchExpandCache);
  720. }
  721. p.translate(shift);
  722. p.setClipRect(adjusted);
  723. paint(p, ExpandingContext{
  724. .progress = fullProgress,
  725. .finalHeight = finalHeight,
  726. .expanding = true,
  727. }, adjusted);
  728. p.translate(-shift);
  729. }
  730. void EmojiListWidget::visibleTopBottomUpdated(
  731. int visibleTop,
  732. int visibleBottom) {
  733. Inner::visibleTopBottomUpdated(visibleTop, visibleBottom);
  734. if (_footer) {
  735. _footer->validateSelectedIcon(
  736. currentSet(visibleTop),
  737. ValidateIconAnimations::Full);
  738. }
  739. unloadNotSeenCustom(visibleTop, visibleBottom);
  740. }
  741. void EmojiListWidget::unloadNotSeenCustom(
  742. int visibleTop,
  743. int visibleBottom) {
  744. enumerateSections([&](const SectionInfo &info) {
  745. if (info.rowsBottom <= visibleTop || info.rowsTop >= visibleBottom) {
  746. unloadCustomIn(info);
  747. }
  748. return true;
  749. });
  750. }
  751. void EmojiListWidget::unloadAllCustom() {
  752. enumerateSections([&](const SectionInfo &info) {
  753. unloadCustomIn(info);
  754. return true;
  755. });
  756. }
  757. void EmojiListWidget::unloadCustomIn(const SectionInfo &info) {
  758. if (!info.section && _recentPainted) {
  759. _recentPainted = false;
  760. for (const auto &single : _recent) {
  761. if (const auto custom = single.custom) {
  762. custom->unload();
  763. }
  764. }
  765. return;
  766. } else if (info.section < _staticCount) {
  767. return;
  768. }
  769. auto &custom = _custom[info.section - _staticCount];
  770. if (!custom.painted) {
  771. return;
  772. }
  773. custom.painted = false;
  774. for (const auto &single : custom.list) {
  775. single.custom->unload();
  776. }
  777. }
  778. object_ptr<TabbedSelector::InnerFooter> EmojiListWidget::createFooter() {
  779. Expects(_footer == nullptr);
  780. if (_mode == EmojiListMode::RecentReactions
  781. || _mode == EmojiListMode::MessageEffects) {
  782. return { nullptr };
  783. }
  784. using FooterDescriptor = StickersListFooter::Descriptor;
  785. const auto flag = powerSavingFlag();
  786. const auto footerPaused = [method = pausedMethod(), flag]() {
  787. return On(flag) || method();
  788. };
  789. auto result = object_ptr<StickersListFooter>(FooterDescriptor{
  790. .session = &session(),
  791. .customTextColor = _customTextColor,
  792. .paused = footerPaused,
  793. .parent = this,
  794. .st = &st(),
  795. .features = { .stickersSettings = false },
  796. .forceFirstFrame = (_mode == Mode::BackgroundEmoji),
  797. });
  798. _footer = result;
  799. _footer->setChosen(
  800. ) | rpl::start_with_next([=](uint64 setId) {
  801. showSet(setId);
  802. }, _footer->lifetime());
  803. return result;
  804. }
  805. void EmojiListWidget::afterShown() {
  806. const auto steal = (_mode == Mode::EmojiStatus)
  807. || (_mode == Mode::FullReactions)
  808. || (_mode == Mode::UserpicBuilder);
  809. if (_search && steal) {
  810. _search->stealFocus();
  811. }
  812. }
  813. void EmojiListWidget::beforeHiding() {
  814. if (_search) {
  815. _search->returnFocus();
  816. }
  817. }
  818. template <typename Callback>
  819. bool EmojiListWidget::enumerateSections(Callback callback) const {
  820. Expects(_columnCount > 0);
  821. auto i = 0;
  822. auto info = SectionInfo();
  823. const auto next = [&] {
  824. info.rowsCount = info.collapsed
  825. ? kCollapsedRows
  826. : (info.count + _columnCount - 1) / _columnCount;
  827. info.rowsTop = info.top
  828. + (i == 0 ? _rowsTop : st().header);
  829. info.rowsBottom = info.rowsTop
  830. + (info.rowsCount * _singleSize.height());
  831. if (!callback(info)) {
  832. return false;
  833. }
  834. info.top = info.rowsBottom;
  835. return true;
  836. };
  837. if (_searchMode) {
  838. info.section = i;
  839. info.count = _searchResults.size();
  840. return next();
  841. }
  842. for (; i != _staticCount; ++i) {
  843. info.section = i;
  844. info.count = i ? _counts[i] : _recent.size();
  845. if (!next()) {
  846. return false;
  847. }
  848. }
  849. for (auto &section : _custom) {
  850. info.section = i++;
  851. info.premiumRequired = section.premiumRequired;
  852. info.count = int(section.list.size());
  853. info.collapsed = !section.expanded
  854. && (!section.canRemove || section.premiumRequired)
  855. && (info.count > _columnCount * kCollapsedRows);
  856. if (!next()) {
  857. return false;
  858. }
  859. }
  860. return true;
  861. }
  862. EmojiListWidget::SectionInfo EmojiListWidget::sectionInfo(int section) const {
  863. Expects(section >= 0 && section < sectionsCount());
  864. auto result = SectionInfo();
  865. enumerateSections([&](const SectionInfo &info) {
  866. if (info.section == section) {
  867. result = info;
  868. return false;
  869. }
  870. return true;
  871. });
  872. return result;
  873. }
  874. EmojiListWidget::SectionInfo EmojiListWidget::sectionInfoByOffset(
  875. int yOffset) const {
  876. auto result = SectionInfo();
  877. const auto count = sectionsCount();
  878. enumerateSections([&result, count, yOffset](const SectionInfo &info) {
  879. if (yOffset < info.rowsBottom || info.section == count - 1) {
  880. result = info;
  881. return false;
  882. }
  883. return true;
  884. });
  885. return result;
  886. }
  887. int EmojiListWidget::sectionsCount() const {
  888. return _searchMode ? 1 : (_staticCount + int(_custom.size()));
  889. }
  890. void EmojiListWidget::setSingleSize(QSize size) {
  891. const auto area = st::emojiPanArea;
  892. _singleSize = size;
  893. _areaPosition = QPoint(
  894. (_singleSize.width() - area.width()) / 2,
  895. (_singleSize.height() - area.height()) / 2);
  896. const auto esize = Ui::Emoji::GetSizeLarge() / style::DevicePixelRatio();
  897. _innerPosition = QPoint(
  898. (area.width() - esize) / 2,
  899. (area.height() - esize) / 2);
  900. const auto customSkip = (esize - _customSingleSize) / 2;
  901. _customPosition = QPoint(customSkip, customSkip);
  902. _picker->setSingleSize(_singleSize);
  903. }
  904. void EmojiListWidget::setColorAllForceRippled(bool force) {
  905. _colorAllRippleForced = force;
  906. if (_colorAllRippleForced) {
  907. _colorAllRippleForcedLifetime = style::PaletteChanged(
  908. ) | rpl::filter([=] {
  909. return _colorAllRipple != nullptr;
  910. }) | rpl::start_with_next([=] {
  911. _colorAllRipple->forceRepaint();
  912. });
  913. if (!_colorAllRipple) {
  914. _colorAllRipple = createButtonRipple(int(Section::People));
  915. }
  916. if (_colorAllRipple->empty()) {
  917. _colorAllRipple->addFading();
  918. } else {
  919. _colorAllRipple->lastUnstop();
  920. }
  921. } else {
  922. if (_colorAllRipple) {
  923. _colorAllRipple->lastStop();
  924. }
  925. _colorAllRippleForcedLifetime.destroy();
  926. }
  927. }
  928. int EmojiListWidget::countDesiredHeight(int newWidth) {
  929. const auto fullWidth = st().margin.left()
  930. + newWidth
  931. + st().margin.right();
  932. const auto padding = st().padding;
  933. const auto innerWidth = fullWidth - padding.left() - padding.right();
  934. _columnCount = std::max(innerWidth / st().desiredSize, 1);
  935. const auto singleWidth = innerWidth / _columnCount;
  936. _rowsTop = _search ? _search->height() : padding.top();
  937. _rowsLeft = padding.left()
  938. + (innerWidth - _columnCount * singleWidth) / 2
  939. - st().margin.left();
  940. setSingleSize({ singleWidth, singleWidth - 2 * st().verticalSizeSub });
  941. const auto countResult = [this](int minimalLastHeight) {
  942. const auto info = sectionInfo(sectionsCount() - 1);
  943. return info.top
  944. + qMax(info.rowsBottom - info.top, minimalLastHeight);
  945. };
  946. const auto minimalHeight = this->minimalHeight();
  947. const auto minimalLastHeight = std::max(
  948. minimalHeight - padding.bottom(),
  949. 0);
  950. const auto result = countResult(minimalLastHeight);
  951. return result
  952. ? qMax(minimalHeight, result + padding.bottom())
  953. : 0;
  954. }
  955. int EmojiListWidget::defaultMinimalHeight() const {
  956. return Inner::defaultMinimalHeight();
  957. }
  958. void EmojiListWidget::ensureLoaded(int section) {
  959. Expects(section >= 0 && section < sectionsCount());
  960. if (section == int(Section::Recent)) {
  961. if (_recent.empty()) {
  962. fillRecent();
  963. }
  964. return;
  965. } else if (section >= _staticCount || !_emoji[section].empty()) {
  966. return;
  967. }
  968. _emoji[section] = Ui::Emoji::GetSection(static_cast<Section>(section));
  969. _counts[section] = _emoji[section].size();
  970. const auto &settings = Core::App().settings();
  971. for (auto &emoji : _emoji[section]) {
  972. emoji = settings.lookupEmojiVariant(emoji);
  973. }
  974. }
  975. void EmojiListWidget::fillRecent() {
  976. if (_mode != Mode::Full) {
  977. return;
  978. }
  979. _recent.clear();
  980. _recentCustomIds.clear();
  981. const auto &list = Core::App().settings().recentEmoji();
  982. _recent.reserve(std::min(int(list.size()), Core::kRecentEmojiLimit) + 1);
  983. const auto test = session().isTestMode();
  984. for (const auto &one : list) {
  985. const auto document = std::get_if<RecentEmojiDocument>(&one.id.data);
  986. if (document && ((document->test != test) || _onlyUnicodeEmoji)) {
  987. continue;
  988. }
  989. _recent.push_back({
  990. .custom = resolveCustomRecent(one.id),
  991. .id = one.id,
  992. });
  993. if (document) {
  994. _recentCustomIds.emplace(document->id);
  995. }
  996. if (_recent.size() >= Core::kRecentEmojiLimit) {
  997. break;
  998. }
  999. }
  1000. }
  1001. void EmojiListWidget::fillRecentFrom(
  1002. const std::vector<EmojiStatusId> &list) {
  1003. const auto test = session().isTestMode();
  1004. _recent.clear();
  1005. _recent.reserve(list.size());
  1006. for (const auto &id : list) {
  1007. if (!id && _mode == Mode::EmojiStatus) {
  1008. const auto star = QString::fromUtf8("\xe2\xad\x90\xef\xb8\x8f");
  1009. _recent.push_back({ .id = { Ui::Emoji::Find(star) } });
  1010. } else if (!id
  1011. && (_mode == Mode::BackgroundEmoji
  1012. || _mode == Mode::ChannelStatus)) {
  1013. const auto fakeId = DocumentId(5246772116543512028ULL);
  1014. const auto no = QString::fromUtf8("\xe2\x9b\x94\xef\xb8\x8f");
  1015. _recent.push_back({
  1016. .custom = resolveCustomRecent(fakeId),
  1017. .id = { Ui::Emoji::Find(no) },
  1018. });
  1019. _recentCustomIds.emplace(fakeId);
  1020. } else {
  1021. _recent.push_back({
  1022. .collectible = id.collectible,
  1023. .custom = resolveCustomRecent(id),
  1024. .id = {
  1025. RecentEmojiDocument{ .id = id.documentId, .test = test },
  1026. },
  1027. });
  1028. _recentCustomIds.emplace(id.collectible
  1029. ? id.collectible->documentId
  1030. : id.documentId);
  1031. }
  1032. }
  1033. }
  1034. base::unique_qptr<Ui::PopupMenu> EmojiListWidget::fillContextMenu(
  1035. const SendMenu::Details &details) {
  1036. if (v::is_null(_selected)) {
  1037. return nullptr;
  1038. }
  1039. const auto over = std::get_if<OverEmoji>(&_selected);
  1040. if (!over) {
  1041. return nullptr;
  1042. }
  1043. const auto section = over->section;
  1044. const auto index = over->index;
  1045. auto menu = base::make_unique_q<Ui::PopupMenu>(
  1046. this,
  1047. (_mode == Mode::Full
  1048. ? st::popupMenuWithIcons
  1049. : st::defaultPopupMenu));
  1050. if (_mode == Mode::Full) {
  1051. fillRecentMenu(menu, section, index);
  1052. } else if (_mode == Mode::EmojiStatus || _mode == Mode::ChannelStatus) {
  1053. fillEmojiStatusMenu(menu, section, index);
  1054. }
  1055. if (menu->empty()) {
  1056. return nullptr;
  1057. }
  1058. return menu;
  1059. }
  1060. void EmojiListWidget::fillRecentMenu(
  1061. not_null<Ui::PopupMenu*> menu,
  1062. int section,
  1063. int index) {
  1064. const auto recent = (section == int(Section::Recent));
  1065. const auto addAction = Ui::Menu::CreateAddActionCallback(menu);
  1066. const auto over = OverEmoji{ section, index };
  1067. const auto emoji = lookupOverEmoji(&over);
  1068. const auto custom = lookupCustomEmoji(&over);
  1069. if (custom.collectible) {
  1070. return;
  1071. }
  1072. const auto document = custom.document;
  1073. if (document && document->sticker()) {
  1074. const auto sticker = document->sticker();
  1075. const auto emoji = sticker->alt;
  1076. const auto setId = sticker->set.id;
  1077. if (!emoji.isEmpty()) {
  1078. auto data = TextForMimeData{ emoji, { emoji } };
  1079. data.rich.entities.push_back({
  1080. EntityType::CustomEmoji,
  1081. 0,
  1082. int(emoji.size()),
  1083. Data::SerializeCustomEmojiId(document)
  1084. });
  1085. addAction(tr::lng_emoji_copy(tr::now), [=] {
  1086. TextUtilities::SetClipboardText(data);
  1087. }, &st::menuIconCopy);
  1088. }
  1089. if (recent && setId && _features.openStickerSets) {
  1090. addAction(
  1091. tr::lng_emoji_view_pack(tr::now),
  1092. crl::guard(this, [=] { displaySet(setId); }),
  1093. &st::menuIconShowAll);
  1094. }
  1095. } else if (recent && emoji) {
  1096. addAction(tr::lng_emoji_copy(tr::now), [=] {
  1097. const auto text = emoji->text();
  1098. TextUtilities::SetClipboardText({ text, { text } });
  1099. }, &st::menuIconCopy);
  1100. }
  1101. if (!recent) {
  1102. return;
  1103. }
  1104. auto id = RecentEmojiId{ emoji };
  1105. if (custom) {
  1106. id.data = RecentEmojiDocument{
  1107. .id = custom.document->id,
  1108. .test = custom.document->session().isTestMode(),
  1109. };
  1110. }
  1111. addAction(tr::lng_emoji_remove_recent(tr::now), crl::guard(this, [=] {
  1112. Core::App().settings().hideRecentEmoji(id);
  1113. refreshRecent();
  1114. }), &st::menuIconCancel);
  1115. menu->addSeparator(&st().expandedSeparator);
  1116. const auto resetRecent = [=] {
  1117. const auto sure = [=](Fn<void()> &&close) {
  1118. Core::App().settings().resetRecentEmoji();
  1119. refreshRecent();
  1120. close();
  1121. };
  1122. checkHideWithBox(Ui::MakeConfirmBox({
  1123. .text = tr::lng_emoji_reset_recent_sure(),
  1124. .confirmed = crl::guard(this, sure),
  1125. .confirmText = tr::lng_emoji_reset_recent_button(tr::now),
  1126. .labelStyle = &st().boxLabel,
  1127. }));
  1128. };
  1129. addAction({
  1130. .text = tr::lng_emoji_reset_recent(tr::now),
  1131. .handler = crl::guard(this, resetRecent),
  1132. .icon = &st::menuIconRestoreAttention,
  1133. .isAttention = true,
  1134. });
  1135. }
  1136. void EmojiListWidget::fillEmojiStatusMenu(
  1137. not_null<Ui::PopupMenu*> menu,
  1138. int section,
  1139. int index) {
  1140. const auto chosen = lookupCustomEmoji(index, section);
  1141. if (!chosen) {
  1142. return;
  1143. }
  1144. const auto selectWith = [=](TimeId scheduled) {
  1145. selectCustom(
  1146. lookupChosen(chosen, nullptr, { .scheduled = scheduled }));
  1147. };
  1148. for (const auto &value : { 3600, 3600 * 8, 3600 * 24, 3600 * 24 * 7 }) {
  1149. const auto text = tr::lng_emoji_status_menu_duration_any(
  1150. tr::now,
  1151. lt_duration,
  1152. Ui::FormatMuteFor(value));
  1153. menu->addAction(text, crl::guard(this, [=] {
  1154. selectWith(base::unixtime::now() + value);
  1155. }));
  1156. }
  1157. menu->addAction(
  1158. tr::lng_manage_messages_ttl_after_custom(tr::now),
  1159. crl::guard(this, [=] { selectWith(
  1160. TabbedSelector::kPickCustomTimeId); }));
  1161. }
  1162. void EmojiListWidget::paintEvent(QPaintEvent *e) {
  1163. auto p = Painter(this);
  1164. const auto clip = e ? e->rect() : rect();
  1165. _repaintsScheduled.clear();
  1166. if (_grabbingChosen) {
  1167. p.setCompositionMode(QPainter::CompositionMode_Source);
  1168. p.fillRect(clip, Qt::transparent);
  1169. p.setCompositionMode(QPainter::CompositionMode_SourceOver);
  1170. } else if (st().bg->c.alpha() > 0) {
  1171. p.fillRect(clip, st().bg);
  1172. }
  1173. if (!_searchExpandCache.isNull()) {
  1174. _searchExpandCache = QImage();
  1175. }
  1176. paint(p, {}, clip);
  1177. }
  1178. void EmojiListWidget::validateEmojiPaintContext(
  1179. const ExpandingContext &context) {
  1180. auto value = Ui::Text::CustomEmojiPaintContext{
  1181. .textColor = (_customTextColor
  1182. ? _customTextColor()
  1183. : (_mode == Mode::EmojiStatus || _mode == Mode::ChannelStatus)
  1184. ? anim::color(
  1185. st::stickerPanPremium1,
  1186. st::stickerPanPremium2,
  1187. 0.5)
  1188. : st().textFg->c),
  1189. .size = QSize(_customSingleSize, _customSingleSize),
  1190. .now = crl::now(),
  1191. .scale = context.progress,
  1192. .paused = On(powerSavingFlag()) || paused(),
  1193. .scaled = context.expanding,
  1194. .internal = { .forceFirstFrame = (_mode == Mode::BackgroundEmoji) },
  1195. };
  1196. if (!_emojiPaintContext) {
  1197. _emojiPaintContext = std::make_unique<
  1198. Ui::Text::CustomEmojiPaintContext
  1199. >(std::move(value));
  1200. } else {
  1201. *_emojiPaintContext = std::move(value);
  1202. }
  1203. }
  1204. void EmojiListWidget::paint(
  1205. Painter &p,
  1206. ExpandingContext context,
  1207. QRect clip) {
  1208. validateEmojiPaintContext(context);
  1209. _paintAsPremium = session().premium();
  1210. auto fromColumn = floorclamp(
  1211. clip.x() - _rowsLeft,
  1212. _singleSize.width(),
  1213. 0,
  1214. _columnCount);
  1215. auto toColumn = ceilclamp(
  1216. clip.x() + clip.width() - _rowsLeft,
  1217. _singleSize.width(),
  1218. 0,
  1219. _columnCount);
  1220. if (rtl()) {
  1221. qSwap(fromColumn, toColumn);
  1222. fromColumn = _columnCount - fromColumn;
  1223. toColumn = _columnCount - toColumn;
  1224. }
  1225. const auto expandProgress = context.progress;
  1226. auto selectedButton = std::get_if<OverButton>(!v::is_null(_pressed)
  1227. ? &_pressed
  1228. : &_selected);
  1229. if (_searchResults.empty() && _searchMode) {
  1230. paintEmptySearchResults(p);
  1231. }
  1232. enumerateSections([&](const SectionInfo &info) {
  1233. if (clip.top() >= info.rowsBottom) {
  1234. return true;
  1235. } else if (clip.top() + clip.height() <= info.top) {
  1236. return false;
  1237. }
  1238. const auto buttonSelected = selectedButton
  1239. ? (selectedButton->section == info.section)
  1240. : false;
  1241. const auto titleLeft = (info.premiumRequired
  1242. ? st().headerLockedLeft
  1243. : st().headerLeft) - st().margin.left();
  1244. const auto widthForTitle = emojiRight()
  1245. - titleLeft
  1246. - paintButtonGetWidth(p, info, buttonSelected, clip);
  1247. if (info.section > 0 && clip.top() < info.rowsTop) {
  1248. p.setFont(st::emojiPanHeaderFont);
  1249. p.setPen(st().headerFg);
  1250. auto titleText = (info.section < _staticCount)
  1251. ? ChatHelpers::EmojiCategoryTitle(info.section)(tr::now)
  1252. : _custom[info.section - _staticCount].title;
  1253. auto titleWidth = st::emojiPanHeaderFont->width(titleText);
  1254. if (titleWidth > widthForTitle) {
  1255. titleText = st::emojiPanHeaderFont->elided(titleText, widthForTitle);
  1256. titleWidth = st::emojiPanHeaderFont->width(titleText);
  1257. }
  1258. const auto top = info.top + st().headerTop;
  1259. if (info.premiumRequired) {
  1260. st::emojiPremiumRequired.paint(
  1261. p,
  1262. st().headerLockLeft - st().margin.left(),
  1263. top,
  1264. width());
  1265. }
  1266. const auto textBaseline = top + st::emojiPanHeaderFont->ascent;
  1267. p.setFont(st::emojiPanHeaderFont);
  1268. p.setPen(st().headerFg);
  1269. p.drawText(titleLeft, textBaseline, titleText);
  1270. }
  1271. if (clip.top() + clip.height() > info.rowsTop) {
  1272. ensureLoaded(info.section);
  1273. auto fromRow = floorclamp(
  1274. clip.y() - info.rowsTop,
  1275. _singleSize.height(),
  1276. 0,
  1277. info.rowsCount);
  1278. auto toRow = ceilclamp(
  1279. clip.y() + clip.height() - info.rowsTop,
  1280. _singleSize.height(),
  1281. 0,
  1282. info.rowsCount);
  1283. for (auto i = fromRow; i < toRow; ++i) {
  1284. for (auto j = fromColumn; j < toColumn; ++j) {
  1285. const auto index = i * _columnCount + j;
  1286. if (index >= info.count) {
  1287. break;
  1288. }
  1289. const auto state = OverEmoji{
  1290. .section = info.section,
  1291. .index = index,
  1292. };
  1293. const auto selected = (state == _selected)
  1294. || (!_picker->isHidden()
  1295. && state == _pickerSelected);
  1296. const auto position = QPoint(
  1297. _rowsLeft + j * _singleSize.width(),
  1298. info.rowsTop + i * _singleSize.height()
  1299. );
  1300. const auto w = position + _areaPosition;
  1301. if (context.expanding) {
  1302. const auto y = (position.y() - _rowsTop);
  1303. const auto x = (position.x() - _rowsLeft);
  1304. const auto sum = y
  1305. + std::max(std::min(y, width()) - x, 0);
  1306. const auto maxSum = context.finalHeight
  1307. + std::min(context.finalHeight, width());
  1308. const auto started = (sum / float64(maxSum))
  1309. - kAppearDuration;
  1310. context.progress = (expandProgress <= started)
  1311. ? 0.
  1312. : (expandProgress >= started + kAppearDuration)
  1313. ? 1.
  1314. : ((expandProgress - started) / kAppearDuration);
  1315. }
  1316. if (info.collapsed
  1317. && index + 1 == _columnCount * kCollapsedRows) {
  1318. drawCollapsedBadge(p, w - _areaPosition, info.count);
  1319. continue;
  1320. }
  1321. if (!_grabbingChosen
  1322. && selected
  1323. && st().overBg->c.alpha() > 0) {
  1324. auto tl = w;
  1325. if (rtl()) {
  1326. tl.setX(width() - tl.x() - st::emojiPanArea.width());
  1327. }
  1328. _overBg.paint(p, QRect(tl, st::emojiPanArea));
  1329. }
  1330. if (_searchMode) {
  1331. drawRecent(p, context, w, _searchResults[index]);
  1332. } else if (info.section == int(Section::Recent)) {
  1333. drawRecent(p, context, w, _recent[index]);
  1334. } else if (info.section < _staticCount) {
  1335. drawEmoji(p, context, w, _emoji[info.section][index]);
  1336. } else {
  1337. const auto set = info.section - _staticCount;
  1338. drawCustom(p, context, w, set, index);
  1339. }
  1340. }
  1341. }
  1342. }
  1343. return true;
  1344. });
  1345. }
  1346. void EmojiListWidget::drawCollapsedBadge(
  1347. QPainter &p,
  1348. QPoint position,
  1349. int count) {
  1350. const auto &st = st::emojiPanExpand;
  1351. const auto text = u"+%1"_q.arg(count - _columnCount * kCollapsedRows + 1);
  1352. const auto textWidth = st.style.font->width(text);
  1353. const auto buttonw = std::max(textWidth - st.width, st.height);
  1354. const auto buttonh = st.height;
  1355. const auto buttonx = position.x() + (_singleSize.width() - buttonw) / 2;
  1356. const auto buttony = position.y() + (_singleSize.height() - buttonh) / 2;
  1357. _collapsedBg.paint(p, QRect(buttonx, buttony, buttonw, buttonh));
  1358. p.setPen(this->st().bg);
  1359. p.setFont(st.style.font);
  1360. p.drawText(
  1361. buttonx + (buttonw - textWidth) / 2,
  1362. (buttony + st.textTop + st.style.font->ascent),
  1363. text);
  1364. }
  1365. void EmojiListWidget::drawRecent(
  1366. QPainter &p,
  1367. const ExpandingContext &context,
  1368. QPoint position,
  1369. const RecentOne &recent) {
  1370. _recentPainted = true;
  1371. const auto locked = (_mode == Mode::MessageEffects)
  1372. && !_paintAsPremium
  1373. && v::is<RecentEmojiDocument>(recent.id.data)
  1374. && !_freeEffects.contains(
  1375. v::get<RecentEmojiDocument>(recent.id.data).id);
  1376. auto lockedPainted = false;
  1377. if (locked) {
  1378. if (_premiumMarkFrameCache.isNull()) {
  1379. const auto ratio = style::DevicePixelRatio();
  1380. _premiumMarkFrameCache = QImage(
  1381. QSize(_customSingleSize, _customSingleSize) * ratio,
  1382. QImage::Format_ARGB32_Premultiplied);
  1383. _premiumMarkFrameCache.setDevicePixelRatio(ratio);
  1384. }
  1385. _premiumMarkFrameCache.fill(Qt::transparent);
  1386. }
  1387. if (const auto custom = recent.custom) {
  1388. const auto exactPosition = position
  1389. + _innerPosition
  1390. + _customPosition;
  1391. _emojiPaintContext->scale = context.progress;
  1392. if (_mode == Mode::ChannelStatus) {
  1393. _emojiPaintContext->internal.forceFirstFrame
  1394. = (recent.id == _recent.front().id);
  1395. }
  1396. if (locked) {
  1397. lockedPainted = custom->ready();
  1398. auto q = Painter(&_premiumMarkFrameCache);
  1399. _emojiPaintContext->position = QPoint();
  1400. custom->paint(q, *_emojiPaintContext);
  1401. q.end();
  1402. p.drawImage(exactPosition, _premiumMarkFrameCache);
  1403. } else {
  1404. _emojiPaintContext->position = exactPosition;
  1405. custom->paint(p, *_emojiPaintContext);
  1406. }
  1407. } else if (const auto emoji = std::get_if<EmojiPtr>(&recent.id.data)) {
  1408. if (_mode == Mode::EmojiStatus) {
  1409. position += QPoint(
  1410. (_singleSize.width() - st::emojiStatusDefault.width()) / 2,
  1411. (_singleSize.height() - st::emojiStatusDefault.height()) / 2
  1412. ) - _areaPosition;
  1413. p.drawImage(position, _premiumIcon->image());
  1414. } else {
  1415. drawEmoji(p, context, position, *emoji);
  1416. }
  1417. } else {
  1418. Unexpected("Empty custom emoji in EmojiListWidget::drawRecent.");
  1419. }
  1420. if (locked) {
  1421. _premiumMark->paint(
  1422. p,
  1423. lockedPainted ? _premiumMarkFrameCache : QImage(),
  1424. recent.premiumLock,
  1425. position,
  1426. _singleSize,
  1427. width());
  1428. }
  1429. }
  1430. void EmojiListWidget::drawEmoji(
  1431. QPainter &p,
  1432. const ExpandingContext &context,
  1433. QPoint position,
  1434. EmojiPtr emoji) {
  1435. position += _innerPosition;
  1436. Ui::Emoji::Draw(
  1437. p,
  1438. emoji,
  1439. Ui::Emoji::GetSizeLarge(),
  1440. position.x(),
  1441. position.y());
  1442. }
  1443. void EmojiListWidget::drawCustom(
  1444. QPainter &p,
  1445. const ExpandingContext &context,
  1446. QPoint position,
  1447. int set,
  1448. int index) {
  1449. auto &custom = _custom[set];
  1450. custom.painted = true;
  1451. auto &entry = custom.list[index];
  1452. _emojiPaintContext->scale = context.progress;
  1453. _emojiPaintContext->position = position
  1454. + _innerPosition
  1455. + _customPosition;
  1456. entry.custom->paint(p, *_emojiPaintContext);
  1457. }
  1458. bool EmojiListWidget::checkPickerHide() {
  1459. if (!_picker->isHidden() && !v::is_null(_pickerSelected)) {
  1460. _picker->hideAnimated();
  1461. _pickerSelected = v::null;
  1462. updateSelected();
  1463. return true;
  1464. }
  1465. return false;
  1466. }
  1467. EmojiListWidget::ResolvedCustom EmojiListWidget::lookupCustomEmoji(
  1468. const OverEmoji *over) const {
  1469. return over
  1470. ? lookupCustomEmoji(over->index, over->section)
  1471. : ResolvedCustom();
  1472. }
  1473. EmojiListWidget::ResolvedCustom EmojiListWidget::lookupCustomEmoji(
  1474. int index,
  1475. int section) const {
  1476. if (_searchMode) {
  1477. if (index < _searchResults.size()) {
  1478. const auto document = std::get_if<RecentEmojiDocument>(
  1479. &_searchResults[index].id.data);
  1480. if (document) {
  1481. return { session().data().document(document->id) };
  1482. }
  1483. }
  1484. return {};
  1485. } else if (section == int(Section::Recent) && index < _recent.size()) {
  1486. const auto &recent = _recent[index];
  1487. if (recent.collectible) {
  1488. return {
  1489. session().data().document(recent.collectible->documentId),
  1490. recent.collectible,
  1491. };
  1492. }
  1493. const auto document = std::get_if<RecentEmojiDocument>(
  1494. &recent.id.data);
  1495. if (document) {
  1496. return { session().data().document(document->id) };
  1497. }
  1498. } else if (section >= _staticCount
  1499. && index < _custom[section - _staticCount].list.size()) {
  1500. auto &set = _custom[section - _staticCount];
  1501. auto &entry = set.list[index];
  1502. return { entry.document, entry.collectible };
  1503. }
  1504. return {};
  1505. }
  1506. EmojiPtr EmojiListWidget::lookupOverEmoji(const OverEmoji *over) const {
  1507. const auto section = over ? over->section : -1;
  1508. const auto index = over ? over->index : -1;
  1509. return _searchMode
  1510. ? ((index < _searchResults.size()
  1511. && v::is<EmojiPtr>(_searchResults[index].id.data))
  1512. ? v::get<EmojiPtr>(_searchResults[index].id.data)
  1513. : nullptr)
  1514. : (section == int(Section::Recent)
  1515. && index < _recent.size()
  1516. && v::is<EmojiPtr>(_recent[index].id.data))
  1517. ? v::get<EmojiPtr>(_recent[index].id.data)
  1518. : (section > int(Section::Recent)
  1519. && section < _staticCount
  1520. && index < _emoji[section].size())
  1521. ? _emoji[section][index]
  1522. : nullptr;
  1523. }
  1524. EmojiChosen EmojiListWidget::lookupChosen(
  1525. EmojiPtr emoji,
  1526. not_null<const OverEmoji*> over) {
  1527. const auto rect = emojiRect(over->section, over->index);
  1528. const auto size = st::emojiStatusDefault.size();
  1529. const auto icon = QRect(
  1530. rect.x() + (_singleSize.width() - size.width()) / 2,
  1531. rect.y() + (_singleSize.height() - size.height()) / 2,
  1532. rect.width(),
  1533. rect.height());
  1534. return {
  1535. .emoji = emoji,
  1536. .messageSendingFrom = {
  1537. .type = Ui::MessageSendingAnimationFrom::Type::Emoji,
  1538. .globalStartGeometry = mapToGlobal(icon),
  1539. },
  1540. };
  1541. }
  1542. FileChosen EmojiListWidget::lookupChosen(
  1543. ResolvedCustom custom,
  1544. const OverEmoji *over,
  1545. Api::SendOptions options) {
  1546. Expects(custom.document != nullptr);
  1547. _grabbingChosen = true;
  1548. const auto guard = gsl::finally([&] { _grabbingChosen = false; });
  1549. const auto rect = over ? emojiRect(over->section, over->index) : QRect();
  1550. const auto emoji = over ? QRect(
  1551. rect.topLeft() + _areaPosition + _innerPosition + _customPosition,
  1552. QSize(_customSingleSize, _customSingleSize)
  1553. ) : QRect();
  1554. return {
  1555. .document = custom.document,
  1556. .options = options,
  1557. .messageSendingFrom = {
  1558. .type = Ui::MessageSendingAnimationFrom::Type::Emoji,
  1559. .globalStartGeometry = over ? mapToGlobal(emoji) : QRect(),
  1560. .frame = over ? Ui::GrabWidgetToImage(this, emoji) : QImage(),
  1561. },
  1562. .collectible = custom.collectible,
  1563. };
  1564. }
  1565. void EmojiListWidget::mousePressEvent(QMouseEvent *e) {
  1566. _lastMousePos = e->globalPos();
  1567. updateSelected();
  1568. if (checkPickerHide() || e->button() != Qt::LeftButton) {
  1569. return;
  1570. }
  1571. setPressed(_selected);
  1572. if (const auto over = std::get_if<OverEmoji>(&_selected)) {
  1573. const auto emoji = lookupOverEmoji(over);
  1574. if (emoji && emoji->hasVariants()) {
  1575. _pickerSelected = _selected;
  1576. setCursor(style::cur_default);
  1577. if (!Core::App().settings().hasChosenEmojiVariant(emoji)) {
  1578. showPicker();
  1579. } else {
  1580. _previewTimer.cancel();
  1581. _showPickerTimer.callOnce(kColorPickerDelay);
  1582. }
  1583. } else if (lookupCustomEmoji(over)) {
  1584. _showPickerTimer.cancel();
  1585. _previewTimer.callOnce(QApplication::startDragTime());
  1586. }
  1587. }
  1588. }
  1589. void EmojiListWidget::mouseReleaseEvent(QMouseEvent *e) {
  1590. _previewTimer.cancel();
  1591. auto pressed = _pressed;
  1592. setPressed(v::null);
  1593. _lastMousePos = e->globalPos();
  1594. if (!_picker->isHidden()) {
  1595. if (_picker->rect().contains(_picker->mapFromGlobal(_lastMousePos))) {
  1596. return _picker->handleMouseRelease(QCursor::pos());
  1597. } else if (const auto over = std::get_if<OverEmoji>(&_pickerSelected)) {
  1598. const auto emoji = lookupOverEmoji(over);
  1599. if (emoji
  1600. && emoji->hasVariants()
  1601. && Core::App().settings().hasChosenEmojiVariant(emoji)) {
  1602. _picker->hideAnimated();
  1603. _pickerSelected = v::null;
  1604. }
  1605. }
  1606. }
  1607. updateSelected();
  1608. if (_showPickerTimer.isActive()) {
  1609. _showPickerTimer.cancel();
  1610. _pickerSelected = v::null;
  1611. _picker->hide();
  1612. }
  1613. if (_previewShown) {
  1614. _previewShown = false;
  1615. return;
  1616. } else if (v::is_null(_selected) || _selected != pressed) {
  1617. return;
  1618. }
  1619. if (const auto over = std::get_if<OverEmoji>(&_selected)) {
  1620. const auto section = over->section;
  1621. const auto index = over->index;
  1622. if (section >= _staticCount
  1623. && sectionInfo(section).collapsed
  1624. && index + 1 == _columnCount * kCollapsedRows) {
  1625. _custom[section - _staticCount].expanded = true;
  1626. resizeToWidth(width());
  1627. update();
  1628. return;
  1629. } else if (const auto emoji = lookupOverEmoji(over)) {
  1630. if (emoji->hasVariants() && !_picker->isHidden()) {
  1631. return;
  1632. }
  1633. selectEmoji(lookupChosen(emoji, over));
  1634. } else if (const auto custom = lookupCustomEmoji(over)) {
  1635. selectCustom(lookupChosen(custom, over));
  1636. }
  1637. } else if (const auto set = std::get_if<OverSet>(&pressed)) {
  1638. Assert(set->section >= _staticCount
  1639. && set->section < _staticCount + _custom.size());
  1640. displaySet(_custom[set->section - _staticCount].id);
  1641. } else if (auto button = std::get_if<OverButton>(&pressed)) {
  1642. Assert(hasButton(button->section));
  1643. const auto id = hasColorButton(button->section)
  1644. ? 0
  1645. : _custom[button->section - _staticCount].id;
  1646. if (hasColorButton(button->section)) {
  1647. _pickerSelected = pressed;
  1648. showPicker();
  1649. } else if (hasRemoveButton(button->section)) {
  1650. removeSet(id);
  1651. } else if (hasAddButton(button->section)) {
  1652. _localSetsManager->install(id);
  1653. } else if (const auto resolved = _show->resolveWindow()) {
  1654. _jumpedToPremium.fire({});
  1655. switch (_mode) {
  1656. case Mode::Full:
  1657. case Mode::UserpicBuilder:
  1658. Settings::ShowPremium(resolved, u"animated_emoji"_q);
  1659. break;
  1660. case Mode::FullReactions:
  1661. case Mode::RecentReactions:
  1662. Settings::ShowPremium(resolved, u"infinite_reactions"_q);
  1663. break;
  1664. case Mode::EmojiStatus:
  1665. case Mode::ChannelStatus:
  1666. Settings::ShowPremium(resolved, u"emoji_status"_q);
  1667. break;
  1668. case Mode::TopicIcon:
  1669. Settings::ShowPremium(resolved, u"forum_topic_icon"_q);
  1670. break;
  1671. case Mode::BackgroundEmoji:
  1672. Settings::ShowPremium(resolved, u"name_color"_q);
  1673. break;
  1674. }
  1675. }
  1676. }
  1677. }
  1678. void EmojiListWidget::displaySet(uint64 setId) {
  1679. if (setId == Data::Stickers::MegagroupSetId) {
  1680. if (_megagroupSet->mgInfo->emojiSet.id) {
  1681. setId = _megagroupSet->mgInfo->emojiSet.id;
  1682. } else {
  1683. return;
  1684. }
  1685. } else if (setId == Data::Stickers::CollectibleSetId) {
  1686. return;
  1687. }
  1688. const auto &sets = session().data().stickers().sets();
  1689. auto it = sets.find(setId);
  1690. if (it != sets.cend()) {
  1691. checkHideWithBox(Box<StickerSetBox>(_show, it->second.get()));
  1692. }
  1693. }
  1694. void EmojiListWidget::removeMegagroupSet(bool locally) {
  1695. if (locally) {
  1696. session().settings().setGroupEmojiSectionHidden(_megagroupSet->id);
  1697. session().saveSettings();
  1698. refreshCustom();
  1699. return;
  1700. }
  1701. checkHideWithBox(Ui::MakeConfirmBox({
  1702. .text = tr::lng_emoji_remove_group_set(),
  1703. .confirmed = crl::guard(this, [this, group = _megagroupSet](
  1704. Fn<void()> &&close) {
  1705. Expects(group->mgInfo != nullptr);
  1706. if (group->mgInfo->emojiSet) {
  1707. session().api().setGroupEmojiSet(group, {});
  1708. }
  1709. close();
  1710. }),
  1711. .cancelled = [](Fn<void()> &&close) { close(); },
  1712. .labelStyle = &st().boxLabel,
  1713. }));
  1714. }
  1715. void EmojiListWidget::removeSet(uint64 setId) {
  1716. const auto &labelSt = st().boxLabel;
  1717. if (setId == Data::Stickers::MegagroupSetId) {
  1718. const auto i = ranges::find(_custom, setId, &CustomSet::id);
  1719. Assert(i != end(_custom));
  1720. const auto removeLocally = !_megagroupSet->canEditEmoji();
  1721. removeMegagroupSet(removeLocally);
  1722. } else if (setId == Data::Stickers::CollectibleSetId) {
  1723. } else if (auto box = MakeConfirmRemoveSetBox(&session(), labelSt, setId)) {
  1724. checkHideWithBox(std::move(box));
  1725. }
  1726. }
  1727. void EmojiListWidget::selectEmoji(EmojiChosen data) {
  1728. Core::App().settings().incrementRecentEmoji({ data.emoji });
  1729. _chosen.fire(std::move(data));
  1730. }
  1731. void EmojiListWidget::selectCustom(FileChosen data) {
  1732. const auto document = data.document;
  1733. const auto skip = (document->isPremiumEmoji() && !session().premium());
  1734. if (!skip && _mode == Mode::Full) {
  1735. auto &settings = Core::App().settings();
  1736. settings.incrementRecentEmoji({ RecentEmojiDocument{
  1737. document->id,
  1738. document->session().isTestMode(),
  1739. } });
  1740. }
  1741. _customChosen.fire(std::move(data));
  1742. }
  1743. void EmojiListWidget::showPicker() {
  1744. if (v::is_null(_pickerSelected)) {
  1745. return;
  1746. }
  1747. const auto showAt = [&](float64 xCoef, int y, int height) {
  1748. y -= _picker->height() - st::emojiPanRadius + getVisibleTop();
  1749. if (y < st().header) {
  1750. y += _picker->height() + height;
  1751. }
  1752. auto xmax = width() - _picker->width();
  1753. if (rtl()) xCoef = 1. - xCoef;
  1754. _picker->move(qRound(xmax * xCoef), y);
  1755. disableScroll(true);
  1756. };
  1757. if (const auto button = std::get_if<OverButton>(&_pickerSelected)) {
  1758. const auto hand = QString::fromUtf8("\xF0\x9F\x91\x8B");
  1759. const auto emoji = Ui::Emoji::Find(hand);
  1760. Assert(emoji != nullptr && emoji->hasVariants());
  1761. _picker->showEmoji(emoji, true);
  1762. setColorAllForceRippled(true);
  1763. const auto rect = buttonRect(button->section);
  1764. showAt(1., rect.y(), rect.height() - 2 * st::emojiPanRadius);
  1765. } else if (const auto over = std::get_if<OverEmoji>(&_pickerSelected)) {
  1766. const auto emoji = lookupOverEmoji(over);
  1767. if (emoji && emoji->hasVariants()) {
  1768. _picker->showEmoji(emoji);
  1769. const auto coef = float64(over->index % _columnCount)
  1770. / float64(_columnCount - 1);
  1771. const auto h = _singleSize.height() - 2 * st::emojiPanRadius;
  1772. showAt(coef, emojiRect(over->section, over->index).y(), h);
  1773. }
  1774. }
  1775. }
  1776. void EmojiListWidget::pickerHidden() {
  1777. _pickerSelected = v::null;
  1778. update();
  1779. disableScroll(false);
  1780. setColorAllForceRippled(false);
  1781. _lastMousePos = QCursor::pos();
  1782. updateSelected();
  1783. }
  1784. bool EmojiListWidget::hasColorButton(int index) const {
  1785. return (_staticCount > int(Section::People))
  1786. && (index == int(Section::People));
  1787. }
  1788. QRect EmojiListWidget::colorButtonRect(int index) const {
  1789. return colorButtonRect(sectionInfo(index));
  1790. }
  1791. QRect EmojiListWidget::colorButtonRect(const SectionInfo &info) const {
  1792. if (_mode != Mode::Full) {
  1793. return QRect();
  1794. }
  1795. const auto &colorSt = st().colorAll;
  1796. const auto buttonw = colorSt.rippleAreaPosition.x()
  1797. + colorSt.rippleAreaSize;
  1798. const auto buttonh = colorSt.height;
  1799. const auto buttonx = emojiRight() - st::emojiPanColorAllSkip - buttonw;
  1800. const auto buttony = info.top + st::emojiPanRemoveTop;
  1801. return QRect(buttonx, buttony, buttonw, buttonh);
  1802. }
  1803. bool EmojiListWidget::hasRemoveButton(int index) const {
  1804. if (index < _staticCount
  1805. || index >= _staticCount + _custom.size()) {
  1806. return false;
  1807. }
  1808. const auto &set = _custom[index - _staticCount];
  1809. if (set.id == Data::Stickers::MegagroupSetId) {
  1810. Assert(_megagroupSet != nullptr);
  1811. if (index + 1 != _staticCount + _custom.size()) {
  1812. return true;
  1813. }
  1814. return !set.list.empty() && _megagroupSet->canEditEmoji();
  1815. } else if (set.id == Data::Stickers::CollectibleSetId) {
  1816. return false;
  1817. }
  1818. return set.canRemove && !set.premiumRequired;
  1819. }
  1820. QRect EmojiListWidget::removeButtonRect(int index) const {
  1821. return removeButtonRect(sectionInfo(index));
  1822. }
  1823. QRect EmojiListWidget::removeButtonRect(const SectionInfo &info) const {
  1824. if (_mode != Mode::Full) {
  1825. return QRect();
  1826. }
  1827. const auto &removeSt = st().removeSet;
  1828. const auto buttonw = removeSt.rippleAreaPosition.x()
  1829. + removeSt.rippleAreaSize;
  1830. const auto buttonh = removeSt.height;
  1831. const auto buttonx = emojiRight() - st::emojiPanRemoveSkip - buttonw;
  1832. const auto buttony = info.top + st::emojiPanRemoveTop;
  1833. return QRect(buttonx, buttony, buttonw, buttonh);
  1834. }
  1835. bool EmojiListWidget::hasAddButton(int index) const {
  1836. if (index < _staticCount
  1837. || index >= _staticCount + _custom.size()) {
  1838. return false;
  1839. }
  1840. const auto &set = _custom[index - _staticCount];
  1841. return !set.canRemove
  1842. && !set.premiumRequired
  1843. && set.id != Data::Stickers::MegagroupSetId
  1844. && set.id != Data::Stickers::CollectibleSetId;
  1845. }
  1846. QRect EmojiListWidget::addButtonRect(int index) const {
  1847. return buttonRect(sectionInfo(index), _add);
  1848. }
  1849. bool EmojiListWidget::hasUnlockButton(int index) const {
  1850. if (index < _staticCount
  1851. || index >= _staticCount + _custom.size()) {
  1852. return false;
  1853. }
  1854. const auto &set = _custom[index - _staticCount];
  1855. return set.premiumRequired;
  1856. }
  1857. QRect EmojiListWidget::unlockButtonRect(int index) const {
  1858. Expects(index >= _staticCount
  1859. && index < _staticCount + _custom.size());
  1860. return buttonRect(sectionInfo(index), rightButton(index));
  1861. }
  1862. bool EmojiListWidget::hasButton(int index) const {
  1863. if (hasColorButton(index)) {
  1864. return true;
  1865. } else if (index >= _staticCount
  1866. && index < _staticCount + _custom.size()) {
  1867. const auto &custom = _custom[index - _staticCount];
  1868. return (custom.id != Data::Stickers::CollectibleSetId)
  1869. && ((custom.id != Data::Stickers::MegagroupSetId)
  1870. || custom.canRemove);
  1871. }
  1872. return false;
  1873. }
  1874. QRect EmojiListWidget::buttonRect(int index) const {
  1875. return hasColorButton(index)
  1876. ? colorButtonRect(index)
  1877. : hasRemoveButton(index)
  1878. ? removeButtonRect(index)
  1879. : hasAddButton(index)
  1880. ? addButtonRect(index)
  1881. : unlockButtonRect(index);
  1882. }
  1883. QRect EmojiListWidget::buttonRect(
  1884. const SectionInfo &info,
  1885. const RightButton &button) const {
  1886. const auto buttonw = button.textWidth - st::emojiPanButton.width;
  1887. const auto buttonh = st::emojiPanButton.height;
  1888. const auto buttonx = emojiRight() - buttonw - st::emojiPanButtonRight;
  1889. const auto buttony = info.top + st::emojiPanButtonTop;
  1890. return QRect(buttonx, buttony, buttonw, buttonh);
  1891. }
  1892. auto EmojiListWidget::rightButton(int index) const -> const RightButton & {
  1893. Expects(index >= _staticCount
  1894. && index < _staticCount + _custom.size());
  1895. return hasAddButton(index)
  1896. ? _add
  1897. : _custom[index - _staticCount].canRemove
  1898. ? _restore
  1899. : _unlock;
  1900. }
  1901. int EmojiListWidget::emojiRight() const {
  1902. return emojiLeft() + (_columnCount * _singleSize.width());
  1903. }
  1904. int EmojiListWidget::emojiLeft() const {
  1905. return _rowsLeft;
  1906. }
  1907. QRect EmojiListWidget::emojiRect(int section, int index) const {
  1908. Expects(_columnCount > 0);
  1909. const auto info = sectionInfo(section);
  1910. const auto countTillItem = (index - (index % _columnCount));
  1911. const auto rowsToSkip = (countTillItem / _columnCount)
  1912. + ((countTillItem % _columnCount) ? 1 : 0);
  1913. const auto x = _rowsLeft + ((index % _columnCount) * _singleSize.width());
  1914. const auto y = info.rowsTop + rowsToSkip * _singleSize.height();
  1915. return QRect(x, y, _singleSize.width(), _singleSize.height());
  1916. }
  1917. void EmojiListWidget::colorChosen(EmojiChosen data) {
  1918. Expects(data.emoji != nullptr && data.emoji->hasVariants());
  1919. const auto emoji = data.emoji;
  1920. auto &settings = Core::App().settings();
  1921. if (const auto button = std::get_if<OverButton>(&_pickerSelected)) {
  1922. settings.saveAllEmojiVariants(emoji);
  1923. for (auto section = int(Section::People)
  1924. ; section < _staticCount
  1925. ; ++section) {
  1926. for (auto &emoji : _emoji[section]) {
  1927. emoji = settings.lookupEmojiVariant(emoji);
  1928. }
  1929. }
  1930. update();
  1931. } else {
  1932. settings.saveEmojiVariant(emoji);
  1933. const auto over = std::get_if<OverEmoji>(&_pickerSelected);
  1934. if (over
  1935. && over->section > int(Section::Recent)
  1936. && over->section < _staticCount
  1937. && over->index < _emoji[over->section].size()) {
  1938. _emoji[over->section][over->index] = emoji;
  1939. rtlupdate(emojiRect(over->section, over->index));
  1940. }
  1941. selectEmoji(data);
  1942. }
  1943. _picker->hideAnimated();
  1944. }
  1945. void EmojiListWidget::mouseMoveEvent(QMouseEvent *e) {
  1946. _lastMousePos = e->globalPos();
  1947. if (!_picker->isHidden()) {
  1948. if (_picker->rect().contains(_picker->mapFromGlobal(_lastMousePos))) {
  1949. return _picker->handleMouseMove(QCursor::pos());
  1950. } else {
  1951. _picker->clearSelection();
  1952. }
  1953. }
  1954. updateSelected();
  1955. }
  1956. void EmojiListWidget::leaveEventHook(QEvent *e) {
  1957. clearSelection();
  1958. }
  1959. void EmojiListWidget::leaveToChildEvent(QEvent *e, QWidget *child) {
  1960. clearSelection();
  1961. }
  1962. void EmojiListWidget::enterFromChildEvent(QEvent *e, QWidget *child) {
  1963. _lastMousePos = QCursor::pos();
  1964. updateSelected();
  1965. }
  1966. void EmojiListWidget::clearSelection() {
  1967. setPressed(v::null);
  1968. setSelected(v::null);
  1969. _lastMousePos = mapToGlobal(QPoint(-10, -10));
  1970. }
  1971. uint64 EmojiListWidget::currentSet(int yOffset) const {
  1972. return sectionSetId(sectionInfoByOffset(yOffset).section);
  1973. }
  1974. void EmojiListWidget::setAllowWithoutPremium(bool allow) {
  1975. if (_allowWithoutPremium == allow) {
  1976. return;
  1977. }
  1978. _allowWithoutPremium = allow;
  1979. refreshCustom();
  1980. resizeToWidth(width());
  1981. }
  1982. void EmojiListWidget::showMegagroupSet(ChannelData *megagroup) {
  1983. Expects(!megagroup || megagroup->isMegagroup());
  1984. if (_megagroupSet != megagroup) {
  1985. _megagroupSet = megagroup;
  1986. refreshCustom();
  1987. resizeToWidth(width());
  1988. }
  1989. }
  1990. QString EmojiListWidget::tooltipText() const {
  1991. if (_mode != Mode::Full) {
  1992. return {};
  1993. }
  1994. const auto &replacements = Ui::Emoji::internal::GetAllReplacements();
  1995. const auto over = std::get_if<OverEmoji>(&_selected);
  1996. if (const auto emoji = lookupOverEmoji(over)) {
  1997. const auto text = emoji->original()->text();
  1998. // find the replacement belonging to the emoji
  1999. const auto it = ranges::find_if(replacements, [&](const auto &one) {
  2000. return text == Ui::Emoji::QStringFromUTF16(one.emoji);
  2001. });
  2002. if (it != replacements.end()) {
  2003. return Ui::Emoji::QStringFromUTF16(it->replacement);
  2004. }
  2005. }
  2006. return {};
  2007. }
  2008. QPoint EmojiListWidget::tooltipPos() const {
  2009. return _lastMousePos;
  2010. }
  2011. bool EmojiListWidget::tooltipWindowActive() const {
  2012. return Ui::AppInFocus() && Ui::InFocusChain(window());
  2013. }
  2014. TabbedSelector::InnerFooter *EmojiListWidget::getFooter() const {
  2015. return _footer;
  2016. }
  2017. void EmojiListWidget::processHideFinished() {
  2018. if (!_picker->isHidden()) {
  2019. _picker->hideFast();
  2020. _pickerSelected = v::null;
  2021. }
  2022. unloadAllCustom();
  2023. clearSelection();
  2024. }
  2025. void EmojiListWidget::processPanelHideFinished() {
  2026. unloadAllCustom();
  2027. if (_localSetsManager->clearInstalledLocally()) {
  2028. refreshCustom();
  2029. }
  2030. }
  2031. void EmojiListWidget::refreshRecent() {
  2032. if (_mode != Mode::Full) {
  2033. return;
  2034. }
  2035. clearSelection();
  2036. fillRecent();
  2037. resizeToWidth(width());
  2038. update();
  2039. }
  2040. void EmojiListWidget::refreshCustom() {
  2041. if (_mode == Mode::RecentReactions || _mode == Mode::MessageEffects) {
  2042. return;
  2043. }
  2044. auto old = base::take(_custom);
  2045. const auto session = &this->session();
  2046. const auto premiumPossible = session->premiumPossible();
  2047. const auto onlyUnicodeEmoji = _onlyUnicodeEmoji || !premiumPossible;
  2048. const auto premiumMayBeBought = (!onlyUnicodeEmoji)
  2049. && premiumPossible
  2050. && !session->premium()
  2051. && !_allowWithoutPremium;
  2052. const auto owner = &session->data();
  2053. const auto &sets = owner->stickers().sets();
  2054. const auto push = [&](uint64 setId, bool installed) {
  2055. const auto megagroup = _megagroupSet
  2056. && (setId == Data::Stickers::MegagroupSetId);
  2057. const auto lookupId = megagroup
  2058. ? _megagroupSet->mgInfo->emojiSet.id
  2059. : setId;
  2060. if (!lookupId) {
  2061. return;
  2062. } else if (!megagroup
  2063. && !_custom.empty()
  2064. && _custom.front().id == Data::Stickers::MegagroupSetId
  2065. && _megagroupSet->mgInfo->emojiSet.id == setId) {
  2066. // Skip the set that is already added as a megagroup set.
  2067. return;
  2068. } else if (megagroup
  2069. && ranges::contains(_custom, lookupId, &CustomSet::id)) {
  2070. // Skip the set that is already added as a custom set.
  2071. return;
  2072. }
  2073. auto it = sets.find(lookupId);
  2074. if (it == sets.cend()
  2075. || it->second->stickers.isEmpty()
  2076. || (_mode == Mode::BackgroundEmoji && !it->second->textColor())
  2077. || (_mode == Mode::ChannelStatus
  2078. && !it->second->channelStatus())) {
  2079. return;
  2080. }
  2081. const auto canRemove = megagroup
  2082. ? (_megagroupSet->canEditEmoji() || installed)
  2083. : !!(it->second->flags & Data::StickersSetFlag::Installed);
  2084. const auto sortAsInstalled = canRemove
  2085. && (!(it->second->flags & Data::StickersSetFlag::Featured)
  2086. || !_localSetsManager->isInstalledLocally(lookupId));
  2087. if (!megagroup && sortAsInstalled != installed) {
  2088. return;
  2089. }
  2090. auto premium = false;
  2091. const auto &list = it->second->stickers;
  2092. const auto i = ranges::find(old, setId, &CustomSet::id);
  2093. if (i != end(old)) {
  2094. const auto valid = [&] {
  2095. const auto count = int(list.size());
  2096. if (i->list.size() != count) {
  2097. return false;
  2098. }
  2099. for (auto k = 0; k != count; ++k) {
  2100. if (!premium && !megagroup && list[k]->isPremiumEmoji()) {
  2101. premium = true;
  2102. }
  2103. if (i->list[k].document != list[k]) {
  2104. return false;
  2105. }
  2106. }
  2107. return true;
  2108. }();
  2109. if (premium && onlyUnicodeEmoji) {
  2110. return;
  2111. } else if (valid) {
  2112. i->thumbnailDocument = it->second->lookupThumbnailDocument();
  2113. const auto premiumRequired = premium && premiumMayBeBought;
  2114. if (i->canRemove != canRemove
  2115. || i->premiumRequired != premiumRequired) {
  2116. i->canRemove = canRemove;
  2117. i->premiumRequired = premiumRequired;
  2118. i->ripple.reset();
  2119. }
  2120. if (i->canRemove && !i->premiumRequired) {
  2121. i->expanded = false;
  2122. }
  2123. _custom.push_back(std::move(*i));
  2124. return;
  2125. }
  2126. }
  2127. auto set = std::vector<CustomOne>();
  2128. set.reserve(list.size());
  2129. for (const auto document : list) {
  2130. const auto id = EmojiStatusId{ document->id };
  2131. if (_restrictedCustomList.contains(id.documentId)) {
  2132. continue;
  2133. } else if (const auto sticker = document->sticker()) {
  2134. set.push_back({
  2135. .custom = resolveCustomEmoji(id, document, lookupId),
  2136. .document = document,
  2137. .emoji = Ui::Emoji::Find(sticker->alt),
  2138. });
  2139. if (!premium && !megagroup && document->isPremiumEmoji()) {
  2140. premium = true;
  2141. }
  2142. }
  2143. }
  2144. if (premium && onlyUnicodeEmoji) {
  2145. return;
  2146. }
  2147. _custom.push_back({
  2148. .id = setId,
  2149. .set = it->second.get(),
  2150. .thumbnailDocument = it->second->lookupThumbnailDocument(),
  2151. .title = it->second->title,
  2152. .list = std::move(set),
  2153. .canRemove = canRemove,
  2154. .premiumRequired = premium && premiumMayBeBought,
  2155. });
  2156. };
  2157. refreshEmojiStatusCollectibles();
  2158. refreshMegagroupStickers(push, GroupStickersPlace::Visible);
  2159. for (const auto setId : owner->stickers().emojiSetsOrder()) {
  2160. push(setId, true);
  2161. }
  2162. for (const auto setId : owner->stickers().featuredEmojiSetsOrder()) {
  2163. push(setId, false);
  2164. }
  2165. refreshMegagroupStickers(push, GroupStickersPlace::Hidden);
  2166. _footer->refreshIcons(
  2167. fillIcons(),
  2168. currentSet(getVisibleTop()),
  2169. nullptr,
  2170. ValidateIconAnimations::None);
  2171. update();
  2172. }
  2173. Fn<void()> EmojiListWidget::repaintCallback(
  2174. DocumentId documentId,
  2175. uint64 setId) {
  2176. return [=] {
  2177. repaintCustom(setId);
  2178. if (_recentCustomIds.contains(documentId)) {
  2179. repaintCustom(RecentEmojiSectionSetId());
  2180. }
  2181. if (_searchCustomIds.contains(documentId)) {
  2182. repaintCustom(SearchEmojiSectionSetId());
  2183. }
  2184. };
  2185. }
  2186. not_null<Ui::Text::CustomEmoji*> EmojiListWidget::resolveCustomEmoji(
  2187. EmojiStatusId id,
  2188. not_null<DocumentData*> document,
  2189. uint64 setId) {
  2190. const auto documentId = document->id;
  2191. const auto i = _customEmoji.find(id);
  2192. const auto recentOnly = (i != end(_customEmoji)) && i->second.recentOnly;
  2193. if (i != end(_customEmoji) && !recentOnly) {
  2194. return i->second.emoji.get();
  2195. }
  2196. auto instance = document->owner().customEmojiManager().create(
  2197. Data::EmojiStatusCustomId(id),
  2198. repaintCallback(documentId, setId),
  2199. Data::CustomEmojiManager::SizeTag::Large);
  2200. if (recentOnly) {
  2201. for (auto &recent : _recent) {
  2202. if (recent.custom && recent.custom == i->second.emoji.get()) {
  2203. recent.custom = instance.get();
  2204. }
  2205. }
  2206. i->second.emoji = std::move(instance);
  2207. i->second.recentOnly = false;
  2208. return i->second.emoji.get();
  2209. }
  2210. return _customEmoji.emplace(
  2211. id,
  2212. CustomEmojiInstance{ .emoji = std::move(instance) }
  2213. ).first->second.emoji.get();
  2214. }
  2215. Ui::Text::CustomEmoji *EmojiListWidget::resolveCustomRecent(
  2216. RecentEmojiId customId) {
  2217. const auto &data = customId.data;
  2218. if (const auto document = std::get_if<RecentEmojiDocument>(&data)) {
  2219. return resolveCustomRecent(document->id);
  2220. } else if (const auto emoji = std::get_if<EmojiPtr>(&data)) {
  2221. return nullptr;
  2222. }
  2223. Unexpected("Custom recent emoji id.");
  2224. }
  2225. not_null<Ui::Text::CustomEmoji*> EmojiListWidget::resolveCustomRecent(
  2226. DocumentId documentId) {
  2227. return resolveCustomRecent(EmojiStatusId{ documentId });
  2228. }
  2229. not_null<Ui::Text::CustomEmoji*> EmojiListWidget::resolveCustomRecent(
  2230. EmojiStatusId id) {
  2231. const auto i = id.collectible
  2232. ? end(_customRecent)
  2233. : _customRecent.find(id.documentId);
  2234. if (i != end(_customRecent)) {
  2235. return i->second.get();
  2236. }
  2237. const auto j = _customEmoji.find(id);
  2238. if (j != end(_customEmoji)) {
  2239. return j->second.emoji.get();
  2240. }
  2241. const auto documentId = id.collectible
  2242. ? id.collectible->documentId
  2243. : id.documentId;
  2244. auto repaint = repaintCallback(documentId, RecentEmojiSectionSetId());
  2245. if (_customRecentFactory && !id.collectible) {
  2246. return _customRecent.emplace(
  2247. id.documentId,
  2248. _customRecentFactory(id.documentId, std::move(repaint))
  2249. ).first->second.get();
  2250. }
  2251. auto custom = session().data().customEmojiManager().create(
  2252. Data::EmojiStatusCustomId(id),
  2253. std::move(repaint),
  2254. Data::CustomEmojiManager::SizeTag::Large);
  2255. return _customEmoji.emplace(
  2256. id,
  2257. CustomEmojiInstance{ .emoji = std::move(custom), .recentOnly = true }
  2258. ).first->second.emoji.get();
  2259. }
  2260. void EmojiListWidget::refreshEmojiStatusCollectibles() {
  2261. if (_mode != Mode::EmojiStatus || !_features.collectibleStatus) {
  2262. return;
  2263. }
  2264. const auto type = Data::EmojiStatuses::Type::Collectibles;
  2265. const auto &list = session().data().emojiStatuses().list(type);
  2266. const auto setId = Data::Stickers::CollectibleSetId;
  2267. auto set = std::vector<CustomOne>();
  2268. set.reserve(list.size());
  2269. for (const auto &status : list) {
  2270. const auto documentId = status.collectible
  2271. ? status.collectible->documentId
  2272. : status.documentId;
  2273. const auto document = session().data().document(documentId);
  2274. const auto sticker = document->sticker();
  2275. set.push_back({
  2276. .collectible = status.collectible,
  2277. .custom = resolveCustomEmoji(status, document, setId),
  2278. .document = document,
  2279. .emoji = sticker ? Ui::Emoji::Find(sticker->alt) : nullptr,
  2280. });
  2281. }
  2282. if (set.empty()) {
  2283. return;
  2284. }
  2285. const auto collectibles = session().data().stickers().collectibleSet();
  2286. _custom.push_back({
  2287. .id = setId,
  2288. .set = collectibles,
  2289. .thumbnailDocument = nullptr,
  2290. .title = collectibles->title,
  2291. .list = std::move(set),
  2292. .canRemove = false,
  2293. .premiumRequired = !session().premium(),
  2294. });
  2295. }
  2296. void EmojiListWidget::refreshMegagroupStickers(
  2297. Fn<void(uint64 setId, bool installed)> push,
  2298. GroupStickersPlace place) {
  2299. if (!_features.megagroupSet
  2300. || !_megagroupSet
  2301. || !_megagroupSet->mgInfo->emojiSet) {
  2302. return;
  2303. }
  2304. auto canEdit = _megagroupSet->canEditEmoji();
  2305. auto isShownHere = [place](bool hidden) {
  2306. return (hidden == (place == GroupStickersPlace::Hidden));
  2307. };
  2308. auto hidden = session().settings().isGroupEmojiSectionHidden(_megagroupSet->id);
  2309. auto removeHiddenForGroup = [this, &hidden] {
  2310. if (hidden) {
  2311. session().settings().removeGroupEmojiSectionHidden(_megagroupSet->id);
  2312. session().saveSettings();
  2313. hidden = false;
  2314. }
  2315. };
  2316. if (canEdit && hidden) {
  2317. removeHiddenForGroup();
  2318. }
  2319. const auto &set = _megagroupSet->mgInfo->emojiSet;
  2320. if (!set.id || !isShownHere(hidden)) {
  2321. return;
  2322. }
  2323. push(Data::Stickers::MegagroupSetId, !hidden);
  2324. if (!_custom.empty()
  2325. && _custom.back().id == Data::Stickers::MegagroupSetId) {
  2326. return;
  2327. } else if (_megagroupSetIdRequested == set.id) {
  2328. return;
  2329. }
  2330. _megagroupSetIdRequested = set.id;
  2331. _api.request(MTPmessages_GetStickerSet(
  2332. Data::InputStickerSet(set),
  2333. MTP_int(0) // hash
  2334. )).done([=](const MTPmessages_StickerSet &result) {
  2335. result.match([&](const MTPDmessages_stickerSet &data) {
  2336. if (const auto set = session().data().stickers().feedSetFull(data)) {
  2337. refreshCustom();
  2338. if (set->id == _megagroupSetIdRequested) {
  2339. _megagroupSetIdRequested = 0;
  2340. } else {
  2341. LOG(("API Error: Got different set."));
  2342. }
  2343. }
  2344. }, [](const MTPDmessages_stickerSetNotModified &) {
  2345. LOG(("API Error: Unexpected messages.stickerSetNotModified."));
  2346. });
  2347. }).send();
  2348. }
  2349. std::vector<StickerIcon> EmojiListWidget::fillIcons() {
  2350. auto result = std::vector<StickerIcon>();
  2351. result.reserve(2 + _custom.size());
  2352. result.emplace_back(RecentEmojiSectionSetId());
  2353. if (_mode != Mode::Full) {
  2354. } else if (_custom.empty()) {
  2355. using Section = Ui::Emoji::Section;
  2356. for (auto i = int(Section::People); i <= int(Section::Symbols); ++i) {
  2357. result.emplace_back(EmojiSectionSetId(Section(i)));
  2358. }
  2359. } else {
  2360. result.emplace_back(AllEmojiSectionSetId());
  2361. }
  2362. const auto esize = StickersListFooter::IconFrameSize();
  2363. for (const auto &custom : _custom) {
  2364. if (custom.id == Data::Stickers::MegagroupSetId) {
  2365. result.emplace_back(Data::Stickers::MegagroupSetId);
  2366. result.back().megagroup = _megagroupSet;
  2367. continue;
  2368. }
  2369. const auto set = custom.set;
  2370. result.emplace_back(set, custom.thumbnailDocument, esize, esize);
  2371. }
  2372. return result;
  2373. }
  2374. int EmojiListWidget::paintButtonGetWidth(
  2375. QPainter &p,
  2376. const SectionInfo &info,
  2377. bool selected,
  2378. QRect clip) const {
  2379. if (!hasButton(info.section)) {
  2380. return 0;
  2381. }
  2382. auto &ripple = (info.section >= _staticCount)
  2383. ? _custom[info.section - _staticCount].ripple
  2384. : _colorAllRipple;
  2385. const auto colorAll = hasColorButton(info.section);
  2386. if (colorAll || hasRemoveButton(info.section)) {
  2387. const auto rect = colorAll
  2388. ? colorButtonRect(info)
  2389. : removeButtonRect(info);
  2390. if (rect.isEmpty()) {
  2391. return 0;
  2392. } else if (rect.intersects(clip)) {
  2393. const auto &bst = colorAll ? st().colorAll : st().removeSet;
  2394. if (colorAll && _colorAllRippleForced) {
  2395. selected = true;
  2396. }
  2397. if (ripple) {
  2398. ripple->paint(
  2399. p,
  2400. rect.x() + bst.rippleAreaPosition.x(),
  2401. rect.y() + bst.rippleAreaPosition.y(),
  2402. width());
  2403. if (ripple->empty()) {
  2404. ripple.reset();
  2405. }
  2406. }
  2407. const auto &icon = selected ? bst.iconOver : bst.icon;
  2408. icon.paint(
  2409. p,
  2410. (rect.topLeft()
  2411. + QPoint(
  2412. rect.width() - icon.width(),
  2413. rect.height() - icon.height()) / 2),
  2414. width());
  2415. }
  2416. return emojiRight() - rect.x();
  2417. }
  2418. const auto canAdd = hasAddButton(info.section);
  2419. const auto &button = rightButton(info.section);
  2420. const auto rect = buttonRect(info, button);
  2421. p.drawImage(rect.topLeft(), selected ? button.backOver : button.back);
  2422. if (ripple) {
  2423. const auto color = QColor(0, 0, 0, 36);
  2424. ripple->paint(p, rect.x(), rect.y(), width(), &color);
  2425. if (ripple->empty()) {
  2426. ripple.reset();
  2427. }
  2428. }
  2429. p.setPen(!canAdd
  2430. ? st::premiumButtonFg
  2431. : selected
  2432. ? st::emojiPanButton.textFgOver
  2433. : st::emojiPanButton.textFg);
  2434. p.setFont(st::emojiPanButton.style.font);
  2435. p.drawText(
  2436. rect.x() - (st::emojiPanButton.width / 2),
  2437. (rect.y()
  2438. + st::emojiPanButton.textTop
  2439. + st::emojiPanButton.style.font->ascent),
  2440. button.text);
  2441. return emojiRight() - rect.x();
  2442. }
  2443. void EmojiListWidget::paintEmptySearchResults(Painter &p) {
  2444. Inner::paintEmptySearchResults(
  2445. p,
  2446. st::emojiEmpty,
  2447. tr::lng_emoji_nothing_found(tr::now));
  2448. }
  2449. bool EmojiListWidget::eventHook(QEvent *e) {
  2450. if (e->type() == QEvent::ParentChange) {
  2451. if (_picker->parentWidget() != parentWidget()) {
  2452. _picker->setParent(parentWidget());
  2453. }
  2454. _picker->raise();
  2455. }
  2456. return Inner::eventHook(e);
  2457. }
  2458. void EmojiListWidget::updateSelected() {
  2459. if (!v::is_null(_pressed) || !v::is_null(_pickerSelected)) {
  2460. if (!_previewShown) {
  2461. return;
  2462. }
  2463. }
  2464. auto newSelected = OverState{ v::null };
  2465. auto p = mapFromGlobal(_lastMousePos);
  2466. auto info = sectionInfoByOffset(p.y());
  2467. auto section = info.section;
  2468. if (p.y() >= info.top && p.y() < info.rowsTop) {
  2469. if (hasButton(section)
  2470. && myrtlrect(buttonRect(section)).contains(p.x(), p.y())) {
  2471. newSelected = OverButton{ section };
  2472. } else if (_features.openStickerSets
  2473. && section >= _staticCount
  2474. && _mode == Mode::Full) {
  2475. newSelected = OverSet{ section };
  2476. }
  2477. } else if (p.y() >= info.rowsTop && p.y() < info.rowsBottom) {
  2478. auto sx = (rtl() ? width() - p.x() : p.x()) - _rowsLeft;
  2479. if (sx >= 0 && sx < _columnCount * _singleSize.width()) {
  2480. const auto index = qFloor((p.y() - info.rowsTop) / _singleSize.height()) * _columnCount + qFloor(sx / _singleSize.width());
  2481. if (index < info.count) {
  2482. newSelected = OverEmoji{ .section = section, .index = index };
  2483. }
  2484. }
  2485. }
  2486. setSelected(newSelected);
  2487. }
  2488. void EmojiListWidget::setSelected(OverState newSelected) {
  2489. if (_selected == newSelected) {
  2490. return;
  2491. }
  2492. setCursor(!v::is_null(newSelected)
  2493. ? style::cur_pointer
  2494. : style::cur_default);
  2495. const auto updateSelected = [&] {
  2496. if (const auto sticker = std::get_if<OverEmoji>(&_selected)) {
  2497. rtlupdate(emojiRect(sticker->section, sticker->index));
  2498. } else if (const auto button = std::get_if<OverButton>(&_selected)) {
  2499. rtlupdate(buttonRect(button->section));
  2500. }
  2501. };
  2502. updateSelected();
  2503. _selected = newSelected;
  2504. updateSelected();
  2505. const auto hasSelection = !v::is_null(_selected);
  2506. if (hasSelection && Core::App().settings().suggestEmoji()) {
  2507. Ui::Tooltip::Show(1000, this);
  2508. }
  2509. setCursor(hasSelection ? style::cur_pointer : style::cur_default);
  2510. if (hasSelection && !_picker->isHidden()) {
  2511. if (_selected != _pickerSelected) {
  2512. _picker->hideAnimated();
  2513. } else {
  2514. _picker->showAnimated();
  2515. }
  2516. } else if (_previewShown && _pressed != _selected) {
  2517. if (const auto over = std::get_if<OverEmoji>(&_selected)) {
  2518. if (const auto custom = lookupCustomEmoji(over)) {
  2519. const auto document = custom.document;
  2520. _pressed = _selected;
  2521. _show->showMediaPreview(
  2522. document->stickerSetOrigin(),
  2523. document);
  2524. }
  2525. }
  2526. }
  2527. }
  2528. void EmojiListWidget::setPressed(OverState newPressed) {
  2529. if (auto button = std::get_if<OverButton>(&_pressed)) {
  2530. Assert(hasColorButton(button->section)
  2531. || (button->section >= _staticCount
  2532. && button->section < _staticCount + _custom.size()));
  2533. auto &ripple = (button->section >= _staticCount)
  2534. ? _custom[button->section - _staticCount].ripple
  2535. : _colorAllRipple;
  2536. if (ripple) {
  2537. ripple->lastStop();
  2538. }
  2539. }
  2540. _pressed = newPressed;
  2541. if (auto button = std::get_if<OverButton>(&_pressed)) {
  2542. Assert(hasColorButton(button->section)
  2543. || (button->section >= _staticCount
  2544. && button->section < _staticCount + _custom.size()));
  2545. auto &ripple = (button->section >= _staticCount)
  2546. ? _custom[button->section - _staticCount].ripple
  2547. : _colorAllRipple;
  2548. if (!ripple) {
  2549. ripple = createButtonRipple(button->section);
  2550. }
  2551. ripple->add(mapFromGlobal(QCursor::pos()) - buttonRippleTopLeft(button->section));
  2552. }
  2553. }
  2554. void EmojiListWidget::initButton(
  2555. RightButton &button,
  2556. const QString &text,
  2557. bool gradient) {
  2558. button.text = text;
  2559. button.textWidth = st::emojiPanButton.style.font->width(text);
  2560. const auto width = button.textWidth - st::emojiPanButton.width;
  2561. const auto height = st::emojiPanButton.height;
  2562. const auto factor = style::DevicePixelRatio();
  2563. auto prepare = [&](QColor bg, QBrush fg) {
  2564. auto image = QImage(
  2565. QSize(width, height) * factor,
  2566. QImage::Format_ARGB32_Premultiplied);
  2567. image.setDevicePixelRatio(factor);
  2568. image.fill(Qt::transparent);
  2569. auto p = QPainter(&image);
  2570. auto hq = PainterHighQualityEnabler(p);
  2571. p.setPen(Qt::NoPen);
  2572. p.setBrush(fg);
  2573. const auto radius = height / 2.;
  2574. p.drawRoundedRect(QRect(0, 0, width, height), radius, radius);
  2575. p.end();
  2576. return image;
  2577. };
  2578. button.back = prepare(Qt::transparent, [&]() -> QBrush {
  2579. if (gradient) {
  2580. auto result = QLinearGradient(QPointF(0, 0), QPointF(width, 0));
  2581. result.setStops(Ui::Premium::GiftGradientStops());
  2582. return result;
  2583. }
  2584. return st::emojiPanButton.textBg;
  2585. }());
  2586. button.backOver = gradient
  2587. ? button.back
  2588. : prepare(Qt::transparent, st::emojiPanButton.textBgOver);
  2589. button.rippleMask = prepare(Qt::black, Qt::white);
  2590. }
  2591. std::unique_ptr<Ui::RippleAnimation> EmojiListWidget::createButtonRipple(
  2592. int section) {
  2593. Expects(hasButton(section));
  2594. const auto colorAll = hasColorButton(section);
  2595. const auto remove = hasRemoveButton(section);
  2596. const auto &staticSt = colorAll ? st().colorAll : st().removeSet;
  2597. const auto &st = (colorAll || remove)
  2598. ? staticSt.ripple
  2599. : st::emojiPanButton.ripple;
  2600. auto mask = (colorAll || remove)
  2601. ? Ui::RippleAnimation::EllipseMask(QSize(
  2602. staticSt.rippleAreaSize,
  2603. staticSt.rippleAreaSize))
  2604. : rightButton(section).rippleMask;
  2605. return std::make_unique<Ui::RippleAnimation>(
  2606. st,
  2607. std::move(mask),
  2608. [this, section] { rtlupdate(buttonRect(section)); });
  2609. }
  2610. QPoint EmojiListWidget::buttonRippleTopLeft(int section) const {
  2611. Expects(hasButton(section));
  2612. return myrtlrect(buttonRect(section)).topLeft()
  2613. + (hasColorButton(section)
  2614. ? st().colorAll.rippleAreaPosition
  2615. : hasRemoveButton(section)
  2616. ? st().removeSet.rippleAreaPosition
  2617. : QPoint());
  2618. }
  2619. PowerSaving::Flag EmojiListWidget::powerSavingFlag() const {
  2620. const auto reactions = (_mode == Mode::FullReactions)
  2621. || (_mode == Mode::RecentReactions);
  2622. return reactions
  2623. ? PowerSaving::kEmojiReactions
  2624. : PowerSaving::kEmojiPanel;
  2625. }
  2626. void EmojiListWidget::refreshEmoji() {
  2627. refreshRecent();
  2628. refreshCustom();
  2629. }
  2630. void EmojiListWidget::showSet(uint64 setId) {
  2631. clearSelection();
  2632. if (_search && _searchMode) {
  2633. _search->cancel();
  2634. applyNextSearchQuery();
  2635. }
  2636. auto y = 0;
  2637. enumerateSections([&](const SectionInfo &info) {
  2638. if (setId == sectionSetId(info.section)) {
  2639. y = info.top;
  2640. return false;
  2641. }
  2642. return true;
  2643. });
  2644. scrollTo(y);
  2645. _lastMousePos = QCursor::pos();
  2646. update();
  2647. }
  2648. uint64 EmojiListWidget::sectionSetId(int section) const {
  2649. Expects(_searchMode
  2650. || section < _staticCount
  2651. || (section - _staticCount) < _custom.size());
  2652. return _searchMode
  2653. ? SearchEmojiSectionSetId()
  2654. : (section < _staticCount)
  2655. ? EmojiSectionSetId(static_cast<Section>(section))
  2656. : _custom[section - _staticCount].id;
  2657. }
  2658. tr::phrase<> EmojiCategoryTitle(int index) {
  2659. switch (index) {
  2660. case 1: return tr::lng_emoji_category1;
  2661. case 2: return tr::lng_emoji_category2;
  2662. case 3: return tr::lng_emoji_category3;
  2663. case 4: return tr::lng_emoji_category4;
  2664. case 5: return tr::lng_emoji_category5;
  2665. case 6: return tr::lng_emoji_category6;
  2666. case 7: return tr::lng_emoji_category7;
  2667. }
  2668. Unexpected("Index in CategoryTitle.");
  2669. }
  2670. } // namespace ChatHelpers