tdesktop/Telegram/SourceFiles/window/window_session_controller.cpp

1104 lines
32 KiB
C++
Raw Normal View History

/*
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 "window/window_session_controller.h"
#include "boxes/peers/edit_peer_info_box.h"
2020-09-22 15:05:07 +00:00
#include "boxes/peer_list_controllers.h"
2019-09-03 15:24:51 +00:00
#include "window/window_controller.h"
#include "window/main_window.h"
2020-03-03 12:07:22 +00:00
#include "window/window_filters_menu.h"
#include "info/info_memento.h"
2018-09-05 19:05:49 +00:00
#include "info/info_controller.h"
#include "history/history.h"
#include "history/history_item.h"
#include "history/view/history_view_element.h"
2020-09-03 08:21:31 +00:00
#include "history/view/history_view_replies_section.h"
2019-04-15 11:54:03 +00:00
//#include "history/feed/history_feed_section.h" // #feed
#include "media/player/media_player_instance.h"
#include "data/data_media_types.h"
#include "data/data_session.h"
2019-04-15 11:54:03 +00:00
#include "data/data_folder.h"
#include "data/data_channel.h"
#include "data/data_chat.h"
2020-09-22 15:05:07 +00:00
#include "data/data_user.h"
#include "data/data_changes.h"
#include "data/data_chat_filters.h"
#include "passport/passport_form_controller.h"
#include "chat_helpers/tabbed_selector.h"
#include "core/shortcuts.h"
2020-06-25 12:16:09 +00:00
#include "core/application.h"
#include "core/core_settings.h"
#include "base/unixtime.h"
#include "ui/layers/generic_box.h"
#include "ui/text/text_utilities.h"
#include "ui/delayed_activation.h"
#include "ui/toast/toast.h"
#include "boxes/calendar_box.h"
#include "boxes/confirm_box.h"
#include "mainwidget.h"
#include "mainwindow.h"
2019-07-24 11:45:24 +00:00
#include "main/main_session.h"
#include "main/main_session_settings.h"
#include "apiwrap.h"
2020-07-01 14:19:25 +00:00
#include "api/api_chat_invite.h"
#include "api/api_global_privacy.h"
#include "support/support_helper.h"
#include "facades.h"
#include "styles/style_window.h"
#include "styles/style_dialogs.h"
#include "styles/style_layers.h" // st::boxLabel
namespace Window {
namespace {
constexpr auto kMaxChatEntryHistorySize = 50;
} // namespace
void ActivateWindow(not_null<SessionController*> controller) {
const auto window = controller->widget();
window->activateWindow();
Ui::ActivateWindowDelayed(window);
}
2018-02-21 21:17:36 +00:00
DateClickHandler::DateClickHandler(Dialogs::Key chat, QDate date)
: _chat(chat)
, _date(date) {
}
void DateClickHandler::setDate(QDate date) {
_date = date;
}
void DateClickHandler::onClick(ClickContext context) const {
App::wnd()->sessionController()->showJumpToDate(_chat, _date);
2018-02-21 21:17:36 +00:00
}
2019-07-24 11:45:24 +00:00
SessionNavigation::SessionNavigation(not_null<Main::Session*> session)
: _session(session) {
2019-01-18 12:27:37 +00:00
}
2020-09-03 08:21:31 +00:00
SessionNavigation::~SessionNavigation() {
_session->api().request(base::take(_showingRepliesRequestId)).cancel();
2020-09-22 15:05:07 +00:00
_session->api().request(base::take(_resolveRequestId)).cancel();
2020-09-03 08:21:31 +00:00
}
2019-07-24 11:45:24 +00:00
Main::Session &SessionNavigation::session() const {
2019-01-18 12:27:37 +00:00
return *_session;
}
2020-09-22 15:05:07 +00:00
void SessionNavigation::showPeerByLink(const PeerByLinkInfo &info) {
Core::App().hideMediaView();
if (const auto username = std::get_if<QString>(&info.usernameOrId)) {
resolveUsername(*username, [=](not_null<PeerData*> peer) {
showPeerByLinkResolved(peer, info);
});
} else if (const auto id = std::get_if<ChannelId>(&info.usernameOrId)) {
resolveChannelById(*id, [=](not_null<ChannelData*> channel) {
showPeerByLinkResolved(channel, info);
});
}
}
void SessionNavigation::resolveUsername(
const QString &username,
Fn<void(not_null<PeerData*>)> done) {
if (const auto peer = _session->data().peerByUsername(username)) {
done(peer);
return;
}
_session->api().request(base::take(_resolveRequestId)).cancel();
_resolveRequestId = _session->api().request(MTPcontacts_ResolveUsername(
MTP_string(username)
)).done([=](const MTPcontacts_ResolvedPeer &result) {
_resolveRequestId = 0;
Ui::hideLayer();
if (result.type() != mtpc_contacts_resolvedPeer) {
return;
}
const auto &d(result.c_contacts_resolvedPeer());
_session->data().processUsers(d.vusers());
_session->data().processChats(d.vchats());
if (const auto peerId = peerFromMTP(d.vpeer())) {
done(_session->data().peer(peerId));
}
}).fail([=](const RPCError &error) {
_resolveRequestId = 0;
if (error.code() == 400) {
Ui::show(Box<InformBox>(
tr::lng_username_not_found(tr::now, lt_user, username)));
}
}).send();
}
void SessionNavigation::resolveChannelById(
ChannelId channelId,
Fn<void(not_null<ChannelData*>)> done) {
if (const auto channel = _session->data().channelLoaded(channelId)) {
done(channel);
return;
}
const auto fail = [=] {
Ui::show(Box<InformBox>(tr::lng_error_post_link_invalid(tr::now)));
};
_session->api().request(base::take(_resolveRequestId)).cancel();
_resolveRequestId = _session->api().request(MTPchannels_GetChannels(
MTP_vector<MTPInputChannel>(
1,
MTP_inputChannel(MTP_int(channelId), MTP_long(0)))
)).done([=](const MTPmessages_Chats &result) {
result.match([&](const auto &data) {
const auto peer = _session->data().processChats(data.vchats());
if (peer && peer->id == peerFromChannel(channelId)) {
done(peer->asChannel());
} else {
fail();
}
});
}).fail([=](const RPCError &error) {
fail();
}).send();
}
void SessionNavigation::showPeerByLinkResolved(
not_null<PeerData*> peer,
const PeerByLinkInfo &info) {
auto params = SectionShow{
SectionShow::Way::Forward
};
params.origin = SectionShow::OriginMessage{
info.clickFromMessageId
};
const auto &replies = info.repliesInfo;
if (const auto threadId = std::get_if<ThreadId>(&replies)) {
showRepliesForMessage(
session().data().history(peer),
threadId->id,
info.messageId,
params);
} else if (const auto commentId = std::get_if<CommentId>(&replies)) {
showRepliesForMessage(
session().data().history(peer),
info.messageId,
commentId->id,
params);
} else if (info.messageId == ShowAtGameShareMsgId) {
const auto user = peer->asUser();
if (user && user->isBot() && !info.startToken.isEmpty()) {
user->botInfo->shareGameShortName = info.startToken;
AddBotToGroupBoxController::Start(this, user);
} else {
crl::on_main(this, [=] {
showPeerHistory(peer->id, params);
});
}
} else if (info.messageId == ShowAtProfileMsgId && !peer->isChannel()) {
const auto user = peer->asUser();
if (user
&& user->isBot()
&& !user->botInfo->cantJoinGroups
&& !info.startToken.isEmpty()) {
user->botInfo->startGroupToken = info.startToken;
AddBotToGroupBoxController::Start(this, user);
} else if (user && user->isBot()) {
// Always open bot chats, even from mention links.
crl::on_main(this, [=] {
showPeerHistory(peer->id, params);
});
} else {
showPeerInfo(peer, params);
}
} else {
const auto user = peer->asUser();
auto msgId = info.messageId;
if (msgId == ShowAtProfileMsgId || !peer->isChannel()) {
// Show specific posts only in channels / supergroups.
msgId = ShowAtUnreadMsgId;
}
if (user && user->isBot()) {
user->botInfo->startToken = info.startToken;
user->session().changes().peerUpdated(
user,
Data::PeerUpdate::Flag::BotStartToken);
}
crl::on_main(this, [=] {
showPeerHistory(peer->id, params, msgId);
});
}
}
2020-09-03 08:21:31 +00:00
void SessionNavigation::showRepliesForMessage(
not_null<History*> history,
MsgId rootId,
MsgId commentId,
2020-09-03 08:21:31 +00:00
const SectionShow &params) {
if (_showingRepliesRequestId
&& _showingRepliesHistory == history.get()
&& _showingRepliesRootId == rootId) {
return;
} else if (!history->peer->asChannel()) {
// HistoryView::RepliesWidget right now handles only channels.
return;
2020-09-03 08:21:31 +00:00
}
_session->api().request(base::take(_showingRepliesRequestId)).cancel();
const auto channelId = history->channelId();
2020-09-22 15:05:07 +00:00
//const auto item = _session->data().message(channelId, rootId);
//if (!commentId && (!item || !item->repliesAreComments())) {
// showSection(HistoryView::RepliesMemento(history, rootId));
// return;
//} else if (const auto id = item ? item->commentsItemId() : FullMsgId()) {
// if (const auto commentsItem = _session->data().message(id)) {
// showSection(
// HistoryView::RepliesMemento(commentsItem));
// return;
// }
//}
2020-09-03 08:21:31 +00:00
_showingRepliesHistory = history;
_showingRepliesRootId = rootId;
_showingRepliesRequestId = _session->api().request(
MTPmessages_GetDiscussionMessage(
history->peer->input,
MTP_int(rootId))
).done([=](const MTPmessages_DiscussionMessage &result) {
_showingRepliesRequestId = 0;
result.match([&](const MTPDmessages_discussionMessage &data) {
_session->data().processUsers(data.vusers());
_session->data().processChats(data.vchats());
_session->data().processMessages(
data.vmessages(),
NewMessageType::Existing);
const auto list = data.vmessages().v;
if (list.isEmpty()) {
return;
}
const auto id = IdFromMessage(list.front());
const auto peer = PeerFromMessage(list.front());
if (!peer || !id) {
return;
}
auto item = _session->data().message(
peerToChannel(peer),
id);
if (const auto group = _session->data().groups().find(item)) {
item = group->items.front();
}
if (item) {
if (const auto maxId = data.vmax_id()) {
item->setRepliesMaxId(maxId->v);
}
if (const auto readTill = data.vread_inbox_max_id()) {
item->setRepliesInboxReadTill(readTill->v);
}
if (const auto readTill = data.vread_outbox_max_id()) {
item->setRepliesOutboxReadTill(readTill->v);
}
2020-09-03 08:21:31 +00:00
const auto post = _session->data().message(channelId, rootId);
2020-09-22 15:05:07 +00:00
if (post && item->history()->channelId() != channelId) {
2020-09-03 08:21:31 +00:00
post->setCommentsItemId(item->fullId());
2020-09-15 08:39:39 +00:00
if (const auto maxId = data.vmax_id()) {
post->setRepliesMaxId(maxId->v);
2020-09-15 08:39:39 +00:00
}
2020-09-18 09:57:04 +00:00
if (const auto readTill = data.vread_inbox_max_id()) {
post->setRepliesInboxReadTill(readTill->v);
}
if (const auto readTill = data.vread_outbox_max_id()) {
post->setRepliesOutboxReadTill(readTill->v);
2020-09-15 08:39:39 +00:00
}
2020-09-08 11:19:44 +00:00
}
2020-09-03 08:21:31 +00:00
showSection(
HistoryView::RepliesMemento(item, commentId));
2020-09-03 08:21:31 +00:00
}
});
}).fail([=](const RPCError &error) {
_showingRepliesRequestId = 0;
if (error.type() == u"CHANNEL_PRIVATE"_q
|| error.type() == u"USER_BANNED_IN_CHANNEL"_q) {
Ui::Toast::Show(tr::lng_group_not_accessible(tr::now));
}
2020-09-03 08:21:31 +00:00
}).send();
}
void SessionNavigation::showPeerInfo(
2019-01-18 12:27:37 +00:00
PeerId peerId,
const SectionShow &params) {
2020-06-08 09:06:50 +00:00
showPeerInfo(_session->data().peer(peerId), params);
2019-01-18 12:27:37 +00:00
}
void SessionNavigation::showPeerInfo(
2019-01-18 12:27:37 +00:00
not_null<PeerData*> peer,
const SectionShow &params) {
2020-06-08 09:06:50 +00:00
//if (Adaptive::ThreeColumn()
2020-06-25 12:16:09 +00:00
// && !Core::App().settings().thirdSectionInfoEnabled()) {
// Core::App().settings().setThirdSectionInfoEnabled(true);
// Core::App().saveSettingsDelayed();
2020-06-08 09:06:50 +00:00
//}
showSection(Info::Memento(peer), params);
2019-01-18 12:27:37 +00:00
}
void SessionNavigation::showPeerInfo(
2019-01-18 12:27:37 +00:00
not_null<History*> history,
const SectionShow &params) {
showPeerInfo(history->peer->id, params);
}
2020-09-22 15:05:07 +00:00
void SessionNavigation::showPeerHistory(
not_null<PeerData*> peer,
const SectionShow &params,
MsgId msgId) {
showPeerHistory(
peer->id,
params,
msgId);
}
void SessionNavigation::showPeerHistory(
not_null<History*> history,
const SectionShow &params,
MsgId msgId) {
showPeerHistory(
history->peer->id,
params,
msgId);
}
void SessionNavigation::showSettings(
2019-01-18 12:27:37 +00:00
Settings::Type type,
const SectionShow &params) {
showSection(
Info::Memento(
Info::Settings::Tag{ _session->user() },
Info::Section(type)),
params);
}
void SessionNavigation::showSettings(const SectionShow &params) {
2019-01-18 12:27:37 +00:00
showSettings(Settings::Type::Main, params);
}
void SessionNavigation::showPollResults(
not_null<PollData*> poll,
FullMsgId contextId,
const SectionShow &params) {
showSection(Info::Memento(poll, contextId), params);
}
SessionController::SessionController(
2019-07-24 11:45:24 +00:00
not_null<Main::Session*> session,
2019-09-03 15:24:51 +00:00
not_null<Controller*> window)
: SessionNavigation(session)
, _window(window)
, _tabbedSelector(
2019-09-03 15:24:51 +00:00
std::make_unique<ChatHelpers::TabbedSelector>(
_window->widget(),
2020-07-01 14:19:25 +00:00
this))
, _invitePeekTimer([=] { checkInvitePeek(); }) {
2019-01-18 12:27:37 +00:00
init();
if (Media::Player::instance()->pauseGifByRoundVideo()) {
enableGifPauseReason(GifPauseReason::RoundPlaying);
}
2019-06-06 11:59:00 +00:00
subscribe(session->api().fullPeerUpdated(), [=](PeerData *peer) {
if (peer == _showEditPeer) {
_showEditPeer = nullptr;
2019-07-25 18:55:11 +00:00
Ui::show(Box<EditPeerInfoBox>(this, peer));
}
});
2019-04-24 10:15:10 +00:00
session->data().chatsListChanges(
) | rpl::filter([=](Data::Folder *folder) {
return (folder != nullptr)
&& (folder == _openedFolder.current())
2020-02-07 09:43:12 +00:00
&& folder->chatsList()->indexed()->empty();
2019-04-24 10:15:10 +00:00
}) | rpl::start_with_next([=](Data::Folder *folder) {
folder->updateChatListSortPosition();
closeFolder();
}, lifetime());
session->data().chatsFilters().changed(
) | rpl::start_with_next([=] {
checkOpenedFilter();
2020-06-22 07:30:32 +00:00
crl::on_main(this, [=] {
refreshFiltersMenu();
});
2020-06-26 17:50:36 +00:00
}, lifetime());
session->api().globalPrivacy().suggestArchiveAndMute(
) | rpl::take(1) | rpl::start_with_next([=] {
session->api().globalPrivacy().reload(crl::guard(this, [=] {
if (!session->api().globalPrivacy().archiveAndMuteCurrent()) {
suggestArchiveAndMute();
}
}));
}, _lifetime);
session->addWindow(this);
}
void SessionController::suggestArchiveAndMute() {
const auto weak = base::make_weak(this);
_window->show(Box([=](not_null<Ui::GenericBox*> box) {
box->setTitle(tr::lng_suggest_hide_new_title());
box->addRow(object_ptr<Ui::FlatLabel>(
box,
tr::lng_suggest_hide_new_about(Ui::Text::RichLangValue),
st::boxLabel));
box->addButton(tr::lng_suggest_hide_new_to_settings(), [=] {
showSettings(Settings::Type::PrivacySecurity);
});
box->setCloseByOutsideClick(false);
box->boxClosing(
) | rpl::start_with_next([=] {
crl::on_main(weak, [=] {
auto &privacy = session().api().globalPrivacy();
privacy.dismissArchiveAndMuteSuggestion();
});
}, box->lifetime());
box->addButton(tr::lng_cancel(), [=] {
box->closeBox();
});
}));
}
2019-09-03 15:24:51 +00:00
not_null<::MainWindow*> SessionController::widget() const {
return _window->widget();
}
auto SessionController::tabbedSelector() const
-> not_null<ChatHelpers::TabbedSelector*> {
return _tabbedSelector.get();
}
void SessionController::takeTabbedSelectorOwnershipFrom(
not_null<QWidget*> parent) {
if (_tabbedSelector->parent() == parent) {
2020-06-10 18:08:17 +00:00
if (const auto chats = widget()->sessionContent()) {
chats->returnTabbedSelector();
}
if (_tabbedSelector->parent() == parent) {
_tabbedSelector->hide();
2019-09-03 15:24:51 +00:00
_tabbedSelector->setParent(widget());
}
}
}
bool SessionController::hasTabbedSelectorOwnership() const {
2019-09-03 15:24:51 +00:00
return (_tabbedSelector->parent() == widget());
}
void SessionController::showEditPeerBox(PeerData *peer) {
_showEditPeer = peer;
2019-06-06 11:59:00 +00:00
session().api().requestFullPeer(peer);
2019-01-18 12:27:37 +00:00
}
void SessionController::init() {
2019-01-18 12:27:37 +00:00
if (session().supportMode()) {
initSupportMode();
}
}
void SessionController::initSupportMode() {
2019-01-18 12:27:37 +00:00
session().supportHelper().registerWindow(this);
Shortcuts::Requests(
) | rpl::start_with_next([=](not_null<Shortcuts::Request*> request) {
using C = Shortcuts::Command;
request->check(C::SupportHistoryBack) && request->handle([=] {
return chatEntryHistoryMove(-1);
});
request->check(C::SupportHistoryForward) && request->handle([=] {
return chatEntryHistoryMove(1);
});
}, lifetime());
}
2020-03-03 12:07:22 +00:00
void SessionController::toggleFiltersMenu(bool enabled) {
if (!enabled == !_filters) {
return;
} else if (enabled) {
_filters = std::make_unique<FiltersMenu>(
widget()->bodyWidget(),
this);
2020-03-03 12:07:22 +00:00
} else {
_filters = nullptr;
}
_filtersMenuChanged.fire({});
2020-03-03 12:07:22 +00:00
}
void SessionController::refreshFiltersMenu() {
2020-06-22 07:30:32 +00:00
toggleFiltersMenu(!session().data().chatsFilters().list().empty());
}
rpl::producer<> SessionController::filtersMenuChanged() const {
return _filtersMenuChanged.events();
}
void SessionController::checkOpenedFilter() {
if (const auto filterId = activeChatsFilterCurrent()) {
const auto &list = session().data().chatsFilters().list();
const auto i = ranges::find(list, filterId, &Data::ChatFilter::id);
if (i == end(list)) {
setActiveChatsFilter(0);
}
}
}
bool SessionController::uniqueChatsInSearchResults() const {
2019-04-24 10:15:10 +00:00
return session().supportMode()
&& !session().settings().supportAllSearchResults()
&& !searchInChat.current();
}
void SessionController::openFolder(not_null<Data::Folder*> folder) {
if (_openedFolder.current() != folder) {
resetFakeUnreadWhileOpened();
}
2020-03-20 13:12:13 +00:00
setActiveChatsFilter(0);
2019-04-24 10:15:10 +00:00
_openedFolder = folder.get();
}
void SessionController::closeFolder() {
2019-04-24 10:15:10 +00:00
_openedFolder = nullptr;
}
const rpl::variable<Data::Folder*> &SessionController::openedFolder() const {
2019-04-24 10:15:10 +00:00
return _openedFolder;
}
void SessionController::setActiveChatEntry(Dialogs::RowDescriptor row) {
2020-03-23 10:09:27 +00:00
const auto was = _activeChatEntry.current().key.history();
const auto now = row.key.history();
if (was && was != now) {
was->setFakeUnreadWhileOpened(false);
2020-07-01 14:19:25 +00:00
_invitePeekTimer.cancel();
}
_activeChatEntry = row;
2020-03-23 10:09:27 +00:00
if (now) {
now->setFakeUnreadWhileOpened(true);
}
2019-01-18 12:27:37 +00:00
if (session().supportMode()) {
pushToChatEntryHistory(row);
}
2020-07-01 14:19:25 +00:00
checkInvitePeek();
}
void SessionController::checkInvitePeek() {
const auto history = activeChatCurrent().history();
if (!history) {
return;
}
const auto channel = history->peer->asChannel();
if (!channel) {
return;
}
const auto expires = channel->invitePeekExpires();
if (!expires) {
return;
}
const auto now = base::unixtime::now();
if (expires > now) {
_invitePeekTimer.callOnce((expires - now) * crl::time(1000));
return;
}
const auto hash = channel->invitePeekHash();
channel->clearInvitePeek();
Api::CheckChatInvite(this, hash, channel);
}
void SessionController::resetFakeUnreadWhileOpened() {
if (const auto history = _activeChatEntry.current().key.history()) {
history->setFakeUnreadWhileOpened(false);
}
}
bool SessionController::chatEntryHistoryMove(int steps) {
if (_chatEntryHistory.empty()) {
return false;
}
const auto position = _chatEntryHistoryPosition + steps;
if (!base::in_range(position, 0, int(_chatEntryHistory.size()))) {
return false;
}
_chatEntryHistoryPosition = position;
return jumpToChatListEntry(_chatEntryHistory[position]);
}
bool SessionController::jumpToChatListEntry(Dialogs::RowDescriptor row) {
if (const auto history = row.key.history()) {
Ui::showPeerHistory(history, row.fullId.msg);
return true;
2019-04-15 11:54:03 +00:00
//} else if (const auto feed = row.key.feed()) { // #feed
2019-06-06 11:59:00 +00:00
// if (const auto item = session().data().message(row.fullId)) {
2019-04-15 11:54:03 +00:00
// showSection(HistoryFeed::Memento(feed, item->position()));
// } else {
// showSection(HistoryFeed::Memento(feed));
// }
}
return false;
}
void SessionController::pushToChatEntryHistory(Dialogs::RowDescriptor row) {
if (!_chatEntryHistory.empty()
&& _chatEntryHistory[_chatEntryHistoryPosition] == row) {
return;
}
_chatEntryHistory.resize(++_chatEntryHistoryPosition);
_chatEntryHistory.push_back(row);
if (_chatEntryHistory.size() > kMaxChatEntryHistorySize) {
_chatEntryHistory.pop_front();
--_chatEntryHistoryPosition;
}
}
void SessionController::setActiveChatEntry(Dialogs::Key key) {
setActiveChatEntry({ key, FullMsgId() });
}
Dialogs::RowDescriptor SessionController::activeChatEntryCurrent() const {
return _activeChatEntry.current();
}
Dialogs::Key SessionController::activeChatCurrent() const {
return activeChatEntryCurrent().key;
}
auto SessionController::activeChatEntryChanges() const
-> rpl::producer<Dialogs::RowDescriptor> {
return _activeChatEntry.changes();
}
rpl::producer<Dialogs::Key> SessionController::activeChatChanges() const {
return activeChatEntryChanges(
) | rpl::map([](const Dialogs::RowDescriptor &value) {
return value.key;
}) | rpl::distinct_until_changed();
}
auto SessionController::activeChatEntryValue() const
-> rpl::producer<Dialogs::RowDescriptor> {
return _activeChatEntry.value();
}
rpl::producer<Dialogs::Key> SessionController::activeChatValue() const {
return activeChatEntryValue(
) | rpl::map([](const Dialogs::RowDescriptor &value) {
return value.key;
}) | rpl::distinct_until_changed();
}
void SessionController::enableGifPauseReason(GifPauseReason reason) {
if (!(_gifPauseReasons & reason)) {
auto notify = (static_cast<int>(_gifPauseReasons) < static_cast<int>(reason));
_gifPauseReasons |= reason;
if (notify) {
_gifPauseLevelChanged.notify();
}
}
}
void SessionController::disableGifPauseReason(GifPauseReason reason) {
if (_gifPauseReasons & reason) {
2017-08-31 16:28:58 +00:00
_gifPauseReasons &= ~reason;
if (_gifPauseReasons < reason) {
_gifPauseLevelChanged.notify();
}
}
}
bool SessionController::isGifPausedAtLeastFor(GifPauseReason reason) const {
if (reason == GifPauseReason::Any) {
2019-09-03 15:24:51 +00:00
return (_gifPauseReasons != 0) || !widget()->isActive();
}
2019-09-03 15:24:51 +00:00
return (static_cast<int>(_gifPauseReasons) >= 2 * static_cast<int>(reason)) || !widget()->isActive();
}
void SessionController::floatPlayerAreaUpdated() {
if (const auto main = widget()->sessionContent()) {
main->floatPlayerAreaUpdated();
}
}
int SessionController::dialogsSmallColumnWidth() const {
return st::dialogsPadding.x() + st::dialogsPhotoSize + st::dialogsPadding.x();
}
int SessionController::minimalThreeColumnWidth() const {
return st::columnMinimalWidthLeft
+ st::columnMinimalWidthMain
+ st::columnMinimalWidthThird;
}
bool SessionController::forceWideDialogs() const {
if (dialogsListDisplayForced().value()) {
return true;
} else if (dialogsListFocused().value()) {
return true;
}
2020-06-10 18:08:17 +00:00
return !content()->isMainSectionShown();
}
auto SessionController::computeColumnLayout() const -> ColumnLayout {
auto layout = Adaptive::WindowLayout::OneColumn;
auto bodyWidth = widget()->bodyWidget()->width() - filtersWidth();
auto dialogsWidth = 0, chatWidth = 0, thirdWidth = 0;
auto useOneColumnLayout = [&] {
auto minimalNormal = st::columnMinimalWidthLeft
+ st::columnMinimalWidthMain;
if (bodyWidth < minimalNormal) {
return true;
}
return false;
};
auto useNormalLayout = [&] {
// Used if useSmallColumnLayout() == false.
if (bodyWidth < minimalThreeColumnWidth()) {
return true;
}
2020-06-25 12:16:09 +00:00
if (!Core::App().settings().tabbedSelectorSectionEnabled()
&& !Core::App().settings().thirdSectionInfoEnabled()) {
return true;
}
return false;
};
if (useOneColumnLayout()) {
dialogsWidth = chatWidth = bodyWidth;
} else if (useNormalLayout()) {
layout = Adaptive::WindowLayout::Normal;
2017-11-12 16:50:58 +00:00
dialogsWidth = countDialogsWidthFromRatio(bodyWidth);
accumulate_min(dialogsWidth, bodyWidth - st::columnMinimalWidthMain);
chatWidth = bodyWidth - dialogsWidth;
} else {
layout = Adaptive::WindowLayout::ThreeColumn;
2017-11-12 16:50:58 +00:00
dialogsWidth = countDialogsWidthFromRatio(bodyWidth);
thirdWidth = countThirdColumnWidthFromRatio(bodyWidth);
auto shrink = shrinkDialogsAndThirdColumns(
dialogsWidth,
2017-11-12 16:50:58 +00:00
thirdWidth,
bodyWidth);
dialogsWidth = shrink.dialogsWidth;
thirdWidth = shrink.thirdWidth;
chatWidth = bodyWidth - dialogsWidth - thirdWidth;
}
return { bodyWidth, dialogsWidth, chatWidth, thirdWidth, layout };
}
int SessionController::countDialogsWidthFromRatio(int bodyWidth) const {
2020-06-25 12:16:09 +00:00
auto result = qRound(bodyWidth * Core::App().settings().dialogsWidthRatio());
2017-11-12 16:50:58 +00:00
accumulate_max(result, st::columnMinimalWidthLeft);
// accumulate_min(result, st::columnMaximalWidthLeft);
2017-11-12 16:50:58 +00:00
return result;
}
int SessionController::countThirdColumnWidthFromRatio(int bodyWidth) const {
2020-06-25 12:16:09 +00:00
auto result = Core::App().settings().thirdColumnWidth();
2017-11-12 16:50:58 +00:00
accumulate_max(result, st::columnMinimalWidthThird);
accumulate_min(result, st::columnMaximalWidthThird);
return result;
}
SessionController::ShrinkResult SessionController::shrinkDialogsAndThirdColumns(
2017-11-12 16:50:58 +00:00
int dialogsWidth,
int thirdWidth,
int bodyWidth) const {
auto chatWidth = st::columnMinimalWidthMain;
if (dialogsWidth + thirdWidth + chatWidth <= bodyWidth) {
return { dialogsWidth, thirdWidth };
}
auto thirdWidthNew = ((bodyWidth - chatWidth) * thirdWidth)
/ (dialogsWidth + thirdWidth);
auto dialogsWidthNew = ((bodyWidth - chatWidth) * dialogsWidth)
/ (dialogsWidth + thirdWidth);
if (thirdWidthNew < st::columnMinimalWidthThird) {
thirdWidthNew = st::columnMinimalWidthThird;
dialogsWidthNew = bodyWidth - thirdWidthNew - chatWidth;
Assert(dialogsWidthNew >= st::columnMinimalWidthLeft);
} else if (dialogsWidthNew < st::columnMinimalWidthLeft) {
dialogsWidthNew = st::columnMinimalWidthLeft;
thirdWidthNew = bodyWidth - dialogsWidthNew - chatWidth;
Assert(thirdWidthNew >= st::columnMinimalWidthThird);
}
return { dialogsWidthNew, thirdWidthNew };
}
bool SessionController::canShowThirdSection() const {
auto currentLayout = computeColumnLayout();
auto minimalExtendBy = minimalThreeColumnWidth()
- currentLayout.bodyWidth;
2019-09-03 15:24:51 +00:00
return (minimalExtendBy <= widget()->maximalExtendBy());
}
bool SessionController::canShowThirdSectionWithoutResize() const {
2017-09-19 10:32:34 +00:00
auto currentWidth = computeColumnLayout().bodyWidth;
return currentWidth >= minimalThreeColumnWidth();
}
bool SessionController::takeThirdSectionFromLayer() {
2020-06-10 18:08:17 +00:00
return widget()->takeThirdSectionFromLayer();
2017-09-19 10:32:34 +00:00
}
void SessionController::resizeForThirdSection() {
if (Adaptive::ThreeColumn()) {
return;
}
2020-06-25 12:16:09 +00:00
auto &settings = Core::App().settings();
auto layout = computeColumnLayout();
auto tabbedSelectorSectionEnabled =
2020-06-25 12:16:09 +00:00
settings.tabbedSelectorSectionEnabled();
auto thirdSectionInfoEnabled =
2020-06-25 12:16:09 +00:00
settings.thirdSectionInfoEnabled();
settings.setTabbedSelectorSectionEnabled(false);
settings.setThirdSectionInfoEnabled(false);
auto wanted = countThirdColumnWidthFromRatio(layout.bodyWidth);
auto minimal = st::columnMinimalWidthThird;
auto extendBy = wanted;
auto extendedBy = [&] {
// Best - extend by third column without moving the window.
// Next - extend by minimal third column without moving.
// Next - show third column inside the window without moving.
// Last - extend with moving.
2019-09-03 15:24:51 +00:00
if (widget()->canExtendNoMove(wanted)) {
return widget()->tryToExtendWidthBy(wanted);
} else if (widget()->canExtendNoMove(minimal)) {
extendBy = minimal;
2019-09-03 15:24:51 +00:00
return widget()->tryToExtendWidthBy(minimal);
} else if (layout.bodyWidth >= minimalThreeColumnWidth()) {
return 0;
}
2019-09-03 15:24:51 +00:00
return widget()->tryToExtendWidthBy(minimal);
}();
if (extendedBy) {
2020-06-25 12:16:09 +00:00
if (extendBy != settings.thirdColumnWidth()) {
settings.setThirdColumnWidth(extendBy);
}
auto newBodyWidth = layout.bodyWidth + extendedBy;
2020-06-25 12:16:09 +00:00
auto currentRatio = settings.dialogsWidthRatio();
settings.setDialogsWidthRatio(
(currentRatio * layout.bodyWidth) / newBodyWidth);
}
auto savedValue = (extendedBy == extendBy) ? -1 : extendedBy;
2020-06-25 12:16:09 +00:00
settings.setThirdSectionExtendedBy(savedValue);
2020-06-25 12:16:09 +00:00
settings.setTabbedSelectorSectionEnabled(
tabbedSelectorSectionEnabled);
2020-06-25 12:16:09 +00:00
settings.setThirdSectionInfoEnabled(
thirdSectionInfoEnabled);
}
void SessionController::closeThirdSection() {
2020-06-25 12:16:09 +00:00
auto &settings = Core::App().settings();
2019-09-03 15:24:51 +00:00
auto newWindowSize = widget()->size();
auto layout = computeColumnLayout();
if (layout.windowLayout == Adaptive::WindowLayout::ThreeColumn) {
2019-09-03 15:24:51 +00:00
auto noResize = widget()->isFullScreen()
|| widget()->isMaximized();
2020-06-25 12:16:09 +00:00
auto savedValue = settings.thirdSectionExtendedBy();
auto extendedBy = (savedValue == -1)
? layout.thirdWidth
: savedValue;
auto newBodyWidth = noResize
? layout.bodyWidth
: (layout.bodyWidth - extendedBy);
2020-06-25 12:16:09 +00:00
auto currentRatio = settings.dialogsWidthRatio();
settings.setDialogsWidthRatio(
(currentRatio * layout.bodyWidth) / newBodyWidth);
newWindowSize = QSize(
2019-09-03 15:24:51 +00:00
widget()->width() + (newBodyWidth - layout.bodyWidth),
widget()->height());
}
2020-06-25 12:16:09 +00:00
settings.setTabbedSelectorSectionEnabled(false);
settings.setThirdSectionInfoEnabled(false);
Core::App().saveSettingsDelayed();
2019-09-03 15:24:51 +00:00
if (widget()->size() != newWindowSize) {
widget()->resize(newWindowSize);
} else {
updateColumnLayout();
}
}
void SessionController::showJumpToDate(Dialogs::Key chat, QDate requestedDate) {
2018-02-21 21:17:36 +00:00
const auto currentPeerDate = [&] {
if (const auto history = chat.history()) {
if (history->scrollTopItem) {
return history->scrollTopItem->dateTime().date();
2018-02-21 21:17:36 +00:00
} else if (history->loadedAtTop()
&& !history->isEmpty()
&& history->peer->migrateFrom()) {
2019-01-18 12:27:37 +00:00
if (const auto migrated = history->owner().historyLoaded(history->peer->migrateFrom())) {
if (migrated->scrollTopItem) {
// We're up in the migrated history.
// So current date is the date of first message here.
return history->blocks.front()->messages.front()->dateTime().date();
}
}
2019-01-15 11:57:45 +00:00
} else if (history->chatListTimeId() != 0) {
return base::unixtime::parse(history->chatListTimeId()).date();
}
2019-04-15 11:54:03 +00:00
//} else if (const auto feed = chat.feed()) { // #feed
// if (chatScrollPosition(feed)) { // #TODO feeds save position
2018-02-21 21:17:36 +00:00
2019-04-15 11:54:03 +00:00
// } else if (feed->chatListTimeId() != 0) {
// return base::unixtime::parse(feed->chatListTimeId()).date();
2019-04-15 11:54:03 +00:00
// }
}
2019-05-28 12:33:42 +00:00
return QDate();
}();
2018-02-21 21:17:36 +00:00
const auto maxPeerDate = [](Dialogs::Key chat) {
if (auto history = chat.history()) {
if (const auto channel = history->peer->migrateTo()) {
2019-01-18 12:27:37 +00:00
history = channel->owner().historyLoaded(channel);
2018-02-21 21:17:36 +00:00
}
2019-01-15 11:57:45 +00:00
if (history && history->chatListTimeId() != 0) {
return base::unixtime::parse(history->chatListTimeId()).date();
}
2019-04-15 11:54:03 +00:00
//} else if (const auto feed = chat.feed()) { // #feed
// if (feed->chatListTimeId() != 0) {
// return base::unixtime::parse(feed->chatListTimeId()).date();
2019-04-15 11:54:03 +00:00
// }
}
return QDate::currentDate();
};
2018-02-21 21:17:36 +00:00
const auto minPeerDate = [](Dialogs::Key chat) {
const auto startDate = [] {
// Telegram was launched in August 2013 :)
return QDate(2013, 8, 1);
};
2018-02-21 21:17:36 +00:00
if (const auto history = chat.history()) {
if (const auto chat = history->peer->migrateFrom()) {
2019-01-18 12:27:37 +00:00
if (const auto history = chat->owner().historyLoaded(chat)) {
2018-02-21 21:17:36 +00:00
if (history->loadedAtTop()) {
if (!history->isEmpty()) {
return history->blocks.front()->messages.front()->dateTime().date();
}
} else {
return startDate();
}
}
}
if (history->loadedAtTop()) {
if (!history->isEmpty()) {
return history->blocks.front()->messages.front()->dateTime().date();
}
return QDate::currentDate();
}
2019-04-15 11:54:03 +00:00
//} else if (const auto feed = chat.feed()) { // #feed
// return startDate();
}
return startDate();
};
2019-05-28 12:33:42 +00:00
const auto highlighted = !requestedDate.isNull()
? requestedDate
: !currentPeerDate.isNull()
? currentPeerDate
: QDate::currentDate();
2018-02-21 21:17:36 +00:00
const auto month = highlighted;
auto callback = [=](const QDate &date) {
2019-01-18 12:27:37 +00:00
session().api().jumpToDate(chat, date);
};
auto box = Box<CalendarBox>(
month,
highlighted,
std::move(callback));
2018-02-21 21:17:36 +00:00
box->setMinDate(minPeerDate(chat));
box->setMaxDate(maxPeerDate(chat));
box->setBeginningButton(true);
Ui::show(std::move(box));
}
void SessionController::showPassportForm(const Passport::FormRequest &request) {
_passportForm = std::make_unique<Passport::FormController>(
this,
request);
_passportForm->show();
}
void SessionController::clearPassportForm() {
_passportForm = nullptr;
}
void SessionController::updateColumnLayout() {
2020-06-10 18:08:17 +00:00
content()->updateColumnLayout();
}
void SessionController::showPeerHistory(
PeerId peerId,
const SectionShow &params,
MsgId msgId) {
2020-06-10 18:08:17 +00:00
content()->ui_showPeerHistory(
peerId,
params,
msgId);
}
void SessionController::showSection(
SectionMemento &&memento,
const SectionShow &params) {
2020-06-10 18:08:17 +00:00
if (!params.thirdColumn && widget()->showSectionInExistingLayer(
&memento,
params)) {
return;
}
2020-06-10 18:08:17 +00:00
content()->showSection(std::move(memento), params);
}
void SessionController::showBackFromStack(const SectionShow &params) {
2020-06-10 18:08:17 +00:00
content()->showBackFromStack(params);
}
void SessionController::showSpecialLayer(
2019-09-18 11:19:05 +00:00
object_ptr<Ui::LayerWidget> &&layer,
anim::type animated) {
2020-06-10 18:08:17 +00:00
widget()->showSpecialLayer(std::move(layer), animated);
}
void SessionController::removeLayerBlackout() {
2020-06-10 18:08:17 +00:00
widget()->ui_removeLayerBlackout();
}
2020-06-10 18:08:17 +00:00
not_null<MainWidget*> SessionController::content() const {
return widget()->sessionContent();
}
2020-03-03 12:07:22 +00:00
int SessionController::filtersWidth() const {
return _filters ? st::windowFiltersWidth : 0;
}
rpl::producer<FilterId> SessionController::activeChatsFilter() const {
return _activeChatsFilter.value();
}
FilterId SessionController::activeChatsFilterCurrent() const {
return _activeChatsFilter.current();
}
void SessionController::setActiveChatsFilter(FilterId id) {
if (activeChatsFilterCurrent() != id) {
resetFakeUnreadWhileOpened();
}
_activeChatsFilter.force_assign(id);
2020-03-20 13:12:13 +00:00
if (id) {
closeFolder();
}
if (Adaptive::OneColumn()) {
Ui::showChatsList(&session());
}
2020-03-03 12:07:22 +00:00
}
SessionController::~SessionController() = default;
} // namespace Window