inline_results_widget.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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 "inline_bots/inline_results_widget.h"
  8. #include "data/data_user.h"
  9. #include "data/data_session.h"
  10. #include "inline_bots/inline_bot_result.h"
  11. #include "inline_bots/inline_results_inner.h"
  12. #include "main/main_session.h"
  13. #include "window/window_session_controller.h"
  14. #include "ui/widgets/shadow.h"
  15. #include "ui/widgets/scroll_area.h"
  16. #include "ui/image/image_prepare.h"
  17. #include "ui/cached_round_corners.h"
  18. #include "ui/ui_utility.h"
  19. #include "styles/style_chat_helpers.h"
  20. namespace InlineBots {
  21. namespace Layout {
  22. namespace {
  23. constexpr auto kInlineBotRequestDelay = 400;
  24. } // namespace
  25. Widget::Widget(
  26. QWidget *parent,
  27. not_null<Window::SessionController*> controller)
  28. : RpWidget(parent)
  29. , _controller(controller)
  30. , _api(&_controller->session().mtp())
  31. , _contentMaxHeight(st::emojiPanMaxHeight)
  32. , _contentHeight(_contentMaxHeight)
  33. , _scroll(this, st::inlineBotsScroll)
  34. , _innerRounding(Ui::PrepareCornerPixmaps(
  35. ImageRoundRadius::Small,
  36. st::emojiPanBg))
  37. , _inlineRequestTimer([=] { onInlineRequest(); }) {
  38. resize(QRect(0, 0, st::emojiPanWidth, _contentHeight).marginsAdded(innerPadding()).size());
  39. _width = width();
  40. _height = height();
  41. _scroll->resize(st::emojiPanWidth - st::roundRadiusSmall, _contentHeight);
  42. _scroll->move(verticalRect().topLeft());
  43. _inner = _scroll->setOwnedWidget(object_ptr<Inner>(this, controller));
  44. _inner->moveToLeft(0, 0, _scroll->width());
  45. _scroll->scrolls(
  46. ) | rpl::start_with_next([=] {
  47. onScroll();
  48. }, lifetime());
  49. _inner->inlineRowsCleared(
  50. ) | rpl::start_with_next([=] {
  51. hideAnimated();
  52. _inner->clearInlineRowsPanel();
  53. }, lifetime());
  54. style::PaletteChanged(
  55. ) | rpl::start_with_next([=] {
  56. _innerRounding = Ui::PrepareCornerPixmaps(
  57. ImageRoundRadius::Small,
  58. st::emojiPanBg);
  59. }, lifetime());
  60. macWindowDeactivateEvents(
  61. ) | rpl::filter([=] {
  62. return !isHidden();
  63. }) | rpl::start_with_next([=] {
  64. leaveEvent(nullptr);
  65. }, lifetime());
  66. // Inner widget has OpaquePaintEvent attribute so it doesn't repaint on scroll.
  67. // But we should force it to repaint so that GIFs will continue to animate without update() calls.
  68. // We do that by creating a transparent widget above our _inner.
  69. auto forceRepaintOnScroll = object_ptr<TWidget>(this);
  70. forceRepaintOnScroll->setGeometry(innerRect().x() + st::roundRadiusSmall, innerRect().y() + st::roundRadiusSmall, st::roundRadiusSmall, st::roundRadiusSmall);
  71. forceRepaintOnScroll->setAttribute(Qt::WA_TransparentForMouseEvents);
  72. forceRepaintOnScroll->show();
  73. setMouseTracking(true);
  74. setAttribute(Qt::WA_OpaquePaintEvent, false);
  75. }
  76. void Widget::moveBottom(int bottom) {
  77. _bottom = bottom;
  78. updateContentHeight();
  79. }
  80. void Widget::updateContentHeight() {
  81. auto addedHeight = innerPadding().top() + innerPadding().bottom();
  82. auto wantedContentHeight = qRound(st::emojiPanHeightRatio * _bottom) - addedHeight;
  83. auto contentHeight = std::clamp(
  84. wantedContentHeight,
  85. st::inlineResultsMinHeight,
  86. st::inlineResultsMaxHeight);
  87. accumulate_min(contentHeight, _bottom - addedHeight);
  88. accumulate_min(contentHeight, _contentMaxHeight);
  89. auto resultTop = _bottom - addedHeight - contentHeight;
  90. if (contentHeight == _contentHeight) {
  91. move(x(), resultTop);
  92. return;
  93. }
  94. auto was = _contentHeight;
  95. _contentHeight = contentHeight;
  96. resize(QRect(0, 0, innerRect().width(), _contentHeight).marginsAdded(innerPadding()).size());
  97. _height = height();
  98. moveToLeft(0, resultTop);
  99. if (was > _contentHeight) {
  100. _scroll->resize(_scroll->width(), _contentHeight);
  101. auto scrollTop = _scroll->scrollTop();
  102. _inner->setVisibleTopBottom(scrollTop, scrollTop + _contentHeight);
  103. } else {
  104. auto scrollTop = _scroll->scrollTop();
  105. _inner->setVisibleTopBottom(scrollTop, scrollTop + _contentHeight);
  106. _scroll->resize(_scroll->width(), _contentHeight);
  107. }
  108. update();
  109. }
  110. void Widget::paintEvent(QPaintEvent *e) {
  111. auto p = QPainter(this);
  112. auto opacityAnimating = _a_opacity.animating();
  113. auto showAnimating = _a_show.animating();
  114. if (_showAnimation && !showAnimating) {
  115. _showAnimation.reset();
  116. if (!opacityAnimating) {
  117. showChildren();
  118. }
  119. }
  120. if (showAnimating) {
  121. Assert(_showAnimation != nullptr);
  122. if (auto opacity = _a_opacity.value(_hiding ? 0. : 1.)) {
  123. _showAnimation->paintFrame(p, 0, 0, width(), _a_show.value(1.), opacity);
  124. }
  125. } else if (opacityAnimating) {
  126. p.setOpacity(_a_opacity.value(_hiding ? 0. : 1.));
  127. p.drawPixmap(0, 0, _cache);
  128. } else if (_hiding || isHidden()) {
  129. hideFinished();
  130. } else {
  131. if (!_cache.isNull()) _cache = QPixmap();
  132. if (!_inPanelGrab) Ui::Shadow::paint(p, innerRect(), width(), st::emojiPanAnimation.shadow);
  133. paintContent(p);
  134. }
  135. }
  136. void Widget::paintContent(QPainter &p) {
  137. auto inner = innerRect();
  138. const auto radius = st::roundRadiusSmall;
  139. const auto top = Ui::CornersPixmaps{
  140. .p = { _innerRounding.p[0], _innerRounding.p[1], QPixmap(), QPixmap() },
  141. };
  142. Ui::FillRoundRect(p, inner.x(), inner.y(), inner.width(), radius, st::emojiPanBg, top);
  143. const auto bottom = Ui::CornersPixmaps{
  144. .p = { QPixmap(), QPixmap(), _innerRounding.p[2], _innerRounding.p[3] },
  145. };
  146. Ui::FillRoundRect(p, inner.x(), inner.y() + inner.height() - radius, inner.width(), radius, st::emojiPanBg, bottom);
  147. auto horizontal = horizontalRect();
  148. auto sidesTop = horizontal.y();
  149. auto sidesHeight = horizontal.height();
  150. p.fillRect(myrtlrect(inner.x() + inner.width() - st::emojiScroll.width, sidesTop, st::emojiScroll.width, sidesHeight), st::emojiPanBg);
  151. p.fillRect(myrtlrect(inner.x(), sidesTop, st::roundRadiusSmall, sidesHeight), st::emojiPanBg);
  152. }
  153. void Widget::moveByBottom() {
  154. updateContentHeight();
  155. }
  156. void Widget::hideFast() {
  157. if (isHidden()) return;
  158. _hiding = false;
  159. _a_opacity.stop();
  160. hideFinished();
  161. }
  162. void Widget::opacityAnimationCallback() {
  163. update();
  164. if (!_a_opacity.animating()) {
  165. if (_hiding) {
  166. _hiding = false;
  167. hideFinished();
  168. } else if (!_a_show.animating()) {
  169. showChildren();
  170. }
  171. }
  172. }
  173. void Widget::prepareCache() {
  174. if (_a_opacity.animating()) return;
  175. auto showAnimation = base::take(_a_show);
  176. auto showAnimationData = base::take(_showAnimation);
  177. showChildren();
  178. _cache = Ui::GrabWidget(this);
  179. _showAnimation = base::take(showAnimationData);
  180. _a_show = base::take(showAnimation);
  181. if (_a_show.animating()) {
  182. hideChildren();
  183. }
  184. }
  185. void Widget::startOpacityAnimation(bool hiding) {
  186. _hiding = false;
  187. prepareCache();
  188. _hiding = hiding;
  189. hideChildren();
  190. _a_opacity.start([this] { opacityAnimationCallback(); }, _hiding ? 1. : 0., _hiding ? 0. : 1., st::emojiPanDuration);
  191. }
  192. void Widget::startShowAnimation() {
  193. if (!_a_show.animating()) {
  194. auto cache = base::take(_cache);
  195. auto opacityAnimation = base::take(_a_opacity);
  196. showChildren();
  197. auto image = grabForPanelAnimation();
  198. _a_opacity = base::take(opacityAnimation);
  199. _cache = base::take(cache);
  200. _showAnimation = std::make_unique<Ui::PanelAnimation>(st::emojiPanAnimation, Ui::PanelAnimation::Origin::BottomLeft);
  201. auto inner = rect().marginsRemoved(st::emojiPanMargins);
  202. _showAnimation->setFinalImage(
  203. std::move(image),
  204. QRect(
  205. inner.topLeft() * style::DevicePixelRatio(),
  206. inner.size() * style::DevicePixelRatio()));
  207. _showAnimation->setCornerMasks(Images::CornersMask(ImageRoundRadius::Small));
  208. _showAnimation->start();
  209. }
  210. hideChildren();
  211. _a_show.start([this] { update(); }, 0., 1., st::emojiPanShowDuration);
  212. }
  213. QImage Widget::grabForPanelAnimation() {
  214. Ui::SendPendingMoveResizeEvents(this);
  215. auto result = QImage(
  216. size() * style::DevicePixelRatio(),
  217. QImage::Format_ARGB32_Premultiplied);
  218. result.setDevicePixelRatio(style::DevicePixelRatio());
  219. result.fill(Qt::transparent);
  220. _inPanelGrab = true;
  221. render(&result);
  222. _inPanelGrab = false;
  223. return result;
  224. }
  225. void Widget::setResultSelectedCallback(Fn<void(ResultSelected)> callback) {
  226. _inner->setResultSelectedCallback(std::move(callback));
  227. }
  228. void Widget::setSendMenuDetails(Fn<SendMenu::Details()> &&callback) {
  229. _inner->setSendMenuDetails(std::move(callback));
  230. }
  231. void Widget::hideAnimated() {
  232. if (isHidden()) return;
  233. if (_hiding) return;
  234. startOpacityAnimation(true);
  235. }
  236. Widget::~Widget() = default;
  237. void Widget::hideFinished() {
  238. hide();
  239. _controller->disableGifPauseReason(
  240. Window::GifPauseReason::InlineResults);
  241. _inner->hideFinished();
  242. _a_show.stop();
  243. _showAnimation.reset();
  244. _cache = QPixmap();
  245. _hiding = false;
  246. _scroll->scrollToY(0);
  247. }
  248. void Widget::showAnimated() {
  249. showStarted();
  250. }
  251. void Widget::showStarted() {
  252. if (isHidden()) {
  253. recountContentMaxHeight();
  254. _inner->preloadImages();
  255. show();
  256. _controller->enableGifPauseReason(
  257. Window::GifPauseReason::InlineResults);
  258. startShowAnimation();
  259. } else if (_hiding) {
  260. startOpacityAnimation(false);
  261. }
  262. }
  263. void Widget::onScroll() {
  264. auto st = _scroll->scrollTop();
  265. if (st + _scroll->height() > _scroll->scrollTopMax()) {
  266. onInlineRequest();
  267. }
  268. _inner->setVisibleTopBottom(st, st + _scroll->height());
  269. }
  270. style::margins Widget::innerPadding() const {
  271. return st::emojiPanMargins;
  272. }
  273. QRect Widget::innerRect() const {
  274. return rect().marginsRemoved(innerPadding());
  275. }
  276. QRect Widget::horizontalRect() const {
  277. return innerRect().marginsRemoved(style::margins(0, st::roundRadiusSmall, 0, st::roundRadiusSmall));
  278. }
  279. QRect Widget::verticalRect() const {
  280. return innerRect().marginsRemoved(style::margins(st::roundRadiusSmall, 0, st::roundRadiusSmall, 0));
  281. }
  282. void Widget::clearInlineBot() {
  283. inlineBotChanged();
  284. }
  285. bool Widget::overlaps(const QRect &globalRect) const {
  286. if (isHidden() || !_cache.isNull()) return false;
  287. auto testRect = QRect(mapFromGlobal(globalRect.topLeft()), globalRect.size());
  288. auto inner = rect().marginsRemoved(st::emojiPanMargins);
  289. return inner.marginsRemoved(QMargins(st::roundRadiusSmall, 0, st::roundRadiusSmall, 0)).contains(testRect)
  290. || inner.marginsRemoved(QMargins(0, st::roundRadiusSmall, 0, st::roundRadiusSmall)).contains(testRect);
  291. }
  292. void Widget::inlineBotChanged() {
  293. if (!_inlineBot) {
  294. return;
  295. }
  296. if (!isHidden() && !_hiding) {
  297. hideAnimated();
  298. }
  299. _api.request(base::take(_inlineRequestId)).cancel();
  300. _inlineQuery = _inlineNextQuery = _inlineNextOffset = QString();
  301. _inlineBot = nullptr;
  302. _inlineCache.clear();
  303. _inner->inlineBotChanged();
  304. _inner->hideInlineRowsPanel();
  305. _requesting.fire(false);
  306. }
  307. void Widget::inlineResultsDone(const MTPmessages_BotResults &result) {
  308. _inlineRequestId = 0;
  309. _requesting.fire(false);
  310. auto it = _inlineCache.find(_inlineQuery);
  311. auto adding = (it != _inlineCache.cend());
  312. if (result.type() == mtpc_messages_botResults) {
  313. auto &d = result.c_messages_botResults();
  314. _controller->session().data().processUsers(d.vusers());
  315. auto &v = d.vresults().v;
  316. auto queryId = d.vquery_id().v;
  317. if (it == _inlineCache.cend()) {
  318. it = _inlineCache.emplace(
  319. _inlineQuery,
  320. std::make_unique<CacheEntry>()).first;
  321. }
  322. auto entry = it->second.get();
  323. entry->nextOffset = qs(d.vnext_offset().value_or_empty());
  324. if (const auto switchPm = d.vswitch_pm()) {
  325. entry->switchPmText = qs(switchPm->data().vtext());
  326. entry->switchPmStartToken = qs(switchPm->data().vstart_param());
  327. entry->switchPmUrl = QByteArray();
  328. } else if (const auto switchWebView = d.vswitch_webview()) {
  329. entry->switchPmText = qs(switchWebView->data().vtext());
  330. entry->switchPmStartToken = QString();
  331. entry->switchPmUrl = switchWebView->data().vurl().v;
  332. }
  333. if (const auto count = v.size()) {
  334. entry->results.reserve(entry->results.size() + count);
  335. }
  336. auto added = 0;
  337. for (const auto &res : v) {
  338. auto result = InlineBots::Result::Create(
  339. &_controller->session(),
  340. queryId,
  341. res);
  342. if (result) {
  343. ++added;
  344. entry->results.push_back(std::move(result));
  345. }
  346. }
  347. if (!added) {
  348. entry->nextOffset = QString();
  349. }
  350. } else if (adding) {
  351. it->second->nextOffset = QString();
  352. }
  353. if (!showInlineRows(!adding)) {
  354. it->second->nextOffset = QString();
  355. }
  356. onScroll();
  357. }
  358. void Widget::queryInlineBot(UserData *bot, PeerData *peer, QString query) {
  359. bool force = false;
  360. _inlineQueryPeer = peer;
  361. if (bot != _inlineBot) {
  362. inlineBotChanged();
  363. _inlineBot = bot;
  364. force = true;
  365. }
  366. if (_inlineQuery != query || force) {
  367. if (_inlineRequestId) {
  368. _api.request(_inlineRequestId).cancel();
  369. _inlineRequestId = 0;
  370. _requesting.fire(false);
  371. }
  372. if (_inlineCache.find(query) != _inlineCache.cend()) {
  373. _inlineRequestTimer.cancel();
  374. _inlineQuery = _inlineNextQuery = query;
  375. showInlineRows(true);
  376. } else {
  377. _inlineNextQuery = query;
  378. _inlineRequestTimer.callOnce(kInlineBotRequestDelay);
  379. }
  380. }
  381. }
  382. void Widget::onInlineRequest() {
  383. if (_inlineRequestId || !_inlineBot || !_inlineQueryPeer) return;
  384. _inlineQuery = _inlineNextQuery;
  385. QString nextOffset;
  386. auto it = _inlineCache.find(_inlineQuery);
  387. if (it != _inlineCache.cend()) {
  388. nextOffset = it->second->nextOffset;
  389. if (nextOffset.isEmpty()) {
  390. return;
  391. }
  392. }
  393. _requesting.fire(true);
  394. _inlineRequestId = _api.request(MTPmessages_GetInlineBotResults(
  395. MTP_flags(0),
  396. _inlineBot->inputUser,
  397. _inlineQueryPeer->input,
  398. MTPInputGeoPoint(),
  399. MTP_string(_inlineQuery),
  400. MTP_string(nextOffset)
  401. )).done([=](const MTPmessages_BotResults &result) {
  402. inlineResultsDone(result);
  403. }).fail([=] {
  404. // show error?
  405. _requesting.fire(false);
  406. _inlineRequestId = 0;
  407. }).handleAllErrors().send();
  408. }
  409. bool Widget::refreshInlineRows(int *added) {
  410. auto it = _inlineCache.find(_inlineQuery);
  411. const CacheEntry *entry = nullptr;
  412. if (it != _inlineCache.cend()) {
  413. if (!it->second->results.empty() || !it->second->switchPmText.isEmpty()) {
  414. entry = it->second.get();
  415. }
  416. _inlineNextOffset = it->second->nextOffset;
  417. }
  418. if (!entry) prepareCache();
  419. auto result = _inner->refreshInlineRows(_inlineQueryPeer, _inlineBot, entry, false);
  420. if (added) *added = result;
  421. return (entry != nullptr);
  422. }
  423. int Widget::showInlineRows(bool newResults) {
  424. auto added = 0;
  425. auto clear = !refreshInlineRows(&added);
  426. if (newResults) {
  427. _scroll->scrollToY(0);
  428. }
  429. auto hidden = isHidden();
  430. if (!hidden && !clear) {
  431. recountContentMaxHeight();
  432. }
  433. if (clear) {
  434. if (!hidden) {
  435. hideAnimated();
  436. } else if (!_hiding) {
  437. _cache = QPixmap(); // clear after refreshInlineRows()
  438. }
  439. } else {
  440. if (hidden || _hiding) {
  441. showAnimated();
  442. }
  443. }
  444. return added;
  445. }
  446. void Widget::recountContentMaxHeight() {
  447. _contentMaxHeight = _inner->countHeight();
  448. updateContentHeight();
  449. }
  450. } // namespace Layout
  451. } // namespace InlineBots