File: peer_list_controllers.cpp

package info (click to toggle)
telegram-desktop 4.6.5%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 53,300 kB
  • sloc: cpp: 605,857; python: 3,978; ansic: 1,636; sh: 965; makefile: 841; objc: 652; javascript: 187; xml: 165
file content (756 lines) | stat: -rw-r--r-- 21,269 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.

For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "boxes/peer_list_controllers.h"

#include "api/api_chat_participants.h"
#include "base/random.h"
#include "ui/boxes/confirm_box.h"
#include "ui/widgets/checkbox.h"
#include "ui/painter.h"
#include "ui/ui_utility.h"
#include "main/main_session.h"
#include "data/data_session.h"
#include "data/data_channel.h"
#include "data/data_chat.h"
#include "data/data_user.h"
#include "data/data_forum.h"
#include "data/data_forum_topic.h"
#include "data/data_folder.h"
#include "data/data_histories.h"
#include "data/data_changes.h"
#include "dialogs/ui/dialogs_layout.h"
#include "apiwrap.h"
#include "mainwidget.h"
#include "mainwindow.h"
#include "lang/lang_keys.h"
#include "history/history.h"
#include "history/history_item.h"
#include "dialogs/dialogs_main_list.h"
#include "window/window_session_controller.h" // showAddContact()
#include "base/unixtime.h"
#include "styles/style_boxes.h"
#include "styles/style_profile.h"
#include "styles/style_dialogs.h"

namespace {

constexpr auto kSortByOnlineThrottle = 3 * crl::time(1000);
constexpr auto kSearchPerPage = 50;

} // namespace

object_ptr<Ui::BoxContent> PrepareContactsBox(
		not_null<Window::SessionController*> sessionController) {
	using Mode = ContactsBoxController::SortMode;
	auto controller = std::make_unique<ContactsBoxController>(
		&sessionController->session());
	const auto raw = controller.get();
	auto init = [=](not_null<PeerListBox*> box) {
		struct State {
			QPointer<Ui::IconButton> toggleSort;
			Mode mode = ContactsBoxController::SortMode::Online;
		};
		const auto state = box->lifetime().make_state<State>();
		box->addButton(tr::lng_close(), [=] { box->closeBox(); });
		box->addLeftButton(
			tr::lng_profile_add_contact(),
			[=] { sessionController->showAddContact(); });
		state->toggleSort = box->addTopButton(st::contactsSortButton, [=] {
			const auto online = (state->mode == Mode::Online);
			state->mode = online ? Mode::Alphabet : Mode::Online;
			raw->setSortMode(state->mode);
			state->toggleSort->setIconOverride(
				online ? &st::contactsSortOnlineIcon : nullptr,
				online ? &st::contactsSortOnlineIconOver : nullptr);
		});
		raw->setSortMode(Mode::Online);
	};
	return Box<PeerListBox>(std::move(controller), std::move(init));
}

void PeerListRowWithLink::setActionLink(const QString &action) {
	_action = action;
	refreshActionLink();
}

void PeerListRowWithLink::refreshActionLink() {
	if (!isInitialized()) return;
	_actionWidth = _action.isEmpty() ? 0 : st::normalFont->width(_action);
}

void PeerListRowWithLink::lazyInitialize(const style::PeerListItem &st) {
	PeerListRow::lazyInitialize(st);
	refreshActionLink();
}

QSize PeerListRowWithLink::rightActionSize() const {
	return QSize(_actionWidth, st::normalFont->height);
}

QMargins PeerListRowWithLink::rightActionMargins() const {
	return QMargins(
		st::contactsCheckPosition.x(),
		(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom() - st::normalFont->height) / 2,
		st::defaultPeerListItem.photoPosition.x() + st::contactsCheckPosition.x(),
		0);
}

void PeerListRowWithLink::rightActionPaint(
		Painter &p,
		int x,
		int y,
		int outerWidth,
		bool selected,
		bool actionSelected) {
	p.setFont(actionSelected ? st::linkOverFont : st::linkFont);
	p.setPen(actionSelected ? st::defaultLinkButton.overColor : st::defaultLinkButton.color);
	p.drawTextLeft(x, y, outerWidth, _action, _actionWidth);
}

