settings_folders.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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 "settings/settings_folders.h"
  8. #include "api/api_chat_filters.h" // ProcessFilterRemove.
  9. #include "apiwrap.h"
  10. #include "boxes/filters/edit_filter_box.h"
  11. #include "boxes/premium_limits_box.h"
  12. #include "boxes/premium_preview_box.h"
  13. #include "core/application.h"
  14. #include "core/ui_integration.h"
  15. #include "data/data_chat_filters.h"
  16. #include "data/data_folder.h"
  17. #include "data/data_peer.h"
  18. #include "data/data_peer_values.h" // Data::AmPremiumValue.
  19. #include "data/data_premium_limits.h"
  20. #include "data/data_session.h"
  21. #include "history/history.h"
  22. #include "lang/lang_keys.h"
  23. #include "lottie/lottie_icon.h"
  24. #include "main/main_session.h"
  25. #include "settings/settings_premium.h"
  26. #include "ui/boxes/confirm_box.h"
  27. #include "ui/empty_userpic.h"
  28. #include "ui/filter_icons.h"
  29. #include "ui/layers/generic_box.h"
  30. #include "ui/painter.h"
  31. #include "ui/rect.h"
  32. #include "ui/text/text_utilities.h"
  33. #include "ui/ui_utility.h"
  34. #include "ui/vertical_list.h"
  35. #include "ui/widgets/box_content_divider.h"
  36. #include "ui/widgets/buttons.h"
  37. #include "ui/widgets/checkbox.h"
  38. #include "ui/widgets/fields/input_field.h"
  39. #include "ui/widgets/labels.h"
  40. #include "ui/wrap/slide_wrap.h"
  41. #include "window/window_controller.h"
  42. #include "window/window_session_controller.h"
  43. #include "styles/style_settings.h"
  44. #include "styles/style_layers.h"
  45. #include "styles/style_boxes.h"
  46. #include "styles/style_chat_helpers.h"
  47. namespace Settings {
  48. namespace {
  49. using Flag = Data::ChatFilter::Flag;
  50. using Flags = Data::ChatFilter::Flags;
  51. class FilterRowButton final : public Ui::RippleButton {
  52. public:
  53. FilterRowButton(
  54. not_null<QWidget*> parent,
  55. not_null<Main::Session*> session,
  56. const Data::ChatFilter &filter,
  57. const QString &description = {});
  58. void setRemoved(bool removed);
  59. void updateData(
  60. const Data::ChatFilter &filter,
  61. bool ignoreCount = false);
  62. void updateCount(const Data::ChatFilter &filter);
  63. [[nodiscard]] rpl::producer<> removeRequests() const;
  64. [[nodiscard]] rpl::producer<> restoreRequests() const;
  65. [[nodiscard]] rpl::producer<> addRequests() const;
  66. void setColorIndexProgress(float64 progress);
  67. private:
  68. enum class State {
  69. Suggested,
  70. Removed,
  71. Normal,
  72. };
  73. void paintEvent(QPaintEvent *e) override;
  74. void setup(const Data::ChatFilter &filter, const QString &status);
  75. void setState(State state, bool force = false);
  76. void updateButtonsVisibility();
  77. const not_null<Main::Session*> _session;
  78. Ui::IconButton _remove;
  79. Ui::RoundButton _restore;
  80. Ui::RoundButton _add;
  81. Ui::Text::String _title;
  82. QString _status;
  83. Ui::FilterIcon _icon = Ui::FilterIcon();
  84. std::optional<uint8> _colorIndex;
  85. float64 _colorIndexProgress = 1.;
  86. State _state = State::Normal;
  87. };
  88. struct FilterRow {
  89. not_null<FilterRowButton*> button;
  90. Data::ChatFilter filter;
  91. bool removed = false;
  92. mtpRequestId removePeersRequestId = 0;
  93. std::vector<not_null<PeerData*>> suggestRemovePeers;
  94. std::vector<not_null<PeerData*>> removePeers;
  95. bool added = false;
  96. bool postponedCountUpdate = false;
  97. };
  98. [[nodiscard]] int CountFilterChats(
  99. not_null<Main::Session*> session,
  100. const Data::ChatFilter &filter) {
  101. auto result = 0;
  102. const auto addList = [&](not_null<Dialogs::MainList*> list) {
  103. for (const auto &entry : list->indexed()->all()) {
  104. if (const auto history = entry->history()) {
  105. if (filter.contains(history)) {
  106. ++result;
  107. }
  108. }
  109. }
  110. };
  111. addList(session->data().chatsList());
  112. const auto folderId = Data::Folder::kId;
  113. if (const auto folder = session->data().folderLoaded(folderId)) {
  114. addList(folder->chatsList());
  115. }
  116. return result;
  117. }
  118. [[nodiscard]] int ComputeCount(
  119. not_null<Main::Session*> session,
  120. const Data::ChatFilter &filter,
  121. bool check = false) {
  122. const auto &list = session->data().chatsFilters().list();
  123. const auto id = filter.id();
  124. const auto i = ranges::find(list, id, &Data::ChatFilter::id);
  125. if ((id && i != end(list))
  126. && (!check
  127. || (i->flags() == filter.flags()
  128. && i->always() == filter.always()
  129. && i->never() == filter.never()))) {
  130. const auto chats = session->data().chatsFilters().chatsList(id);
  131. return chats->indexed()->size();
  132. }
  133. return CountFilterChats(session, filter);
  134. }
  135. [[nodiscard]] QString ComputeCountString(
  136. not_null<Main::Session*> session,
  137. const Data::ChatFilter &filter,
  138. bool check = false) {
  139. const auto count = ComputeCount(session, filter, check);
  140. const auto result = count
  141. ? tr::lng_filters_chats_count(tr::now, lt_count_short, count)
  142. : tr::lng_filters_no_chats(tr::now);
  143. return filter.chatlist()
  144. ? (result
  145. + QString::fromUtf8(" \xE2\x80\xA2 ")
  146. + tr::lng_filters_shareable_status(tr::now))
  147. : result;
  148. }
  149. FilterRowButton::FilterRowButton(
  150. not_null<QWidget*> parent,
  151. not_null<Main::Session*> session,
  152. const Data::ChatFilter &filter,
  153. const QString &description)
  154. : RippleButton(parent, st::defaultRippleAnimation)
  155. , _session(session)
  156. , _remove(this, st::filtersRemove)
  157. , _restore(this, tr::lng_filters_restore(), st::stickersUndoRemove)
  158. , _add(this, tr::lng_filters_recommended_add(), st::stickersTrendingAdd)
  159. , _state(description.isEmpty() ? State::Normal : State::Suggested) {
  160. _restore.setTextTransform(Ui::RoundButton::TextTransform::NoTransform);
  161. _add.setTextTransform(Ui::RoundButton::TextTransform::NoTransform);
  162. setup(filter, description.isEmpty()
  163. ? ComputeCountString(session, filter)
  164. : description);
  165. }
  166. void FilterRowButton::setRemoved(bool removed) {
  167. setState(removed ? State::Removed : State::Normal);
  168. }
  169. void FilterRowButton::updateData(
  170. const Data::ChatFilter &filter,
  171. bool ignoreCount) {
  172. Expects(_session != nullptr);
  173. const auto title = filter.title();
  174. _title.setMarkedText(
  175. st::contactsNameStyle,
  176. title.text,
  177. kMarkupTextOptions,
  178. Core::TextContext({
  179. .session = _session,
  180. .repaint = [=] { update(); },
  181. .customEmojiLoopLimit = title.isStatic ? -1 : 0,
  182. }));
  183. _icon = Ui::ComputeFilterIcon(filter);
  184. _colorIndex = filter.colorIndex();
  185. if (!ignoreCount) {
  186. updateCount(filter);
  187. }
  188. }
  189. void FilterRowButton::updateCount(const Data::ChatFilter &filter) {
  190. _status = ComputeCountString(_session, filter, true);
  191. update();
  192. }
  193. void FilterRowButton::setState(State state, bool force) {
  194. if (!force && _state == state) {
  195. return;
  196. }
  197. _state = state;
  198. setPointerCursor(_state == State::Normal);
  199. setDisabled(_state != State::Normal);
  200. updateButtonsVisibility();
  201. update();
  202. }
  203. void FilterRowButton::setup(
  204. const Data::ChatFilter &filter,
  205. const QString &status) {
  206. resize(width(), st::defaultPeerListItem.height);
  207. _status = status;
  208. updateData(filter, true);
  209. setState(_state, true);
  210. sizeValue() | rpl::start_with_next([=](QSize size) {
  211. const auto right = st::contactsPadding.right()
  212. + st::contactsCheckPosition.x();
  213. const auto width = size.width();
  214. const auto height = size.height();
  215. _restore.moveToRight(right, (height - _restore.height()) / 2, width);
  216. _add.moveToRight(right, (height - _add.height()) / 2, width);
  217. const auto skipped = right - st::stickersRemoveSkip;
  218. _remove.moveToRight(skipped, (height - _remove.height()) / 2, width);
  219. }, lifetime());
  220. }
  221. void FilterRowButton::updateButtonsVisibility() {
  222. _remove.setVisible(_state == State::Normal);
  223. _restore.setVisible(_state == State::Removed);
  224. _add.setVisible(_state == State::Suggested);
  225. }
  226. rpl::producer<> FilterRowButton::removeRequests() const {
  227. return _remove.clicks() | rpl::to_empty;
  228. }
  229. rpl::producer<> FilterRowButton::restoreRequests() const {
  230. return _restore.clicks() | rpl::to_empty;
  231. }
  232. rpl::producer<> FilterRowButton::addRequests() const {
  233. return _add.clicks() | rpl::to_empty;
  234. }
  235. void FilterRowButton::setColorIndexProgress(float64 progress) {
  236. _colorIndexProgress = progress;
  237. if (_colorIndex) {
  238. update();
  239. }
  240. }
  241. void FilterRowButton::paintEvent(QPaintEvent *e) {
  242. auto p = Painter(this);
  243. const auto over = isOver() || isDown();
  244. if (_state == State::Normal) {
  245. if (over) {
  246. p.fillRect(e->rect(), st::windowBgOver);
  247. }
  248. RippleButton::paintRipple(p, 0, 0);
  249. if (_colorIndex) {
  250. p.setPen(Qt::NoPen);
  251. p.setBrush(Ui::EmptyUserpic::UserpicColor(*_colorIndex).color2);
  252. const auto w = height() / 3;
  253. const auto rect = QRect(
  254. _remove.x() - w - st::contactsCheckPosition.x(),
  255. (height() - w) / 2,
  256. w,
  257. w);
  258. auto hq = PainterHighQualityEnabler(p);
  259. p.drawEllipse(rect - Margins((1. - _colorIndexProgress) * w / 2));
  260. }
  261. } else if (_state == State::Removed) {
  262. p.setOpacity(st::stickersRowDisabledOpacity);
  263. }
  264. const auto left = (_state == State::Suggested)
  265. ? st::defaultSubsectionTitlePadding.left()
  266. : st::settingsButtonActive.padding.left();
  267. const auto buttonsLeft = std::min(
  268. _add.x(),
  269. std::min(_remove.x(), _restore.x()));
  270. const auto availableWidth = buttonsLeft - left;
  271. p.setPen(st::contactsNameFg);
  272. _title.drawLeftElided(
  273. p,
  274. left,
  275. st::contactsPadding.top() + st::contactsNameTop,
  276. availableWidth,
  277. width());
  278. p.setFont(st::contactsStatusFont);
  279. p.setPen(st::contactsStatusFg);
  280. p.drawTextLeft(
  281. left,
  282. st::contactsPadding.top() + st::contactsStatusTop,
  283. width(),
  284. _status);
  285. if (_state != State::Suggested) {
  286. const auto icon = Ui::LookupFilterIcon(_icon).normal;
  287. // For now.
  288. auto hq = PainterHighQualityEnabler(p);
  289. const auto iconWidth = icon->width() - style::ConvertScale(9);
  290. const auto scale = st::settingsIconAdd.width() / float64(iconWidth);
  291. p.translate(
  292. st::settingsButtonActive.iconLeft,
  293. (height() - icon->height() * scale) / 2);
  294. p.translate(-iconWidth / 2, -iconWidth / 2);
  295. p.scale(scale, scale);
  296. p.translate(iconWidth / 2, iconWidth / 2);
  297. icon->paint(
  298. p,
  299. 0,
  300. 0,
  301. width(),
  302. (over
  303. ? st::activeButtonBgOver
  304. : st::activeButtonBg)->c);
  305. }
  306. }
  307. [[nodiscard]] Fn<void()> SetupFoldersContent(
  308. not_null<Window::SessionController*> controller,
  309. not_null<Ui::VerticalLayout*> container,
  310. not_null<rpl::event_stream<bool>*> tagsButtonEnabled) {
  311. auto &lifetime = container->lifetime();
  312. const auto weak = Ui::MakeWeak(container);
  313. const auto session = &controller->session();
  314. const auto limit = [=] {
  315. return Data::PremiumLimits(session).dialogFiltersCurrent();
  316. };
  317. Ui::AddSkip(container, st::defaultVerticalListSkip);
  318. Ui::AddSubsectionTitle(container, tr::lng_filters_subtitle());
  319. struct State {
  320. std::vector<FilterRow> rows;
  321. rpl::variable<int> count;
  322. rpl::variable<int> suggested;
  323. Fn<void(const FilterRowButton*, Fn<void(Data::ChatFilter)>)> save;
  324. Ui::Animations::Simple tagsEnabledAnimation;
  325. };
  326. const auto state = lifetime.make_state<State>();
  327. const auto find = [=](not_null<FilterRowButton*> button) {
  328. const auto i = ranges::find(state->rows, button, &FilterRow::button);
  329. Assert(i != end(state->rows));
  330. return &*i;
  331. };
  332. const auto showLimitReached = [=] {
  333. const auto removed = ranges::count_if(
  334. state->rows,
  335. &FilterRow::removed);
  336. const auto count = int(state->rows.size() - removed);
  337. if (count < limit()) {
  338. return false;
  339. }
  340. controller->show(Box(FiltersLimitBox, session, count));
  341. return true;
  342. };
  343. const auto markForRemovalSure = [=](not_null<FilterRowButton*> button) {
  344. const auto row = find(button);
  345. auto suggestRemoving = Api::ExtractSuggestRemoving(row->filter);
  346. if (row->removed || row->removePeersRequestId > 0) {
  347. return;
  348. } else if (!suggestRemoving.empty()) {
  349. const auto chosen = crl::guard(button, [=](
  350. std::vector<not_null<PeerData*>> peers) {
  351. const auto row = find(button);
  352. row->removePeers = std::move(peers);
  353. row->removed = true;
  354. button->setRemoved(true);
  355. });
  356. Api::ProcessFilterRemove(
  357. controller,
  358. row->filter.title(),
  359. row->filter.iconEmoji(),
  360. std::move(suggestRemoving),
  361. row->suggestRemovePeers,
  362. chosen);
  363. } else {
  364. row->removePeers = {};
  365. row->removed = true;
  366. button->setRemoved(true);
  367. }
  368. };
  369. const auto markForRemoval = [=](not_null<FilterRowButton*> button) {
  370. const auto row = find(button);
  371. if (row->removed || row->removePeersRequestId > 0) {
  372. return;
  373. } else if (row->filter.hasMyLinks()) {
  374. controller->show(Ui::MakeConfirmBox({
  375. .text = { tr::lng_filters_delete_sure(tr::now) },
  376. .confirmed = crl::guard(button, [=](Fn<void()> close) {
  377. markForRemovalSure(button);
  378. close();
  379. }),
  380. .confirmText = tr::lng_box_delete(),
  381. .confirmStyle = &st::attentionBoxButton,
  382. }));
  383. } else {
  384. markForRemovalSure(button);
  385. }
  386. };
  387. const auto remove = [=](not_null<FilterRowButton*> button) {
  388. const auto row = find(button);
  389. if (row->removed || row->removePeersRequestId > 0) {
  390. return;
  391. } else if (row->filter.chatlist() && !row->removePeersRequestId) {
  392. row->removePeersRequestId = session->api().request(
  393. MTPchatlists_GetLeaveChatlistSuggestions(
  394. MTP_inputChatlistDialogFilter(
  395. MTP_int(row->filter.id())))
  396. ).done(crl::guard(button, [=](const MTPVector<MTPPeer> &result) {
  397. const auto row = find(button);
  398. row->removePeersRequestId = -1;
  399. row->suggestRemovePeers = ranges::views::all(
  400. result.v
  401. ) | ranges::views::transform([=](const MTPPeer &peer) {
  402. return session->data().peer(peerFromMTP(peer));
  403. }) | ranges::to_vector;
  404. markForRemoval(button);
  405. })).fail(crl::guard(button, [=] {
  406. const auto row = find(button);
  407. row->removePeersRequestId = -1;
  408. markForRemoval(button);
  409. })).send();
  410. } else {
  411. markForRemoval(button);
  412. }
  413. };
  414. const auto wrap = container->add(object_ptr<Ui::VerticalLayout>(
  415. container));
  416. const auto addFilter = [=](const Data::ChatFilter &filter) {
  417. const auto button = wrap->add(
  418. object_ptr<FilterRowButton>(wrap, session, filter));
  419. button->removeRequests(
  420. ) | rpl::start_with_next([=] {
  421. remove(button);
  422. }, button->lifetime());
  423. button->restoreRequests(
  424. ) | rpl::start_with_next([=] {
  425. if (showLimitReached()) {
  426. return;
  427. }
  428. button->setRemoved(false);
  429. find(button)->removed = false;
  430. }, button->lifetime());
  431. button->setClickedCallback([=] {
  432. const auto found = find(button);
  433. if (found->removed) {
  434. return;
  435. }
  436. const auto doneCallback = [=](const Data::ChatFilter &result) {
  437. find(button)->filter = result;
  438. button->updateData(result);
  439. };
  440. const auto saveAnd = [=](
  441. const Data::ChatFilter &data,
  442. Fn<void(Data::ChatFilter)> next) {
  443. doneCallback(data);
  444. state->save(button, next);
  445. };
  446. controller->window().show(Box(
  447. EditFilterBox,
  448. controller,
  449. found->filter,
  450. crl::guard(button, doneCallback),
  451. crl::guard(button, saveAnd)));
  452. });
  453. state->rows.push_back({ button, filter });
  454. state->count = state->rows.size();
  455. const auto filters = &controller->session().data().chatsFilters();
  456. const auto id = filter.id();
  457. if (ranges::contains(filters->list(), id, &Data::ChatFilter::id)) {
  458. filters->chatsList(id)->fullSize().changes(
  459. ) | rpl::start_with_next([=] {
  460. const auto found = find(button);
  461. if (found->postponedCountUpdate) {
  462. return;
  463. }
  464. found->postponedCountUpdate = true;
  465. Ui::PostponeCall(button, [=] {
  466. const auto &list = filters->list();
  467. const auto i = ranges::find(
  468. list,
  469. id,
  470. &Data::ChatFilter::id);
  471. if (i == end(list)) {
  472. return;
  473. }
  474. const auto found = find(button);
  475. const auto &now = found->filter;
  476. if ((i->flags() != now.flags())
  477. || (i->always() != now.always())
  478. || (i->never() != now.never())) {
  479. return;
  480. }
  481. button->updateCount(now);
  482. found->postponedCountUpdate = false;
  483. });
  484. }, button->lifetime());
  485. }
  486. wrap->resizeToWidth(container->width());
  487. return button;
  488. };
  489. const auto &list = session->data().chatsFilters().list();
  490. for (const auto &filter : list) {
  491. if (filter.id()) {
  492. addFilter(filter);
  493. }
  494. }
  495. session->data().chatsFilters().isChatlistChanged(
  496. ) | rpl::start_with_next([=](FilterId id) {
  497. const auto filters = &session->data().chatsFilters();
  498. const auto &list = filters->list();
  499. const auto i = ranges::find(list, id, &Data::ChatFilter::id);
  500. const auto j = ranges::find(state->rows, id, [](const auto &row) {
  501. return row.filter.id();
  502. });
  503. if (i == end(list) || j == end(state->rows)) {
  504. return;
  505. }
  506. j->filter = j->filter.withChatlist(i->chatlist(), i->hasMyLinks());
  507. j->button->updateCount(j->filter);
  508. }, container->lifetime());
  509. AddButtonWithIcon(
  510. container,
  511. tr::lng_filters_create(),
  512. st::settingsButtonActive,
  513. { &st::settingsIconAdd, IconType::Round, &st::windowBgActive }
  514. )->setClickedCallback([=] {
  515. if (showLimitReached()) {
  516. return;
  517. }
  518. const auto created = std::make_shared<FilterRowButton*>(nullptr);
  519. const auto doneCallback = [=](const Data::ChatFilter &result) {
  520. if (const auto button = *created) {
  521. find(button)->filter = result;
  522. button->updateData(result);
  523. } else {
  524. *created = addFilter(result);
  525. }
  526. };
  527. const auto saveAnd = [=](
  528. const Data::ChatFilter &data,
  529. Fn<void(Data::ChatFilter)> next) {
  530. doneCallback(data);
  531. state->save(*created, next);
  532. };
  533. controller->window().show(Box(
  534. EditFilterBox,
  535. controller,
  536. Data::ChatFilter(),
  537. crl::guard(container, doneCallback),
  538. crl::guard(container, saveAnd)));
  539. });
  540. Ui::AddSkip(container);
  541. const auto nonEmptyAbout = container->add(
  542. object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  543. container,
  544. object_ptr<Ui::VerticalLayout>(container))
  545. )->setDuration(0);
  546. const auto aboutRows = nonEmptyAbout->entity();
  547. Ui::AddDivider(aboutRows);
  548. Ui::AddSkip(aboutRows);
  549. Ui::AddSubsectionTitle(aboutRows, tr::lng_filters_recommended());
  550. const auto setTagsProgress = [=](float64 value) {
  551. for (const auto &row : state->rows) {
  552. row.button->setColorIndexProgress(value);
  553. }
  554. };
  555. tagsButtonEnabled->events() | rpl::distinct_until_changed(
  556. ) | rpl::start_with_next([=](bool value) {
  557. state->tagsEnabledAnimation.stop();
  558. state->tagsEnabledAnimation.start(
  559. setTagsProgress,
  560. value ? .0 : 1.,
  561. value ? 1. : .0,
  562. st::universalDuration);
  563. }, lifetime);
  564. setTagsProgress(session->data().chatsFilters().tagsEnabled());
  565. rpl::single(rpl::empty) | rpl::then(
  566. session->data().chatsFilters().suggestedUpdated()
  567. ) | rpl::map([=] {
  568. return session->data().chatsFilters().suggestedFilters();
  569. }) | rpl::filter([=](const std::vector<Data::SuggestedFilter> &list) {
  570. return !list.empty();
  571. }) | rpl::take(
  572. 1
  573. ) | rpl::start_with_next([=](
  574. const std::vector<Data::SuggestedFilter> &suggestions) {
  575. for (const auto &suggestion : suggestions) {
  576. const auto &filter = suggestion.filter;
  577. if (ranges::contains(state->rows, filter, &FilterRow::filter)) {
  578. continue;
  579. }
  580. state->suggested = state->suggested.current() + 1;
  581. const auto button = aboutRows->add(object_ptr<FilterRowButton>(
  582. aboutRows,
  583. session,
  584. filter,
  585. suggestion.description));
  586. button->addRequests(
  587. ) | rpl::start_with_next([=] {
  588. if (showLimitReached()) {
  589. return;
  590. }
  591. addFilter(filter);
  592. state->suggested = state->suggested.current() - 1;
  593. delete button;
  594. }, button->lifetime());
  595. }
  596. aboutRows->resizeToWidth(container->width());
  597. Ui::AddSkip(aboutRows, st::defaultVerticalListSkip);
  598. }, aboutRows->lifetime());
  599. auto showSuggestions = rpl::combine(
  600. state->suggested.value(),
  601. state->count.value(),
  602. Data::AmPremiumValue(session)
  603. ) | rpl::map([limit](int suggested, int count, bool) {
  604. return suggested > 0 && count < limit();
  605. });
  606. nonEmptyAbout->toggleOn(std::move(showSuggestions));
  607. const auto prepareGoodIdsForNewFilters = [=] {
  608. const auto &list = session->data().chatsFilters().list();
  609. auto localId = 1;
  610. const auto chooseNextId = [&] {
  611. ++localId;
  612. while (ranges::contains(list, localId, &Data::ChatFilter::id)) {
  613. ++localId;
  614. }
  615. return localId;
  616. };
  617. auto result = base::flat_map<not_null<FilterRowButton*>, FilterId>();
  618. for (auto &row : state->rows) {
  619. const auto id = row.filter.id();
  620. if (row.removed) {
  621. continue;
  622. } else if (!id
  623. || !ranges::contains(list, id, &Data::ChatFilter::id)) {
  624. result.emplace(row.button, chooseNextId());
  625. }
  626. }
  627. return result;
  628. };
  629. state->save = [=](
  630. const FilterRowButton *single,
  631. Fn<void(Data::ChatFilter)> next) {
  632. auto ids = prepareGoodIdsForNewFilters();
  633. auto updated = Data::ChatFilter();
  634. auto order = std::vector<FilterId>();
  635. auto updates = std::vector<MTPUpdate>();
  636. auto addRequests = std::vector<MTPmessages_UpdateDialogFilter>();
  637. auto removeRequests = std::vector<MTPmessages_UpdateDialogFilter>();
  638. auto removeChatlistRequests = std::vector<MTPchatlists_LeaveChatlist>();
  639. auto &realFilters = session->data().chatsFilters();
  640. const auto &list = realFilters.list();
  641. order.reserve(state->rows.size());
  642. for (auto &row : state->rows) {
  643. if (row.button.get() == single) {
  644. updated = row.filter;
  645. }
  646. const auto id = row.filter.id();
  647. const auto removed = row.removed;
  648. const auto i = ranges::find(list, id, &Data::ChatFilter::id);
  649. if (removed && (i == end(list) || id == FilterId(0))) {
  650. continue;
  651. } else if (!removed && i != end(list) && *i == row.filter) {
  652. order.push_back(id);
  653. continue;
  654. }
  655. const auto newId = ids.take(row.button).value_or(id);
  656. if (newId != id) {
  657. row.filter = row.filter.withId(newId);
  658. row.button->updateData(row.filter);
  659. if (row.button.get() == single) {
  660. updated = row.filter;
  661. }
  662. }
  663. const auto tl = removed
  664. ? MTPDialogFilter()
  665. : row.filter.tl(newId);
  666. const auto removeChatlistWithChats = removed
  667. && row.filter.chatlist()
  668. && !row.removePeers.empty();
  669. if (removeChatlistWithChats) {
  670. auto inputs = ranges::views::all(
  671. row.removePeers
  672. ) | ranges::views::transform([](not_null<PeerData*> peer) {
  673. return MTPInputPeer(peer->input);
  674. }) | ranges::to<QVector<MTPInputPeer>>();
  675. removeChatlistRequests.push_back(
  676. MTPchatlists_LeaveChatlist(
  677. MTP_inputChatlistDialogFilter(MTP_int(newId)),
  678. MTP_vector<MTPInputPeer>(std::move(inputs))));
  679. } else {
  680. const auto request = MTPmessages_UpdateDialogFilter(
  681. MTP_flags(removed
  682. ? MTPmessages_UpdateDialogFilter::Flag(0)
  683. : MTPmessages_UpdateDialogFilter::Flag::f_filter),
  684. MTP_int(newId),
  685. tl);
  686. if (removed) {
  687. removeRequests.push_back(request);
  688. } else {
  689. addRequests.push_back(request);
  690. order.push_back(newId);
  691. }
  692. }
  693. updates.push_back(MTP_updateDialogFilter(
  694. MTP_flags(removed
  695. ? MTPDupdateDialogFilter::Flag(0)
  696. : MTPDupdateDialogFilter::Flag::f_filter),
  697. MTP_int(newId),
  698. tl));
  699. }
  700. if (!ranges::contains(order, FilterId(0))) {
  701. auto position = 0;
  702. for (const auto &filter : list) {
  703. const auto id = filter.id();
  704. if (!id) {
  705. break;
  706. } else if (const auto i = ranges::find(order, id)
  707. ; i != order.end()) {
  708. position = int(i - order.begin()) + 1;
  709. }
  710. }
  711. order.insert(order.begin() + position, FilterId(0));
  712. }
  713. if (next) {
  714. // We're not closing the layer yet, so delete removed rows.
  715. for (auto i = state->rows.begin(); i != state->rows.end();) {
  716. if (i->removed) {
  717. const auto button = i->button;
  718. i = state->rows.erase(i);
  719. delete button;
  720. } else {
  721. ++i;
  722. }
  723. }
  724. }
  725. crl::on_main(session, [
  726. session,
  727. next,
  728. updated,
  729. order = std::move(order),
  730. updates = std::move(updates),
  731. addRequests = std::move(addRequests),
  732. removeRequests = std::move(removeRequests),
  733. removeChatlistRequests = std::move(removeChatlistRequests)
  734. ] {
  735. const auto api = &session->api();
  736. const auto filters = &session->data().chatsFilters();
  737. const auto ids = std::make_shared<
  738. base::flat_set<mtpRequestId>
  739. >();
  740. const auto checkFinished = [=] {
  741. if (ids->empty() && next) {
  742. Assert(updated.id() != 0);
  743. next(updated);
  744. }
  745. };
  746. for (const auto &update : updates) {
  747. filters->apply(update);
  748. }
  749. auto previousId = mtpRequestId(0);
  750. const auto sendRequests = [&](const auto &requests) {
  751. for (auto &request : requests) {
  752. previousId = api->request(
  753. std::move(request)
  754. ).done([=](const auto &result, mtpRequestId id) {
  755. if constexpr (std::is_same_v<
  756. std::decay_t<decltype(result)>,
  757. MTPUpdates>) {
  758. session->api().applyUpdates(result);
  759. }
  760. ids->remove(id);
  761. checkFinished();
  762. }).afterRequest(previousId).send();
  763. ids->emplace(previousId);
  764. }
  765. };
  766. sendRequests(removeRequests);
  767. sendRequests(removeChatlistRequests);
  768. sendRequests(addRequests);
  769. if (!order.empty() && !addRequests.empty()) {
  770. filters->saveOrder(order, previousId);
  771. }
  772. checkFinished();
  773. });
  774. };
  775. return [copy = state->save] {
  776. copy(nullptr, nullptr);
  777. };
  778. }
  779. void SetupTopContent(
  780. not_null<Ui::VerticalLayout*> parent,
  781. rpl::producer<> showFinished) {
  782. const auto divider = Ui::CreateChild<Ui::BoxContentDivider>(parent.get());
  783. const auto verticalLayout = parent->add(
  784. object_ptr<Ui::VerticalLayout>(parent.get()));
  785. auto icon = CreateLottieIcon(
  786. verticalLayout,
  787. {
  788. .name = u"filters"_q,
  789. .sizeOverride = {
  790. st::settingsFilterIconSize,
  791. st::settingsFilterIconSize,
  792. },
  793. },
  794. st::settingsFilterIconPadding);
  795. std::move(
  796. showFinished
  797. ) | rpl::start_with_next([animate = std::move(icon.animate)] {
  798. animate(anim::repeat::once);
  799. }, verticalLayout->lifetime());
  800. verticalLayout->add(std::move(icon.widget));
  801. verticalLayout->add(
  802. object_ptr<Ui::CenterWrap<>>(
  803. verticalLayout,
  804. object_ptr<Ui::FlatLabel>(
  805. verticalLayout,
  806. tr::lng_filters_about(),
  807. st::settingsFilterDividerLabel)),
  808. st::settingsFilterDividerLabelPadding);
  809. verticalLayout->geometryValue(
  810. ) | rpl::start_with_next([=](const QRect &r) {
  811. divider->setGeometry(r);
  812. }, divider->lifetime());
  813. }
  814. void SetupTagContent(
  815. not_null<Window::SessionController*> controller,
  816. not_null<Ui::VerticalLayout*> content,
  817. not_null<rpl::event_stream<bool>*> tagsButtonEnabled) {
  818. Ui::AddDivider(content);
  819. Ui::AddSkip(content);
  820. const auto session = &controller->session();
  821. struct State final {
  822. rpl::event_stream<bool> tagsTurnOff;
  823. base::Timer requestTimer;
  824. Fn<void()> sendCallback;
  825. };
  826. auto premium = Data::AmPremiumValue(session);
  827. const auto tagsButton = content->add(
  828. object_ptr<Ui::SettingsButton>(
  829. content,
  830. tr::lng_filters_enable_tags(),
  831. st::settingsButtonNoIconLocked));
  832. const auto state = tagsButton->lifetime().make_state<State>();
  833. tagsButton->toggleOn(rpl::merge(
  834. rpl::combine(
  835. session->data().chatsFilters().tagsEnabledValue(),
  836. rpl::duplicate(premium),
  837. rpl::mappers::_1 && rpl::mappers::_2),
  838. state->tagsTurnOff.events()));
  839. rpl::duplicate(premium) | rpl::start_with_next([=](bool value) {
  840. tagsButton->setToggleLocked(!value);
  841. }, tagsButton->lifetime());
  842. const auto send = [=, weak = Ui::MakeWeak(tagsButton)](bool checked) {
  843. session->data().chatsFilters().requestToggleTags(checked, [=] {
  844. if (const auto strong = weak.data()) {
  845. state->tagsTurnOff.fire(!checked);
  846. }
  847. });
  848. };
  849. tagsButton->toggledValue(
  850. ) | rpl::filter([=](bool checked) {
  851. const auto premium = session->premium();
  852. if (checked && !premium) {
  853. ShowPremiumPreviewToBuy(controller, PremiumFeature::FilterTags);
  854. state->tagsTurnOff.fire(false);
  855. }
  856. if (!premium) {
  857. tagsButtonEnabled->fire(false);
  858. } else {
  859. tagsButtonEnabled->fire_copy(checked);
  860. }
  861. const auto proceed = premium
  862. && (checked != session->data().chatsFilters().tagsEnabled());
  863. if (!proceed) {
  864. state->requestTimer.cancel();
  865. }
  866. return proceed;
  867. }) | rpl::start_with_next([=](bool v) {
  868. state->sendCallback = [=] { send(v); };
  869. state->requestTimer.cancel();
  870. state->requestTimer.setCallback([=] { send(v); });
  871. state->requestTimer.callOnce(500);
  872. }, tagsButton->lifetime());
  873. tagsButton->lifetime().add([=] {
  874. if (state->requestTimer.isActive()) {
  875. if (state->sendCallback) {
  876. state->sendCallback();
  877. }
  878. }
  879. });
  880. Ui::AddSkip(content);
  881. const auto about = Ui::AddDividerText(
  882. content,
  883. rpl::conditional(
  884. rpl::duplicate(premium),
  885. tr::lng_filters_enable_tags_about(Ui::Text::RichLangValue),
  886. tr::lng_filters_enable_tags_about_premium(
  887. lt_link,
  888. tr::lng_effect_premium_link() | rpl::map([](QString t) {
  889. return Ui::Text::Link(std::move(t), u"internal:"_q);
  890. }),
  891. Ui::Text::RichLangValue)));
  892. about->setClickHandlerFilter([=](const auto &...) {
  893. Settings::ShowPremium(controller, u"folder_tags"_q);
  894. return true;
  895. });
  896. }
  897. void SetupView(
  898. not_null<Window::SessionController*> controller,
  899. not_null<Ui::VerticalLayout*> content,
  900. bool dividerNeeded) {
  901. const auto wrap = content->add(
  902. object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  903. content,
  904. object_ptr<Ui::VerticalLayout>(content)));
  905. wrap->toggleOn(controller->enoughSpaceForFiltersValue());
  906. content = wrap->entity();
  907. if (dividerNeeded) {
  908. Ui::AddDivider(content);
  909. }
  910. Ui::AddSkip(content);
  911. Ui::AddSubsectionTitle(content, tr::lng_filters_view_subtitle());
  912. const auto group = std::make_shared<Ui::RadioenumGroup<bool>>(
  913. Core::App().settings().chatFiltersHorizontal());
  914. const auto addSend = [&](bool value, const QString &text) {
  915. content->add(
  916. object_ptr<Ui::Radioenum<bool>>(
  917. content,
  918. group,
  919. value,
  920. text,
  921. st::settingsSendType),
  922. st::settingsSendTypePadding);
  923. };
  924. addSend(false, tr::lng_filters_vertical(tr::now));
  925. addSend(true, tr::lng_filters_horizontal(tr::now));
  926. group->setChangedCallback([=](bool value) {
  927. Core::App().settings().setChatFiltersHorizontal(value);
  928. Core::App().saveSettingsDelayed();
  929. });
  930. Ui::AddSkip(content);
  931. Ui::AddSkip(content);
  932. }
  933. } // namespace
  934. Folders::Folders(
  935. QWidget *parent,
  936. not_null<Window::SessionController*> controller)
  937. : Section(parent) {
  938. setupContent(controller);
  939. }
  940. Folders::~Folders() {
  941. if (!Core::Quitting()) {
  942. _save();
  943. }
  944. }
  945. rpl::producer<QString> Folders::title() {
  946. return tr::lng_filters_title();
  947. }
  948. void Folders::setupContent(not_null<Window::SessionController*> controller) {
  949. controller->session().data().chatsFilters().requestSuggested();
  950. const auto content = Ui::CreateChild<Ui::VerticalLayout>(this);
  951. const auto tagsButtonEnabled
  952. = content->lifetime().make_state<rpl::event_stream<bool>>();
  953. SetupTopContent(content, _showFinished.events());
  954. _save = SetupFoldersContent(controller, content, tagsButtonEnabled);
  955. auto dividerNeeded = true;
  956. if (controller->session().premiumPossible()) {
  957. SetupTagContent(controller, content, tagsButtonEnabled);
  958. dividerNeeded = false;
  959. }
  960. SetupView(controller, content, dividerNeeded);
  961. Ui::ResizeFitChild(this, content);
  962. }
  963. void Folders::showFinished() {
  964. _showFinished.fire({});
  965. }
  966. } // namespace Settings