PeerListGlobalSearchController::PeerListGlobalSearchController(
	not_null<Main::Session*> session)
: _session(session)
, _api(&session->mtp()) {
	_timer.setCallback([this] { searchOnServer(); });
}

void PeerListGlobalSearchController::searchQuery(const QString &query) {
	if (_query != query) {
		_query = query;
		_requestId = 0;
		if (!_query.isEmpty() && !searchInCache()) {
			_timer.callOnce(AutoSearchTimeout);
		} else {
			_timer.cancel();
		}
	}
}

bool PeerListGlobalSearchController::searchInCache() {
	auto it = _cache.find(_query);
	if (it != _cache.cend()) {
		_requestId = 0;
		searchDone(it->second, _requestId);
		return true;
	}
	return false;
}

void PeerListGlobalSearchController::searchOnServer() {
	_requestId = _api.request(MTPcontacts_Search(
		MTP_string(_query),
		MTP_int(SearchPeopleLimit)
	)).done([=](const MTPcontacts_Found &result, mtpRequestId requestId) {
		searchDone(result, requestId);
	}).fail([=](const MTP::Error &error, mtpRequestId requestId) {
		if (_requestId == requestId) {
			_requestId = 0;
			delegate()->peerListSearchRefreshRows();
		}
	}).send();
	_queries.emplace(_requestId, _query);
}

void PeerListGlobalSearchController::searchDone(
		const MTPcontacts_Found &result,
		mtpRequestId requestId) {
	Expects(result.type() == mtpc_contacts_found);

	auto &contacts = result.c_contacts_found();
	auto query = _query;
	if (requestId) {
		_session->data().processUsers(contacts.vusers());
		_session->data().processChats(contacts.vchats());
		auto it = _queries.find(requestId);
		if (it != _queries.cend()) {
			query = it->second;
			_cache[query] = result;
			_queries.erase(it);
		}
	}
	const auto feedList = [&](const MTPVector<MTPPeer> &list) {
		for (const auto &mtpPeer : list.v) {
			const auto peer = _session->data().peerLoaded(
				peerFromMTP(mtpPeer));
			if (peer) {
				delegate()->peerListSearchAddRow(peer);
			}
		}
	};
	if (_requestId == requestId) {
		_requestId = 0;
		feedList(contacts.vmy_results());
		feedList(contacts.vresults());
		delegate()->peerListSearchRefreshRows();
	}
}

bool PeerListGlobalSearchController::isLoading() {
	return _timer.isActive() || _requestId;
}

ChatsListBoxController::Row::Row(not_null<History*> history)
: PeerListRow(history->peer)
, _history(history) {
}

ChatsListBoxController::ChatsListBoxController(
	not_null<Main::Session*> session)
: ChatsListBoxController(
	std::make_unique<PeerListGlobalSearchController>(session)) {
}

ChatsListBoxController::ChatsListBoxController(
	std::unique_ptr<PeerListSearchController> searchController)
: PeerListController(std::move(searchController)) {
}

void ChatsListBoxController::prepare() {
	setSearchNoResultsText(tr::lng_blocked_list_not_found(tr::now));
	delegate()->peerListSetSearchMode(PeerListSearchMode::Enabled);

	prepareViewHook();

	if (!session().data().chatsListLoaded()) {
		session().data().chatsListLoadedEvents(
		) | rpl::filter([=](Data::Folder *folder) {
			return !folder;
		}) | rpl::start_with_next([=] {
			checkForEmptyRows();
		}, lifetime());
	}

	session().data().chatsListChanges(
	) | rpl::start_with_next([=] {
		rebuildRows();
	}, lifetime());

	session().data().contactsLoaded().value(
	) | rpl::start_with_next([=] {
		rebuildRows();
	}, lifetime());
}

void ChatsListBoxController::rebuildRows() {
	auto wasEmpty = !delegate()->peerListFullRowsCount();
	auto appendList = [this](auto chats) {
		auto count = 0;
		for (const auto &row : chats->all()) {
			if (const auto history = row->history()) {
				if (appendRow(history)) {
					++count;
				}
			}
		}
		return count;
	};
	auto added = 0;
	if (respectSavedMessagesChat()) {
		if (appendRow(session().data().history(session().user()))) {
			++added;
		}
	}
	added += appendList(session().data().chatsList()->indexed());
	const auto id = Data::Folder::kId;
	if (const auto folder = session().data().folderLoaded(id)) {
		added += appendList(folder->chatsList()->indexed());
	}
	added += appendList(session().data().contactsNoChatsList());
	if (!wasEmpty && added > 0) {
		// Place dialogs list before contactsNoDialogs list.
		delegate()->peerListPartitionRows([](const PeerListRow &a) {
			const auto history = static_cast<const Row&>(a).history();
			return history->inChatList();
		});
		if (respectSavedMessagesChat()) {
			delegate()->peerListPartitionRows([](const PeerListRow &a) {
				return a.peer()->isSelf();
			});
		}
	}
	checkForEmptyRows();
	delegate()->peerListRefreshRows();
}

void ChatsListBoxController::checkForEmptyRows() {
	if (delegate()->peerListFullRowsCount()) {
		setDescriptionText(QString());
	} else {
		const auto loaded = session().data().contactsLoaded().current()
			&& session().data().chatsListLoaded();
		setDescriptionText(loaded ? emptyBoxText() : tr::lng_contacts_loading(tr::now));
	}
}

QString ChatsListBoxController::emptyBoxText() const {
	return tr::lng_contacts_not_found(tr::now);
}

std::unique_ptr<PeerListRow> ChatsListBoxController::createSearchRow(
		not_null<PeerData*> peer) {
	return createRow(peer->owner().history(peer));
}

bool ChatsListBoxController::appendRow(not_null<History*> history) {
	if (auto row = delegate()->peerListFindRow(history->peer->id.value)) {
		updateRowHook(static_cast<Row*>(row));
		return false;
	}
	if (auto row = createRow(history)) {
		delegate()->peerListAppendRow(std::move(row));
		return true;
	}
	return false;
}

ContactsBoxController::ContactsBoxController(
	not_null<Main::Session*> session)
: ContactsBoxController(
	session,
	std::make_unique<PeerListGlobalSearchController>(session)) {
}

ContactsBoxController::ContactsBoxController(
	not_null<Main::Session*> session,
	std::unique_ptr<PeerListSearchController> searchController)
: PeerListController(std::move(searchController))
, _session(session)
, _sortByOnlineTimer([=] { sort(); }) {
}

Main::Session &ContactsBoxController::session() const {
	return *_session;
}

void ContactsBoxController::prepare() {
	setSearchNoResultsText(tr::lng_blocked_list_not_found(tr::now));
	delegate()->peerListSetSearchMode(PeerListSearchMode::Enabled);
	delegate()->peerListSetTitle(tr::lng_contacts_header());

	prepareViewHook();

	session().data().contactsLoaded().value(
	) | rpl::start_with_next([=] {
		rebuildRows();
	}, lifetime());
}

void ContactsBoxController::rebuildRows() {
	const auto appendList = [&](auto chats) {
		auto count = 0;
		for (const auto &row : chats->all()) {
			if (const auto history = row->history()) {
				if (const auto user = history->peer->asUser()) {
					if (appendRow(user)) {
						++count;
					}
				}
			}
		}
		return count;
	};
	appendList(session().data().contactsList());
	checkForEmptyRows();
	sort();
	delegate()->peerListRefreshRows();
}

void ContactsBoxController::checkForEmptyRows() {
	setDescriptionText(delegate()->peerListFullRowsCount()
		? QString()
		: session().data().contactsLoaded().current()
		? tr::lng_contacts_not_found(tr::now)
		: tr::lng_contacts_loading(tr::now));
}

std::unique_ptr<PeerListRow> ContactsBoxController::createSearchRow(
		not_null<PeerData*> peer) {
	if (const auto user = peer->asUser()) {
		return createRow(user);
	}
	return nullptr;
}

void ContactsBoxController::rowClicked(not_null<PeerListRow*> row) {
	const auto peer = row->peer();
	if (const auto window = peer->session().tryResolveWindow()) {
		window->showPeerHistory(row->peer());
	}
}

void ContactsBoxController::setSortMode(SortMode mode) {
	if (_sortMode == mode) {
		return;
	}
	_sortMode = mode;
	sort();
	if (_sortMode == SortMode::Online) {
		session().changes().peerUpdates(
			Data::PeerUpdate::Flag::OnlineStatus
		) | rpl::filter([=](const Data::PeerUpdate &update) {
			return !_sortByOnlineTimer.isActive()
				&& delegate()->peerListFindRow(update.peer->id.value);
		}) | rpl::start_with_next([=] {
			_sortByOnlineTimer.callOnce(kSortByOnlineThrottle);
		}, _sortByOnlineLifetime);
	} else {
		_sortByOnlineTimer.cancel();
		_sortByOnlineLifetime.destroy();
	}
}

void ContactsBoxController::sort() {
	switch (_sortMode) {
	case SortMode::Alphabet: sortByName(); break;
	case SortMode::Online: sortByOnline(); break;
	default: Unexpected("SortMode in ContactsBoxController.");
	}
}

void ContactsBoxController::sortByName() {
	auto keys = base::flat_map<PeerListRowId, QString>();
	keys.reserve(delegate()->peerListFullRowsCount());
	const auto key = [&](const PeerListRow &row) {
		const auto id = row.id();
		const auto i = keys.find(id);
		if (i != end(keys)) {
			return i->second;
		}
		const auto peer = row.peer();
		const auto history = peer->owner().history(peer);
		return keys.emplace(id, history->chatListNameSortKey()).first->second;
	};
	const auto predicate = [&](const PeerListRow &a, const PeerListRow &b) {
		return (key(a).compare(key(b)) < 0);
	};
	delegate()->peerListSortRows(predicate);
}

void ContactsBoxController::sortByOnline() {
	const auto now = base::unixtime::now();
	const auto key = [&](const PeerListRow &row) {
		const auto user = row.peer()->asUser();
		return user ? (std::min(user->onlineTill, now) + 1) : TimeId();
	};
	const auto predicate = [&](const PeerListRow &a, const PeerListRow &b) {
		return key(a) > key(b);
	};
	delegate()->peerListSortRows(predicate);
}

bool ContactsBoxController::appendRow(not_null<UserData*> user) {
	if (auto row = delegate()->peerListFindRow(user->id.value)) {
		updateRowHook(row);
		return false;
	}
	if (auto row = createRow(user)) {
		delegate()->peerListAppendRow(std::move(row));
		return true;
	}
	return false;
}

std::unique_ptr<PeerListRow> ContactsBoxController::createRow(
		not_null<UserData*> user) {
	return std::make_unique<PeerListRow>(user);
}

ChooseRecipientBoxController::ChooseRecipientBoxController(
	not_null<Main::Session*> session,
	FnMut<void(not_null<Data::Thread*>)> callback,
	Fn<bool(not_null<Data::Thread*>)> filter)
: ChatsListBoxController(session)
, _session(session)
, _callback(std::move(callback))
, _filter(std::move(filter)) {
}

Main::Session &ChooseRecipientBoxController::session() const {
	return *_session;
}

void ChooseRecipientBoxController::prepareViewHook() {
	delegate()->peerListSetTitle(tr::lng_forward_choose());
}

void ChooseRecipientBoxController::rowClicked(not_null<PeerListRow*> row) {
	auto guard = base::make_weak(this);
	const auto peer = row->peer();
	if (const auto forum = peer->forum()) {
		const auto weak = std::make_shared<QPointer<Ui::BoxContent>>();
		auto callback = [=](not_null<Data::ForumTopic*> topic) {
			const auto exists = guard.get();
			if (!exists) {
				if (*weak) {
					(*weak)->closeBox();
				}
				return;
			}
			auto onstack = std::move(_callback);
			onstack(topic);
			if (guard) {
				_callback = std::move(onstack);
			} else if (*weak) {
				(*weak)->closeBox();
			}
		};
		const auto filter = [=](not_null<Data::ForumTopic*> topic) {
			return guard && (!_filter || _filter(topic));
		};
		auto owned = Box<PeerListBox>(
			std::make_unique<ChooseTopicBoxController>(
				forum,
				std::move(callback),
				filter),
			[=](not_null<PeerListBox*> box) {
				box->addButton(tr::lng_cancel(), [=] {
					box->closeBox();
				});

				forum->destroyed(
				) | rpl::start_with_next([=] {
					box->closeBox();
				}, box->lifetime());
			});
		*weak = owned.data();
		delegate()->peerListShowBox(std::move(owned));
		return;
	}
	const auto history = peer->owner().history(peer);
	auto callback = std::move(_callback);
	callback(history);
	if (guard) {
		_callback = std::move(callback);
	}
}

auto ChooseRecipientBoxController::createRow(
		not_null<History*> history) -> std::unique_ptr<Row> {
	const auto peer = history->peer;
	const auto skip = _filter
		? !_filter(history)
		: ((peer->isBroadcast() && !Data::CanSendAnything(peer))
			|| (peer->isUser() && !Data::CanSendAnything(peer)));
	return skip ? nullptr : std::make_unique<Row>(history);
}

ChooseTopicSearchController::ChooseTopicSearchController(
	not_null<Data::Forum*> forum)
: _forum(forum)
, _api(&forum->session().mtp())
, _timer([=] { searchOnServer(); }) {
}

void ChooseTopicSearchController::searchQuery(const QString &query) {
	if (_query != query) {
		_query = query;
		_api.request(base::take(_requestId)).cancel();
		_offsetDate = 0;
		_offsetId = 0;
		_offsetTopicId = 0;
		_allLoaded = false;
		if (!_query.isEmpty()) {
			_timer.callOnce(AutoSearchTimeout);
		} else {
			_timer.cancel();
		}
	}
}

void ChooseTopicSearchController::searchOnServer() {
	_requestId = _api.request(MTPchannels_GetForumTopics(
		MTP_flags(MTPchannels_GetForumTopics::Flag::f_q),
		_forum->channel()->inputChannel,
		MTP_string(_query),
		MTP_int(_offsetDate),
		MTP_int(_offsetId),
		MTP_int(_offsetTopicId),
		MTP_int(kSearchPerPage)
	)).done([=](const MTPmessages_ForumTopics &result) {
		_requestId = 0;
		const auto savedTopicId = _offsetTopicId;
		const auto byCreation = result.data().is_order_by_create_date();
		_forum->applyReceivedTopics(result, [&](
				not_null<Data::ForumTopic*> topic) {
			_offsetTopicId = topic->rootId();
			if (byCreation) {
				_offsetDate = topic->creationDate();
				if (const auto last = topic->lastServerMessage()) {
					_offsetId = last->id;
				}
			} else if (const auto last = topic->lastServerMessage()) {
				_offsetId = last->id;
				_offsetDate = last->date();
			}
			delegate()->peerListSearchAddRow(topic->rootId().bare);
		});
		if (_offsetTopicId == savedTopicId) {
			_allLoaded = true;
		}
		delegate()->peerListSearchRefreshRows();
	}).fail([=] {
		_allLoaded = true;
	}).send();
}

bool ChooseTopicSearchController::isLoading() {
	return _timer.isActive() || _requestId;
}

bool ChooseTopicSearchController::loadMoreRows() {
	if (!isLoading()) {
		searchOnServer();
	}
	return !_allLoaded;
}

ChooseTopicBoxController::Row::Row(not_null<Data::ForumTopic*> topic)
: PeerListRow(topic->rootId().bare)
, _topic(topic) {
}

QString ChooseTopicBoxController::Row::generateName() {
	return _topic->title();
}

QString ChooseTopicBoxController::Row::generateShortName() {
	return _topic->title();
}

auto ChooseTopicBoxController::Row::generatePaintUserpicCallback(
	bool forceRound)
-> PaintRoundImageCallback {
	return [=](
			Painter &p,
			int x,
			int y,
			int outerWidth,
			int size) {
		const auto &st = st::forumTopicRow;
		x -= st.padding.left();
		y -= st.padding.top();
		auto view = Ui::PeerUserpicView();
		p.translate(x, y);
		_topic->paintUserpic(p, view, {
			.st = &st,
			.currentBg = st::windowBg,
			.now = crl::now(),
			.width = outerWidth,
			.paused = false,
		});
		p.translate(-x, -y);
	};
}

auto ChooseTopicBoxController::Row::generateNameFirstLetters() const
-> const base::flat_set<QChar> & {
	return _topic->chatListFirstLetters();
}

auto ChooseTopicBoxController::Row::generateNameWords() const
-> const base::flat_set<QString> & {
	return _topic->chatListNameWords();
}

ChooseTopicBoxController::ChooseTopicBoxController(
	not_null<Data::Forum*> forum,
	FnMut<void(not_null<Data::ForumTopic*>)> callback,
	Fn<bool(not_null<Data::ForumTopic*>)> filter)
: PeerListController(std::make_unique<ChooseTopicSearchController>(forum))
, _forum(forum)
, _callback(std::move(callback))
, _filter(std::move(filter)) {
	setStyleOverrides(&st::chooseTopicList);

	_forum->chatsListChanges(
	) | rpl::start_with_next([=] {
		refreshRows();
	}, lifetime());

	_forum->topicDestroyed(
	) | rpl::start_with_next([=](not_null<Data::ForumTopic*> topic) {
		const auto id = PeerListRowId(topic->rootId().bare);
		if (const auto row = delegate()->peerListFindRow(id)) {
			delegate()->peerListRemoveRow(row);
			delegate()->peerListRefreshRows();
		}
	}, lifetime());
}

Main::Session &ChooseTopicBoxController::session() const {
	return _forum->session();
}

void ChooseTopicBoxController::rowClicked(not_null<PeerListRow*> row) {
	const auto weak = base::make_weak(this);
	auto onstack = base::take(_callback);
	onstack(static_cast<Row*>(row.get())->topic());
	if (weak) {
		_callback = std::move(onstack);
	}
}

void ChooseTopicBoxController::prepare() {
	delegate()->peerListSetTitle(tr::lng_forward_choose());
	setSearchNoResultsText(tr::lng_topics_not_found(tr::now));
	delegate()->peerListSetSearchMode(PeerListSearchMode::Enabled);
	refreshRows(true);

	session().changes().entryUpdates(
		Data::EntryUpdate::Flag::Repaint
	) | rpl::start_with_next([=](const Data::EntryUpdate &update) {
		if (const auto topic = update.entry->asTopic()) {
			if (topic->forum() == _forum) {
				const auto id = topic->rootId().bare;
				if (const auto row = delegate()->peerListFindRow(id)) {
					delegate()->peerListUpdateRow(row);
				}
			}
		}
	}, lifetime());
}

void ChooseTopicBoxController::refreshRows(bool initial) {
	auto added = false;
	for (const auto &row : _forum->topicsList()->indexed()->all()) {
		if (const auto topic = row->topic()) {
			const auto id = topic->rootId().bare;
			auto already = delegate()->peerListFindRow(id);
			if (initial || !already) {
				if (auto created = createRow(topic)) {
					delegate()->peerListAppendRow(std::move(created));
					added = true;
				}
			} else if (already->isSearchResult()) {
				delegate()->peerListAppendFoundRow(already);
				added = true;
			}
		}
	}
	if (added) {
		delegate()->peerListRefreshRows();
	}
}

void ChooseTopicBoxController::loadMoreRows() {
	_forum->requestTopics();
}

std::unique_ptr<PeerListRow> ChooseTopicBoxController::createSearchRow(
		PeerListRowId id) {
	if (const auto topic = _forum->topicFor(MsgId(id))) {
		return std::make_unique<Row>(topic);
	}
	return nullptr;
}

auto ChooseTopicBoxController::createRow(not_null<Data::ForumTopic*> topic)
-> std::unique_ptr<Row> {
	const auto skip = _filter && !_filter(topic);
	return skip ? nullptr : std::make_unique<Row>(topic);
};