From 0c8709ca5f87227973d71190677a1e4aa2456da8 Mon Sep 17 00:00:00 2001 From: John Preston Date: Tue, 11 Sep 2018 15:50:40 +0300 Subject: [PATCH] Replace App::self() with Auth().user(). Always have self Auth().user() when AuthSession exists. --- Telegram/Resources/langs/lang.strings | 1 - Telegram/SourceFiles/apiwrap.cpp | 38 ++++++----- Telegram/SourceFiles/apiwrap.h | 4 +- Telegram/SourceFiles/app.cpp | 22 ++----- Telegram/SourceFiles/app.h | 1 - Telegram/SourceFiles/auth_session.cpp | 13 ++-- Telegram/SourceFiles/auth_session.h | 12 ++-- .../SourceFiles/boxes/edit_caption_box.cpp | 2 +- .../boxes/peer_list_controllers.cpp | 6 +- Telegram/SourceFiles/boxes/share_box.cpp | 7 +-- Telegram/SourceFiles/boxes/username_box.cpp | 34 +++++++--- .../chat_helpers/emoji_list_widget.cpp | 2 +- Telegram/SourceFiles/data/data_peer.cpp | 16 ++--- Telegram/SourceFiles/facades.cpp | 6 +- Telegram/SourceFiles/facades.h | 2 - .../admin_log/history_admin_log_inner.cpp | 2 +- .../SourceFiles/history/history_widget.cpp | 6 +- .../view/history_view_top_bar_widget.cpp | 8 ++- Telegram/SourceFiles/intro/introwidget.cpp | 15 +++-- Telegram/SourceFiles/mainwidget.cpp | 44 ++++--------- Telegram/SourceFiles/mainwidget.h | 4 +- Telegram/SourceFiles/mainwindow.cpp | 12 ++-- Telegram/SourceFiles/mainwindow.h | 2 +- .../media/player/media_player_instance.cpp | 9 +-- Telegram/SourceFiles/mediaview.cpp | 2 +- Telegram/SourceFiles/messenger.cpp | 36 +++++++---- Telegram/SourceFiles/messenger.h | 2 +- .../old_settings/settings_cover.cpp | 2 +- .../old_settings/settings_info_widget.cpp | 4 +- .../old_settings/settings_inner_widget.cpp | 6 +- .../passport/passport_form_controller.cpp | 5 +- .../passport/passport_panel_details_row.cpp | 4 +- .../platform/mac/main_window_mac.mm | 5 +- .../profile/profile_block_group_members.cpp | 6 +- .../profile/profile_channel_controllers.cpp | 8 +-- .../settings/settings_information.cpp | 22 +++++-- .../SourceFiles/ui/widgets/input_fields.cpp | 8 ++- .../SourceFiles/window/window_controller.cpp | 13 ++-- .../SourceFiles/window/window_main_menu.cpp | 63 +++++++------------ .../SourceFiles/window/window_main_menu.h | 1 - .../SourceFiles/window/window_peer_menu.cpp | 2 +- 41 files changed, 227 insertions(+), 230 deletions(-) diff --git a/Telegram/Resources/langs/lang.strings b/Telegram/Resources/langs/lang.strings index 0f638e53b..ba52c162f 100644 --- a/Telegram/Resources/langs/lang.strings +++ b/Telegram/Resources/langs/lang.strings @@ -973,7 +973,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL "lng_media_auto_groups" = "Groups and channels"; "lng_media_auto_play" = "Autoplay"; -"lng_emoji_category0" = "Frequently used"; "lng_emoji_category1" = "People"; "lng_emoji_category2" = "Nature"; "lng_emoji_category3" = "Food & Drink"; diff --git a/Telegram/SourceFiles/apiwrap.cpp b/Telegram/SourceFiles/apiwrap.cpp index c02f64404..1f6964b63 100644 --- a/Telegram/SourceFiles/apiwrap.cpp +++ b/Telegram/SourceFiles/apiwrap.cpp @@ -557,8 +557,8 @@ void ApiWrap::requestContacts() { if (contact.type() != mtpc_contact) continue; const auto userId = contact.c_contact().vuser_id.v; - if (userId == _session->userId() && App::self()) { - App::self()->setContactStatus( + if (userId == _session->userId()) { + Auth().user()->setContactStatus( UserData::ContactStatus::Contact); } } @@ -763,7 +763,9 @@ void ApiWrap::requestFullPeer(PeerData *peer) { _fullPeerRequests.remove(peer); }; if (auto user = peer->asUser()) { - return request(MTPusers_GetFullUser(user->inputUser)).done([this, user](const MTPUserFull &result, mtpRequestId requestId) { + return request(MTPusers_GetFullUser( + user->inputUser + )).done([this, user](const MTPUserFull &result, mtpRequestId requestId) { gotUserFull(user, result, requestId); }).fail(failHandler).send(); } else if (auto chat = peer->asChat()) { @@ -946,6 +948,13 @@ void ApiWrap::gotChatFull(PeerData *peer, const MTPmessages_ChatFull &result, mt void ApiWrap::gotUserFull(UserData *user, const MTPUserFull &result, mtpRequestId req) { auto &d = result.c_userFull(); + if (user == _session->user() && !_session->validateSelf(d.vuser)) { + constexpr auto kRequestUserAgainTimeout = TimeMs(10000); + App::CallDelayed(kRequestUserAgainTimeout, _session, [=] { + requestFullPeer(user); + }); + return; + } App::feedUsers(MTP_vector(1, d.vuser)); if (d.has_profile_photo()) { _session->data().photo(d.vprofile_photo); @@ -1394,7 +1403,7 @@ void ApiWrap::requestSelfParticipant(ChannelData *channel) { channel->inviter = _session->userId(); channel->inviteDate = channel->date; if (channel->mgInfo) { - channel->mgInfo->creator = App::self(); + channel->mgInfo->creator = Auth().user(); } } break; case mtpc_channelParticipantAdmin: { @@ -2006,14 +2015,15 @@ void ApiWrap::updatePrivacyLastSeens(const QVector &rules) { if (_contactsStatusesRequestId) { request(_contactsStatusesRequestId).cancel(); } - _contactsStatusesRequestId = request(MTPcontacts_GetStatuses()).done([this](const MTPVector &result) { + _contactsStatusesRequestId = request(MTPcontacts_GetStatuses( + )).done([=](const MTPVector &result) { _contactsStatusesRequestId = 0; for_const (auto &item, result.v) { Assert(item.type() == mtpc_contactStatus); auto &data = item.c_contactStatus(); if (auto user = App::userLoaded(data.vuser_id.v)) { auto oldOnlineTill = user->onlineTill; - auto newOnlineTill = onlineTillFromStatus(data.vstatus, oldOnlineTill); + auto newOnlineTill = OnlineTillFromStatus(data.vstatus, oldOnlineTill); if (oldOnlineTill != newOnlineTill) { user->onlineTill = newOnlineTill; Notify::peerUpdatedDelayed(user, Notify::PeerUpdate::Flag::UserOnlineChanged); @@ -2025,10 +2035,14 @@ void ApiWrap::updatePrivacyLastSeens(const QVector &rules) { }).send(); } -int ApiWrap::onlineTillFromStatus(const MTPUserStatus &status, int currentOnlineTill) { +int ApiWrap::OnlineTillFromStatus( + const MTPUserStatus &status, + int currentOnlineTill) { switch (status.type()) { case mtpc_userStatusEmpty: return 0; - case mtpc_userStatusRecently: return (currentOnlineTill > -10) ? -2 : currentOnlineTill; // don't modify pseudo-online + case mtpc_userStatusRecently: + // Don't modify pseudo-online. + return (currentOnlineTill > -10) ? -2 : currentOnlineTill; case mtpc_userStatusLastWeek: return -3; case mtpc_userStatusLastMonth: return -4; case mtpc_userStatusOffline: return status.c_userStatusOffline().vwas_online.v; @@ -4892,11 +4906,7 @@ void ApiWrap::photoUploadReady( } void ApiWrap::clearPeerPhoto(not_null photo) { - const auto self = App::self(); - if (!self) { - return; - } - + const auto self = Auth().user(); if (self->userpicPhotoId() == photo->id) { request(MTPphotos_UpdateProfilePhoto( MTP_inputPhotoEmpty() @@ -5005,7 +5015,7 @@ void ApiWrap::saveSelfBio(const QString &text, FnMut done) { _saveBioRequestId = 0; App::feedUsers(MTP_vector(1, result)); - App::self()->setAbout(_saveBioText); + Auth().user()->setAbout(_saveBioText); if (_saveBioDone) { _saveBioDone(); } diff --git a/Telegram/SourceFiles/apiwrap.h b/Telegram/SourceFiles/apiwrap.h index 7d4e9c95b..ecee3efac 100644 --- a/Telegram/SourceFiles/apiwrap.h +++ b/Telegram/SourceFiles/apiwrap.h @@ -182,7 +182,9 @@ public: void savePrivacy(const MTPInputPrivacyKey &key, QVector &&rules); void handlePrivacyChange(mtpTypeId keyTypeId, const MTPVector &rules); - int onlineTillFromStatus(const MTPUserStatus &status, int currentOnlineTill); + static int OnlineTillFromStatus( + const MTPUserStatus &status, + int currentOnlineTill); void clearHistory(not_null peer); diff --git a/Telegram/SourceFiles/app.cpp b/Telegram/SourceFiles/app.cpp index 053b11bde..ce7af1bf9 100644 --- a/Telegram/SourceFiles/app.cpp +++ b/Telegram/SourceFiles/app.cpp @@ -49,8 +49,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL namespace { App::LaunchState _launchState = App::Launched; - UserData *self = nullptr; - std::unordered_map> peersData; using LocationsData = QHash; @@ -309,10 +307,6 @@ namespace App { : data->phone().isEmpty() ? UserData::ContactStatus::PhoneUnknown : UserData::ContactStatus::CanAdd); - if (d.is_self() && ::self != data) { - ::self = data; - Global::RefSelfChanged().notify(); - } } if (canShareThisContact != data->canShareThisContactFast()) { @@ -334,8 +328,10 @@ namespace App { } if (status && !minimal) { - auto oldOnlineTill = data->onlineTill; - auto newOnlineTill = Auth().api().onlineTillFromStatus(*status, oldOnlineTill); + const auto oldOnlineTill = data->onlineTill; + const auto newOnlineTill = ApiWrap::OnlineTillFromStatus( + *status, + oldOnlineTill); if (oldOnlineTill != newOnlineTill) { data->onlineTill = newOnlineTill; update.flags |= UpdateFlag::UserOnlineChanged; @@ -344,7 +340,7 @@ namespace App { if (data->contactStatus() == UserData::ContactStatus::PhoneUnknown && !data->phone().isEmpty() - && data->id != Auth().userPeerId()) { + && !data->isSelf()) { data->setContactStatus(UserData::ContactStatus::CanAdd); } if (App::main()) { @@ -918,7 +914,7 @@ namespace App { } void checkSavedGif(HistoryItem *item) { - if (!item->Has() && (item->out() || item->history()->peer == App::self())) { + if (!item->Has() && (item->out() || item->history()->peer == Auth().user())) { if (const auto media = item->media()) { if (const auto document = media->document()) { if (document->isGifv()) { @@ -1153,10 +1149,6 @@ namespace App { } } - UserData *self() { - return ::self; - } - PeerData *peerByName(const QString &username) { const auto uname = username.trimmed(); for (const auto &[peerId, peer] : peersData) { @@ -1294,8 +1286,6 @@ namespace App { cSetAutoDownloadPhoto(0); cSetAutoDownloadAudio(0); cSetAutoDownloadGif(0); - ::self = nullptr; - Global::RefSelfChanged().notify(true); } void historyRegDependency(HistoryItem *dependent, HistoryItem *dependency) { diff --git a/Telegram/SourceFiles/app.h b/Telegram/SourceFiles/app.h index 4f7292618..d9a5517bf 100644 --- a/Telegram/SourceFiles/app.h +++ b/Telegram/SourceFiles/app.h @@ -135,7 +135,6 @@ namespace App { void enumerateChatsChannels( Fn)> action); - UserData *self(); PeerData *peerByName(const QString &username); QString peerName(const PeerData *peer, bool forDialogs = false); diff --git a/Telegram/SourceFiles/auth_session.cpp b/Telegram/SourceFiles/auth_session.cpp index 1fda773cf..443f85373 100644 --- a/Telegram/SourceFiles/auth_session.cpp +++ b/Telegram/SourceFiles/auth_session.cpp @@ -265,8 +265,8 @@ AuthSession &Auth() { return *result; } -AuthSession::AuthSession(UserId userId) -: _userId(userId) +AuthSession::AuthSession(const MTPUser &user) +: _user(App::user(user.match([](const auto &data) { return data.vid.v; }))) , _autoLockTimer([this] { checkAutoLock(); }) , _api(std::make_unique(this)) , _calls(std::make_unique()) @@ -276,7 +276,7 @@ AuthSession::AuthSession(UserId userId) , _notifications(std::make_unique(this)) , _data(std::make_unique(this)) , _changelogs(Core::Changelogs::Create(this)) { - Expects(_userId != 0); + App::feedUser(user); _saveDataTimer.setCallback([=] { Local::writeUserSettings(); @@ -294,21 +294,18 @@ AuthSession::AuthSession(UserId userId) }); _api->refreshProxyPromotion(); _api->requestTermsUpdate(); + _api->requestFullPeer(_user); Window::Theme::Background()->start(); } bool AuthSession::Exists() { - if (auto messenger = Messenger::InstancePointer()) { + if (const auto messenger = Messenger::InstancePointer()) { return (messenger->authSession() != nullptr); } return false; } -UserData *AuthSession::user() const { - return App::user(userId()); -} - base::Observable &AuthSession::downloaderTaskFinished() { return downloader().taskFinished(); } diff --git a/Telegram/SourceFiles/auth_session.h b/Telegram/SourceFiles/auth_session.h index e04e16ce7..4acc88573 100644 --- a/Telegram/SourceFiles/auth_session.h +++ b/Telegram/SourceFiles/auth_session.h @@ -186,7 +186,7 @@ class AuthSession final : public base::has_weak_ptr , private base::Subscriber { public: - AuthSession(UserId userId); + AuthSession(const MTPUser &user); AuthSession(const AuthSession &other) = delete; AuthSession &operator=(const AuthSession &other) = delete; @@ -194,12 +194,14 @@ public: static bool Exists(); UserId userId() const { - return _userId; + return _user->bareId(); } PeerId userPeerId() const { - return peerFromUser(userId()); + return _user->id; + } + not_null user() const { + return _user; } - UserData *user() const; bool validateSelf(const MTPUser &user); Storage::Downloader &downloader() { @@ -249,7 +251,7 @@ public: private: static constexpr auto kDefaultSaveDelay = TimeMs(1000); - const UserId _userId = 0; + const not_null _user; AuthSessionSettings _settings; base::Timer _saveDataTimer; diff --git a/Telegram/SourceFiles/boxes/edit_caption_box.cpp b/Telegram/SourceFiles/boxes/edit_caption_box.cpp index 71dfb8d76..430e56821 100644 --- a/Telegram/SourceFiles/boxes/edit_caption_box.cpp +++ b/Telegram/SourceFiles/boxes/edit_caption_box.cpp @@ -416,7 +416,7 @@ void EditCaptionBox::save() { }; const auto prepareFlags = Ui::ItemTextOptions( item->history(), - App::self()).flags; + Auth().user()).flags; TextUtilities::PrepareForSending(sending, prepareFlags); TextUtilities::Trim(sending); diff --git a/Telegram/SourceFiles/boxes/peer_list_controllers.cpp b/Telegram/SourceFiles/boxes/peer_list_controllers.cpp index f87db0167..1ff476539 100644 --- a/Telegram/SourceFiles/boxes/peer_list_controllers.cpp +++ b/Telegram/SourceFiles/boxes/peer_list_controllers.cpp @@ -263,10 +263,8 @@ void ChatsListBoxController::rebuildRows() { }; auto added = 0; if (respectSavedMessagesChat()) { - if (auto self = App::self()) { - if (appendRow(App::history(self))) { - ++added; - } + if (appendRow(App::history(Auth().user()))) { + ++added; } } added += appendList(App::main()->dialogsList()); diff --git a/Telegram/SourceFiles/boxes/share_box.cpp b/Telegram/SourceFiles/boxes/share_box.cpp index 920107bfd..2b01973d3 100644 --- a/Telegram/SourceFiles/boxes/share_box.cpp +++ b/Telegram/SourceFiles/boxes/share_box.cpp @@ -294,10 +294,9 @@ ShareBox::Inner::Inner(QWidget *parent, ShareBox::FilterCallback &&filterCallbac setAttribute(Qt::WA_OpaquePaintEvent); const auto dialogs = App::main()->dialogsList(); - if (const auto self = App::self()) { - if (_filterCallback(App::self())) { - _chatsIndexed->addToEnd(App::history(self)); - } + const auto self = Auth().user(); + if (_filterCallback(self)) { + _chatsIndexed->addToEnd(App::history(self)); } for (const auto row : dialogs->all()) { if (const auto history = row->history()) { diff --git a/Telegram/SourceFiles/boxes/username_box.cpp b/Telegram/SourceFiles/boxes/username_box.cpp index 45eb821b5..e94347319 100644 --- a/Telegram/SourceFiles/boxes/username_box.cpp +++ b/Telegram/SourceFiles/boxes/username_box.cpp @@ -16,6 +16,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/toast/toast.h" #include "styles/style_boxes.h" #include "messenger.h" +#include "auth_session.h" namespace { @@ -24,14 +25,21 @@ constexpr auto kMinUsernameLength = 5; } // namespace UsernameBox::UsernameBox(QWidget*) -: _username(this, st::defaultInputField, [] { return qsl("@username"); }, App::self()->username, false) +: _username( + this, + st::defaultInputField, + [] { return qsl("@username"); }, + Auth().user()->username, + false) , _link(this, QString(), st::boxLinkButton) , _about(st::boxWidth - st::usernamePadding.left()) , _checkTimer(this) { } void UsernameBox::prepare() { - _goodText = App::self()->username.isEmpty() ? QString() : lang(lng_username_available); + _goodText = Auth().user()->username.isEmpty() + ? QString() + : lang(lng_username_available); setTitle(langFactory(lng_username_title)); @@ -170,9 +178,14 @@ bool UsernameBox::onUpdateFail(const RPCError &error) { if (MTP::isDefaultHandledError(error)) return false; _saveRequestId = 0; - QString err(error.type()); - if (err == qstr("USERNAME_NOT_MODIFIED") || _sentUsername == App::self()->username) { - App::self()->setName(TextUtilities::SingleLine(App::self()->firstName), TextUtilities::SingleLine(App::self()->lastName), TextUtilities::SingleLine(App::self()->nameOrPhone), TextUtilities::SingleLine(_sentUsername)); + const auto self = Auth().user(); + const auto err = error.type(); + if (err == qstr("USERNAME_NOT_MODIFIED") || _sentUsername == self->username) { + self->setName( + TextUtilities::SingleLine(self->firstName), + TextUtilities::SingleLine(self->lastName), + TextUtilities::SingleLine(self->nameOrPhone), + TextUtilities::SingleLine(_sentUsername)); closeBox(); return true; } else if (err == qstr("USERNAME_INVALID")) { @@ -194,8 +207,13 @@ bool UsernameBox::onUpdateFail(const RPCError &error) { void UsernameBox::onCheckDone(const MTPBool &result) { _checkRequestId = 0; - QString newError = (mtpIsTrue(result) || _checkUsername == App::self()->username) ? QString() : lang(lng_username_occupied); - QString newGood = newError.isEmpty() ? lang(lng_username_available) : QString(); + const auto newError = (mtpIsTrue(result) + || _checkUsername == Auth().user()->username) + ? QString() + : lang(lng_username_occupied); + const auto newGood = newError.isEmpty() + ? lang(lng_username_available) + : QString(); if (_errorText != newError || _goodText != newGood) { _errorText = newError; _goodText = newGood; @@ -212,7 +230,7 @@ bool UsernameBox::onCheckFail(const RPCError &error) { _errorText = lang(lng_username_invalid); update(); return true; - } else if (err == qstr("USERNAME_OCCUPIED") && _checkUsername != App::self()->username) { + } else if (err == qstr("USERNAME_OCCUPIED") && _checkUsername != Auth().user()->username) { _errorText = lang(lng_username_occupied); update(); return true; diff --git a/Telegram/SourceFiles/chat_helpers/emoji_list_widget.cpp b/Telegram/SourceFiles/chat_helpers/emoji_list_widget.cpp index 857c3f326..1475bfda9 100644 --- a/Telegram/SourceFiles/chat_helpers/emoji_list_widget.cpp +++ b/Telegram/SourceFiles/chat_helpers/emoji_list_widget.cpp @@ -463,7 +463,7 @@ void EmojiListWidget::paintEvent(QPaintEvent *e) { if (info.section > 0 && r.top() < info.rowsTop) { p.setFont(st::emojiPanHeaderFont); p.setPen(st::emojiPanHeaderFg); - p.drawTextLeft(st::emojiPanHeaderLeft - st::buttonRadius, info.top + st::emojiPanHeaderTop, width(), lang(LangKey(lng_emoji_category0 + info.section))); + p.drawTextLeft(st::emojiPanHeaderLeft - st::buttonRadius, info.top + st::emojiPanHeaderTop, width(), lang(LangKey(lng_emoji_category1 + info.section - 1))); } if (r.top() + r.height() > info.rowsTop) { ensureLoaded(info.section); diff --git a/Telegram/SourceFiles/data/data_peer.cpp b/Telegram/SourceFiles/data/data_peer.cpp index 5dfe78101..ef130866b 100644 --- a/Telegram/SourceFiles/data/data_peer.cpp +++ b/Telegram/SourceFiles/data/data_peer.cpp @@ -437,8 +437,6 @@ void UserData::setName(const QString &newFirstName, const QString &newLastName, void UserData::setPhone(const QString &newPhone) { if (_phone != newPhone) { _phone = newPhone; - if (bareId() == Auth().userId()) { - } } } @@ -1042,15 +1040,16 @@ void ChannelData::setAdminRights(const MTPChannelAdminRights &rights) { } _adminRights.set(rights.c_channelAdminRights().vflags.v); if (isMegagroup()) { + const auto self = Auth().user(); if (hasAdminRights()) { if (!amCreator()) { auto me = MegagroupInfo::Admin { rights }; me.canEdit = false; - mgInfo->lastAdmins.emplace(App::self(), me); + mgInfo->lastAdmins.emplace(self, me); } - mgInfo->lastRestricted.remove(App::self()); + mgInfo->lastRestricted.remove(self); } else { - mgInfo->lastAdmins.remove(App::self()); + mgInfo->lastAdmins.remove(self); } auto amAdmin = hasAdminRights() || amCreator(); @@ -1067,15 +1066,16 @@ void ChannelData::setRestrictedRights(const MTPChannelBannedRights &rights) { _restrictedUntill = rights.c_channelBannedRights().vuntil_date.v; _restrictions.set(rights.c_channelBannedRights().vflags.v); if (isMegagroup()) { + const auto self = Auth().user(); if (hasRestrictions()) { if (!amCreator()) { auto me = MegagroupInfo::Restricted { rights }; - mgInfo->lastRestricted.emplace(App::self(), me); + mgInfo->lastRestricted.emplace(self, me); } - mgInfo->lastAdmins.remove(App::self()); + mgInfo->lastAdmins.remove(self); Data::ChannelAdminChanges(this).feed(Auth().userId(), false); } else { - mgInfo->lastRestricted.remove(App::self()); + mgInfo->lastRestricted.remove(self); } } Notify::peerUpdatedDelayed(this, UpdateFlag::ChannelRightsChanged | UpdateFlag::AdminsChanged | UpdateFlag::BannedUsersChanged); diff --git a/Telegram/SourceFiles/facades.cpp b/Telegram/SourceFiles/facades.cpp index 2300b76aa..c63ee1f7a 100644 --- a/Telegram/SourceFiles/facades.cpp +++ b/Telegram/SourceFiles/facades.cpp @@ -119,7 +119,7 @@ void activateBotCommand( Ui::showPeerHistory(history, ShowAtTheEndMsgId); auto options = ApiWrap::SendOptions(history); options.replyTo = msgId; - Auth().api().shareContact(App::self(), options); + Auth().api().shareContact(Auth().user(), options); })); } break; @@ -551,8 +551,6 @@ struct Data { CircleMasksMap CircleMasks; - base::Observable SelfChanged; - bool AskDownloadPath = false; QString DownloadPath; QByteArray DownloadPathBookmark; @@ -681,8 +679,6 @@ DefineVar(Global, Stickers::Order, ArchivedStickerSetsOrder); DefineRefVar(Global, CircleMasksMap, CircleMasks); -DefineRefVar(Global, base::Observable, SelfChanged); - DefineVar(Global, bool, AskDownloadPath); DefineVar(Global, QString, DownloadPath); DefineVar(Global, QByteArray, DownloadPathBookmark); diff --git a/Telegram/SourceFiles/facades.h b/Telegram/SourceFiles/facades.h index 637dc42d4..847124d47 100644 --- a/Telegram/SourceFiles/facades.h +++ b/Telegram/SourceFiles/facades.h @@ -292,8 +292,6 @@ DeclareVar(HiddenPinnedMessagesMap, HiddenPinnedMessages); typedef QMap CircleMasksMap; DeclareRefVar(CircleMasksMap, CircleMasks); -DeclareRefVar(base::Observable, SelfChanged); - DeclareVar(bool, AskDownloadPath); DeclareVar(QString, DownloadPath); DeclareVar(QByteArray, DownloadPathBookmark); diff --git a/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp b/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp index 17ba44044..82dd04c93 100644 --- a/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp +++ b/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp @@ -411,7 +411,7 @@ void InnerWidget::requestAdmins() { } }); if (_admins.empty()) { - _admins.push_back(App::self()); + _admins.push_back(Auth().user()); } if (_showFilterCallback) { showFilter(std::move(_showFilterCallback)); diff --git a/Telegram/SourceFiles/history/history_widget.cpp b/Telegram/SourceFiles/history/history_widget.cpp index 5950f36d3..187b39968 100644 --- a/Telegram/SourceFiles/history/history_widget.cpp +++ b/Telegram/SourceFiles/history/history_widget.cpp @@ -2916,7 +2916,9 @@ void HistoryWidget::saveEditMsg() { : WebPageId(0)); const auto textWithTags = _field->getTextWithAppliedMarkdown(); - const auto prepareFlags = Ui::ItemTextOptions(_history, App::self()).flags; + const auto prepareFlags = Ui::ItemTextOptions( + _history, + Auth().user()).flags; auto sending = TextWithEntities(); auto left = TextWithEntities { textWithTags.text, ConvertTextTagsToEntities(textWithTags.tags) }; TextUtilities::PrepareForSending(left, prepareFlags); @@ -4448,7 +4450,7 @@ void HistoryWidget::sendFileConfirmed( }; const auto prepareFlags = Ui::ItemTextOptions( history, - App::self()).flags; + Auth().user()).flags; TextUtilities::PrepareForSending(caption, prepareFlags); TextUtilities::Trim(caption); auto localEntities = TextUtilities::EntitiesToMTP(caption.entities); diff --git a/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp b/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp index 527ee50de..a765c6311 100644 --- a/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp +++ b/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp @@ -760,12 +760,13 @@ void TopBarWidget::updateOnlineDisplay() { text = lng_chat_status_members(lt_count, chat->count); } } else { + const auto self = Auth().user(); auto online = 0; auto onlyMe = true; for (auto [user, v] : chat->participants) { if (user->onlineTill > now) { ++online; - if (onlyMe && user != App::self()) onlyMe = false; + if (onlyMe && user != self) onlyMe = false; } } if (online > 0 && !onlyMe) { @@ -783,12 +784,13 @@ void TopBarWidget::updateOnlineDisplay() { if (channel->mgInfo->lastParticipants.empty() || channel->lastParticipantsCountOutdated()) { Auth().api().requestLastParticipants(channel); } + const auto self = Auth().user(); auto online = 0; - bool onlyMe = true; + auto onlyMe = true; for (auto &participant : std::as_const(channel->mgInfo->lastParticipants)) { if (participant->onlineTill > now) { ++online; - if (onlyMe && participant != App::self()) { + if (onlyMe && participant != self) { onlyMe = false; } } diff --git a/Telegram/SourceFiles/intro/introwidget.cpp b/Telegram/SourceFiles/intro/introwidget.cpp index 4616e6c37..65c296d01 100644 --- a/Telegram/SourceFiles/intro/introwidget.cpp +++ b/Telegram/SourceFiles/intro/introwidget.cpp @@ -594,7 +594,9 @@ QString Widget::Step::nextButtonText() const { } void Widget::Step::finish(const MTPUser &user, QImage &&photo) { - if (user.type() != mtpc_user || !user.c_user().is_self()) { + if (user.type() != mtpc_user + || !user.c_user().is_self() + || !user.c_user().vid.v) { // No idea what to do here. // We could've reset intro and MTP, but this really should not happen. Ui::show(Box("Internal error: bad user.is_self() after sign in.")); @@ -610,16 +612,13 @@ void Widget::Step::finish(const MTPUser &user, QImage &&photo) { Local::writeLangPack(); } - Messenger::Instance().authSessionCreate(user.c_user().vid.v); + Messenger::Instance().authSessionCreate(user); Local::writeMtpData(); - App::wnd()->setupMain(&user); + App::wnd()->setupMain(); // "this" is already deleted here by creating the main widget. - if (const auto user = App::self()) { - Auth().api().requestFullPeer(user); - if (!photo.isNull()) { - Auth().api().uploadPeerPhoto(user, std::move(photo)); - } + if (AuthSession::Exists() && !photo.isNull()) { + Auth().api().uploadPeerPhoto(Auth().user(), std::move(photo)); } } diff --git a/Telegram/SourceFiles/mainwidget.cpp b/Telegram/SourceFiles/mainwidget.cpp index 95113f071..4f420e465 100644 --- a/Telegram/SourceFiles/mainwidget.cpp +++ b/Telegram/SourceFiles/mainwidget.cpp @@ -1112,7 +1112,12 @@ void MainWidget::deleteConversation( void MainWidget::deleteAndExit(ChatData *chat) { PeerData *peer = chat; - MTP::send(MTPmessages_DeleteChatUser(chat->inputChat, App::self()->inputUser), rpcDone(&MainWidget::deleteHistoryAfterLeave, peer), rpcFail(&MainWidget::leaveChatFailed, peer)); + MTP::send( + MTPmessages_DeleteChatUser( + chat->inputChat, + Auth().user()->inputUser), + rpcDone(&MainWidget::deleteHistoryAfterLeave, peer), + rpcFail(&MainWidget::leaveChatFailed, peer)); } void MainWidget::addParticipants( @@ -3647,26 +3652,13 @@ void MainWidget::mtpPing() { MTP::ping(); } -void MainWidget::start(const MTPUser *self) { +void MainWidget::start() { Auth().api().requestNotifySettings(MTP_inputNotifyUsers()); Auth().api().requestNotifySettings(MTP_inputNotifyChats()); - if (!self) { - MTP::send(MTPusers_GetFullUser(MTP_inputUserSelf()), rpcDone(&MainWidget::startWithSelf)); - return; - } else if (!Auth().validateSelf(*self)) { - constexpr auto kRequestUserAgainTimeout = TimeMs(10000); - App::CallDelayed(kRequestUserAgainTimeout, this, [=] { - MTP::send(MTPusers_GetFullUser(MTP_inputUserSelf()), rpcDone(&MainWidget::startWithSelf)); - }); - return; - } - Local::readSavedPeers(); cSetOtherOnline(0); - if (const auto user = App::feedUsers(MTP_vector(1, *self))) { - user->loadUserpic(); - } + Auth().user()->loadUserpic(); MTP::send(MTPupdates_GetState(), rpcDone(&MainWidget::gotState)); update(); @@ -3938,15 +3930,6 @@ bool MainWidget::inviteImportFail(const RPCError &error) { return true; } -void MainWidget::startWithSelf(const MTPUserFull &result) { - Expects(result.type() == mtpc_userFull); - auto &d = result.c_userFull(); - start(&d.vuser); - if (auto user = App::self()) { - Auth().api().processFullPeer(user, result); - } -} - void MainWidget::incrementSticker(DocumentData *sticker) { if (!sticker || !sticker->sticker()) return; if (sticker->sticker()->set.type() == mtpc_inputStickerSetEmpty) return; @@ -4145,12 +4128,11 @@ void MainWidget::updateOnline(bool gotOtherOffline) { _lastSetOnline = ms; _onlineRequest = MTP::send(MTPaccount_UpdateStatus(MTP_bool(!isOnline))); - if (App::self()) { - App::self()->onlineTill = unixtime() + (isOnline ? (Global::OnlineUpdatePeriod() / 1000) : -1); - Notify::peerUpdatedDelayed( - App::self(), - Notify::PeerUpdate::Flag::UserOnlineChanged); - } + const auto self = Auth().user(); + self->onlineTill = unixtime() + (isOnline ? (Global::OnlineUpdatePeriod() / 1000) : -1); + Notify::peerUpdatedDelayed( + self, + Notify::PeerUpdate::Flag::UserOnlineChanged); if (!isOnline) { // Went offline, so we need to save message draft to the cloud. saveDraftToCloud(); } diff --git a/Telegram/SourceFiles/mainwidget.h b/Telegram/SourceFiles/mainwidget.h index ebe6d3714..7372ff4a7 100644 --- a/Telegram/SourceFiles/mainwidget.h +++ b/Telegram/SourceFiles/mainwidget.h @@ -95,7 +95,7 @@ public: void showAnimated(const QPixmap &bgAnimCache, bool back = false); - void start(const MTPUser *self = nullptr); + void start(); void openPeerByName( const QString &name, @@ -443,8 +443,6 @@ private: Window::SectionSlideParams prepareHistoryAnimation(PeerId historyPeerId); Window::SectionSlideParams prepareDialogsAnimation(); - void startWithSelf(const MTPUserFull &user); - void saveSectionInStack(); void getChannelDifference(ChannelData *channel, ChannelDifferenceRequest from = ChannelDifferenceRequest::Unknown); diff --git a/Telegram/SourceFiles/mainwindow.cpp b/Telegram/SourceFiles/mainwindow.cpp index 43247e816..7ad7ce1d3 100644 --- a/Telegram/SourceFiles/mainwindow.cpp +++ b/Telegram/SourceFiles/mainwindow.cpp @@ -79,7 +79,9 @@ MainWindow::MainWindow() { setLocale(QLocale(QLocale::English, QLocale::UnitedStates)); - subscribe(Global::RefSelfChanged(), [this] { updateGlobalMenu(); }); + subscribe(Messenger::Instance().authSessionChanged(), [this] { + updateGlobalMenu(); + }); subscribe(Window::Theme::Background(), [this](const Window::Theme::BackgroundUpdate &data) { themeUpdated(data); }); @@ -277,7 +279,7 @@ void MainWindow::sendServiceHistoryRequest() { _main->rpcFail(&MainWidget::serviceHistoryFail)); } -void MainWindow::setupMain(const MTPUser *self) { +void MainWindow::setupMain() { Expects(AuthSession::Exists()); auto animated = (_intro || _passcodeLock); @@ -294,7 +296,7 @@ void MainWindow::setupMain(const MTPUser *self) { } else { _main->activate(); } - _main->start(self); + _main->start(); fixOrder(); } @@ -606,7 +608,7 @@ void MainWindow::updateTrayMenu(bool force) { void MainWindow::onShowAddContact() { if (isHidden()) showFromTray(); - if (App::self()) { + if (AuthSession::Exists()) { Ui::show(Box(), LayerOption::KeepOther); } } @@ -614,7 +616,7 @@ void MainWindow::onShowAddContact() { void MainWindow::onShowNewGroup() { if (isHidden()) showFromTray(); - if (App::self()) { + if (AuthSession::Exists()) { Ui::show( Box(CreatingGroupGroup, false), LayerOption::KeepOther); diff --git a/Telegram/SourceFiles/mainwindow.h b/Telegram/SourceFiles/mainwindow.h index 4820efc52..dc4171dcb 100644 --- a/Telegram/SourceFiles/mainwindow.h +++ b/Telegram/SourceFiles/mainwindow.h @@ -52,7 +52,7 @@ public: void setupPasscodeLock(); void clearPasscodeLock(); void setupIntro(); - void setupMain(const MTPUser *user = nullptr); + void setupMain(); void serviceNotification(const TextWithEntities &message, const MTPMessageMedia &media = MTP_messageMediaEmpty(), int32 date = 0, bool force = false); void sendServiceHistoryRequest(); void showDelayedServiceMsgs(); diff --git a/Telegram/SourceFiles/media/player/media_player_instance.cpp b/Telegram/SourceFiles/media/player/media_player_instance.cpp index 6dd72090a..9712ecf13 100644 --- a/Telegram/SourceFiles/media/player/media_player_instance.cpp +++ b/Telegram/SourceFiles/media/player/media_player_instance.cpp @@ -54,11 +54,6 @@ Instance::Instance() subscribe(Media::Player::Updated(), [this](const AudioMsgId &audioId) { handleSongUpdate(audioId); }); - subscribe(Global::RefSelfChanged(), [this] { - if (!App::self()) { - handleLogout(); - } - }); // While we have one Media::Player::Instance for all authsessions we have to do this. auto handleAuthSessionChange = [this] { @@ -69,9 +64,11 @@ Instance::Instance() pause(AudioMsgId::Type::Song); } }); + } else { + handleLogout(); } }; - subscribe(Messenger::Instance().authSessionChanged(), [handleAuthSessionChange] { + subscribe(Messenger::Instance().authSessionChanged(), [=] { handleAuthSessionChange(); }); handleAuthSessionChange(); diff --git a/Telegram/SourceFiles/mediaview.cpp b/Telegram/SourceFiles/mediaview.cpp index 574719ef6..6712d25d0 100644 --- a/Telegram/SourceFiles/mediaview.cpp +++ b/Telegram/SourceFiles/mediaview.cpp @@ -442,7 +442,7 @@ void MediaView::updateActions() { auto canDelete = [&] { if (_canDeleteItem) { return true; - } else if (!_msgid && _photo && App::self() && _user == App::self()) { + } else if (!_msgid && _photo && _user && _user == Auth().user()) { return _userPhotosData && _fullIndex && _fullCount; } else if (_photo && _photo->peer && _photo->peer->userpicPhotoId() == _photo->id) { if (auto chat = _photo->peer->asChat()) { diff --git a/Telegram/SourceFiles/messenger.cpp b/Telegram/SourceFiles/messenger.cpp index 1a1961dd3..a80e49a30 100644 --- a/Telegram/SourceFiles/messenger.cpp +++ b/Telegram/SourceFiles/messenger.cpp @@ -66,6 +66,7 @@ Messenger *Messenger::InstancePointer() { struct Messenger::Private { UserId authSessionUserId = 0; + QByteArray authSessionUserSerialized; std::unique_ptr storedAuthSession; MTP::Instance::Config mtpConfig; MTP::AuthKeysList mtpKeysToDestroy; @@ -454,7 +455,21 @@ void Messenger::startMtp() { } if (_private->authSessionUserId) { - authSessionCreate(base::take(_private->authSessionUserId)); + authSessionCreate(MTP_user( + MTP_flags(MTPDuser::Flag::f_self), + MTP_int(base::take(_private->authSessionUserId)), + MTPlong(), // access_hash + MTPstring(), // first_name + MTPstring(), // last_name + MTPstring(), // username + MTPstring(), // phone + MTPUserProfilePhoto(), + MTPUserStatus(), + MTPint(), // bot_info_version + MTPstring(), // restriction_reason + MTPstring(), // bot_inline_placeholder + MTPstring())); // lang_code + //Local::readUser(base::take(_private->authSessionUserSerialized)); } if (_private->storedAuthSession) { if (_authSession) { @@ -538,15 +553,8 @@ void Messenger::startLocalStorage() { }); subscribe(authSessionChanged(), [this] { InvokeQueued(this, [this] { - if (_mtproto) { - _mtproto->requestConfig(); - } - }); - }); - subscribe(Global::RefSelfChanged(), [=] { - InvokeQueued(this, [=] { - const auto phone = App::self() - ? App::self()->phone() + const auto phone = AuthSession::Exists() + ? Auth().user()->phone() : QString(); if (cLoggedPhoneNumber() != phone) { cSetLoggedPhoneNumber(phone); @@ -555,6 +563,9 @@ void Messenger::startLocalStorage() { } Local::writeSettings(); } + if (_mtproto) { + _mtproto->requestConfig(); + } }); }); } @@ -689,10 +700,10 @@ void Messenger::onSwitchTestMode() { App::restart(); } -void Messenger::authSessionCreate(UserId userId) { +void Messenger::authSessionCreate(const MTPUser &user) { Expects(_mtproto != nullptr); - _authSession = std::make_unique(userId); + _authSession = std::make_unique(user); authSessionChanged().notify(true); } @@ -702,6 +713,7 @@ void Messenger::authSessionDestroy() { _authSession.reset(); _private->storedAuthSession.reset(); _private->authSessionUserId = 0; + _private->authSessionUserSerialized = {}; authSessionChanged().notify(true); } diff --git a/Telegram/SourceFiles/messenger.h b/Telegram/SourceFiles/messenger.h index 926573e09..fa8d6ea50 100644 --- a/Telegram/SourceFiles/messenger.h +++ b/Telegram/SourceFiles/messenger.h @@ -144,7 +144,7 @@ public: Lang::CloudManager *langCloudManager() { return _langCloudManager.get(); } - void authSessionCreate(UserId userId); + void authSessionCreate(const MTPUser &user); base::Observable &authSessionChanged() { return _authSessionChanged; } diff --git a/Telegram/SourceFiles/old_settings/settings_cover.cpp b/Telegram/SourceFiles/old_settings/settings_cover.cpp index 6af6081e5..044dc0a27 100644 --- a/Telegram/SourceFiles/old_settings/settings_cover.cpp +++ b/Telegram/SourceFiles/old_settings/settings_cover.cpp @@ -30,7 +30,7 @@ namespace OldSettings { CoverWidget::CoverWidget(QWidget *parent, UserData *self) : BlockWidget(parent, self, QString()) -, _self(App::self()) +, _self(self) , _userpicButton( this, App::wnd()->controller(), diff --git a/Telegram/SourceFiles/old_settings/settings_info_widget.cpp b/Telegram/SourceFiles/old_settings/settings_info_widget.cpp index 9fcbbcc78..d35f019d9 100644 --- a/Telegram/SourceFiles/old_settings/settings_info_widget.cpp +++ b/Telegram/SourceFiles/old_settings/settings_info_widget.cpp @@ -115,8 +115,8 @@ void InfoWidget::refreshBio() { TextWithEntities(), QString()); if (auto text = _bio->entity()->textLabel()) { - text->setClickHandlerFilter([](auto&&...) { - Ui::show(Box(App::self())); + text->setClickHandlerFilter([=](auto&&...) { + Ui::show(Box(self())); return false; }); } diff --git a/Telegram/SourceFiles/old_settings/settings_inner_widget.cpp b/Telegram/SourceFiles/old_settings/settings_inner_widget.cpp index ba0fd9b88..54fc0b22f 100644 --- a/Telegram/SourceFiles/old_settings/settings_inner_widget.cpp +++ b/Telegram/SourceFiles/old_settings/settings_inner_widget.cpp @@ -19,19 +19,19 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "old_settings/settings_background_widget.h" #include "old_settings/settings_privacy_widget.h" #include "old_settings/settings_advanced_widget.h" +#include "auth_session.h" namespace OldSettings { InnerWidget::InnerWidget(QWidget *parent) : LayerInner(parent) , _blocks(this) -, _self(App::self()) { +, _self(AuthSession::Exists() ? Auth().user().get() : nullptr) { refreshBlocks(); - subscribe(Global::RefSelfChanged(), [this] { fullRebuild(); }); subscribe(Lang::Current().updated(), [this] { fullRebuild(); }); } void InnerWidget::fullRebuild() { - _self = App::self(); + _self = AuthSession::Exists() ? Auth().user().get() : nullptr; refreshBlocks(); } diff --git a/Telegram/SourceFiles/passport/passport_form_controller.cpp b/Telegram/SourceFiles/passport/passport_form_controller.cpp index 143ff24f5..2546b9da3 100644 --- a/Telegram/SourceFiles/passport/passport_form_controller.cpp +++ b/Telegram/SourceFiles/passport/passport_form_controller.cpp @@ -1579,10 +1579,7 @@ QString FormController::defaultEmail() const { } QString FormController::defaultPhoneNumber() const { - if (const auto self = App::self()) { - return self->phone(); - } - return QString(); + return Auth().user()->phone(); } auto FormController::scanUpdated() const diff --git a/Telegram/SourceFiles/passport/passport_panel_details_row.cpp b/Telegram/SourceFiles/passport/passport_panel_details_row.cpp index 01ffa009e..cbfaeb15f 100644 --- a/Telegram/SourceFiles/passport/passport_panel_details_row.cpp +++ b/Telegram/SourceFiles/passport/passport_panel_details_row.cpp @@ -16,6 +16,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/widgets/checkbox.h" #include "ui/wrap/slide_wrap.h" #include "ui/countryinput.h" +#include "auth_session.h" #include "styles/style_boxes.h" #include "styles/style_passport.h" @@ -377,7 +378,8 @@ void CountryRow::errorAnimationCallback() { void CountryRow::chooseCountry() { const auto top = _value.current(); const auto name = CountrySelectBox::NameByISO(top); - const auto isoByPhone = CountrySelectBox::ISOByPhone(App::self()->phone()); + const auto isoByPhone = CountrySelectBox::ISOByPhone( + Auth().user()->phone()); const auto box = _controller->show(Box(!name.isEmpty() ? top : !isoByPhone.isEmpty() diff --git a/Telegram/SourceFiles/platform/mac/main_window_mac.mm b/Telegram/SourceFiles/platform/mac/main_window_mac.mm index 69e4b6cd3..bfa242ae5 100644 --- a/Telegram/SourceFiles/platform/mac/main_window_mac.mm +++ b/Telegram/SourceFiles/platform/mac/main_window_mac.mm @@ -12,6 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwidget.h" #include "application.h" #include "messenger.h" +#include "auth_session.h" #include "history/history.h" #include "history/history_widget.h" #include "history/history_inner_widget.h" @@ -605,7 +606,7 @@ void MainWindow::createGlobalMenu() { connect(psContacts, &QAction::triggered, psContacts, [] { if (App::wnd() && App::wnd()->isHidden()) App::wnd()->showFromTray(); - if (!App::self()) return; + if (!AuthSession::Exists()) return; Ui::show(Box(std::make_unique(), [](not_null box) { box->addButton(langFactory(lng_close), [box] { box->closeBox(); }); box->addLeftButton(langFactory(lng_profile_add_contact), [] { App::wnd()->onShowAddContact(); }); @@ -695,7 +696,7 @@ void MainWindow::updateGlobalMenuHook() { canDelete = list->canDeleteSelected(); } App::wnd()->updateIsActive(0); - const auto logged = !!App::self(); + const auto logged = AuthSession::Exists(); const auto locked = !Messenger::Instance().locked(); const auto inactive = !logged || locked; _forceDisabled(psLogout, !logged && !locked); diff --git a/Telegram/SourceFiles/profile/profile_block_group_members.cpp b/Telegram/SourceFiles/profile/profile_block_group_members.cpp index 5565384cb..320e39e04 100644 --- a/Telegram/SourceFiles/profile/profile_block_group_members.cpp +++ b/Telegram/SourceFiles/profile/profile_block_group_members.cpp @@ -343,7 +343,7 @@ void GroupMembersWidget::refreshLimitReached() { void GroupMembersWidget::checkSelfAdmin(ChatData *chat) { if (chat->participants.empty()) return; - auto self = App::self(); + const auto self = Auth().user(); if (chat->amAdmin() && !chat->admins.contains(self)) { chat->admins.insert(self); } else if (!chat->amAdmin() && chat->admins.contains(self)) { @@ -404,7 +404,7 @@ void GroupMembersWidget::fillChatMembers(ChatData *chat) { _sortByOnline = true; reserveItemsForSize(chat->participants.size()); - addUser(chat, App::self())->onlineForSort + addUser(chat, Auth().user())->onlineForSort = std::numeric_limits::max(); for (auto [user, v] : chat->participants) { if (!user->isSelf()) { @@ -454,7 +454,7 @@ void GroupMembersWidget::fillMegagroupMembers(ChannelData *megagroup) { clearItems(); reserveItemsForSize(membersList.size()); if (megagroup->amIn()) { - addUser(megagroup, App::self())->onlineForSort + addUser(megagroup, Auth().user())->onlineForSort = std::numeric_limits::max(); } } else if (membersList.size() >= itemsCount()) { diff --git a/Telegram/SourceFiles/profile/profile_channel_controllers.cpp b/Telegram/SourceFiles/profile/profile_channel_controllers.cpp index 92b8695d1..84f4f12ef 100644 --- a/Telegram/SourceFiles/profile/profile_channel_controllers.cpp +++ b/Telegram/SourceFiles/profile/profile_channel_controllers.cpp @@ -801,7 +801,7 @@ void ParticipantsBoxController::editAdminDone( } } else { // It won't be replaced if the entry already exists. - _additional.adminPromotedBy.emplace(user, App::self()); + _additional.adminPromotedBy.emplace(user, Auth().user()); _additional.adminCanEdit.emplace(user); _additional.adminRights[user] = rights; _additional.kicked.erase(user); @@ -859,7 +859,7 @@ void ParticipantsBoxController::editRestrictedDone(not_null user, con _additional.adminRights.erase(user); _additional.adminCanEdit.erase(user); _additional.adminPromotedBy.erase(user); - _additional.restrictedBy.emplace(user, App::self()); + _additional.restrictedBy.emplace(user, Auth().user()); if (fullBanned) { _additional.kicked.emplace(user); _additional.restrictedRights.erase(user); @@ -1472,7 +1472,7 @@ void AddParticipantBoxController::editAdminDone( _additional.adminCanEdit.emplace(user); auto it = _additional.adminPromotedBy.find(user); if (it == _additional.adminPromotedBy.end()) { - _additional.adminPromotedBy.emplace(user, App::self()); + _additional.adminPromotedBy.emplace(user, Auth().user()); } } if (_adminDoneCallback) { @@ -1557,7 +1557,7 @@ void AddParticipantBoxController::editRestrictedDone( } else { _additional.kicked.erase(user); } - _additional.restrictedBy.emplace(user, App::self()); + _additional.restrictedBy.emplace(user, Auth().user()); } if (_bannedDoneCallback) { _bannedDoneCallback(user, rights); diff --git a/Telegram/SourceFiles/settings/settings_information.cpp b/Telegram/SourceFiles/settings/settings_information.cpp index 20a7e5a0b..1b913021b 100644 --- a/Telegram/SourceFiles/settings/settings_information.cpp +++ b/Telegram/SourceFiles/settings/settings_information.cpp @@ -208,14 +208,18 @@ BioManager SetupBio( geometry.y() + style->textMargins.top()); }, countdown->lifetime()); + const auto assign = [=](QString text) { + auto position = bio->textCursor().position(); + bio->setText(text.replace('\n', ' ')); + auto cursor = bio->textCursor(); + cursor.setPosition(position); + bio->setTextCursor(cursor); + }; const auto updated = [=] { auto text = bio->getLastText(); if (text.indexOf('\n') >= 0) { - auto position = bio->textCursor().position(); - bio->setText(text.replace('\n', ' ')); - auto cursor = bio->textCursor(); - cursor.setPosition(position); - bio->setTextCursor(cursor); + assign(text); + text = bio->getLastText(); } changed->fire(*current != text); const auto countLeft = qMax(kMaxBioLength - text.size(), 0); @@ -230,8 +234,14 @@ BioManager SetupBio( Info::Profile::BioValue( self ) | rpl::start_with_next([=](const TextWithEntities &text) { + const auto wasChanged = (*current != bio->getLastText()); *current = text.text; - changed->fire(*current != bio->getLastText()); + if (wasChanged) { + changed->fire(*current != bio->getLastText()); + } else { + assign(text.text); + *current = bio->getLastText(); + } }, bio->lifetime()); bio->setMaxLength(kMaxBioLength); diff --git a/Telegram/SourceFiles/ui/widgets/input_fields.cpp b/Telegram/SourceFiles/ui/widgets/input_fields.cpp index 7e30458c5..49186159a 100644 --- a/Telegram/SourceFiles/ui/widgets/input_fields.cpp +++ b/Telegram/SourceFiles/ui/widgets/input_fields.cpp @@ -15,6 +15,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_keys.h" #include "mainwindow.h" #include "numbers.h" +#include "auth_session.h" #include "messenger.h" namespace Ui { @@ -4122,10 +4123,11 @@ void PhoneInput::focusInEvent(QFocusEvent *e) { void PhoneInput::clearText() { QString phone; - if (App::self()) { - QVector newPattern = phoneNumberParse(App::self()->phone()); + if (AuthSession::Exists()) { + const auto self = Auth().user(); + QVector newPattern = phoneNumberParse(self->phone()); if (!newPattern.isEmpty()) { - phone = App::self()->phone().mid(0, newPattern.at(0)); + phone = self->phone().mid(0, newPattern.at(0)); } } setText(phone); diff --git a/Telegram/SourceFiles/window/window_controller.cpp b/Telegram/SourceFiles/window/window_controller.cpp index b1b06d6e7..f2c9217cd 100644 --- a/Telegram/SourceFiles/window/window_controller.cpp +++ b/Telegram/SourceFiles/window/window_controller.cpp @@ -478,17 +478,18 @@ void Navigation::showPeerInfo( void Navigation::showSettings( Settings::Type type, const SectionShow ¶ms) { - const auto self = App::self(); - if (!self) { + if (AuthSession::Exists()) { + showSection( + Info::Memento( + Info::Settings::Tag{ Auth().user() }, + Info::Section(type)), + params); + } else { // #TODO settings App::wnd()->showSpecialLayer( Box(), params.animated); - return; } - showSection( - Info::Memento(Info::Settings::Tag{ self }, Info::Section(type)), - params); } void Navigation::showSettings(const SectionShow ¶ms) { diff --git a/Telegram/SourceFiles/window/window_main_menu.cpp b/Telegram/SourceFiles/window/window_main_menu.cpp index a96beaad5..4546aa189 100644 --- a/Telegram/SourceFiles/window/window_main_menu.cpp +++ b/Telegram/SourceFiles/window/window_main_menu.cpp @@ -38,10 +38,20 @@ MainMenu::MainMenu( , _version(this, st::mainMenuVersionLabel) { setAttribute(Qt::WA_OpaquePaintEvent); - subscribe(Global::RefSelfChanged(), [this] { - checkSelf(); - }); - checkSelf(); + auto showSelfChat = [] { + App::main()->choosePeer(Auth().userPeerId(), ShowAtUnreadMsgId); + }; + _userpicButton.create( + this, + _controller, + Auth().user(), + Ui::UserpicButton::Role::Custom, + st::mainMenuUserpic); + _userpicButton->setClickedCallback(showSelfChat); + _userpicButton->show(); + _cloudButton.create(this, st::mainMenuCloudButton); + _cloudButton->setClickedCallback(showSelfChat); + _cloudButton->show(); _nightThemeSwitch.setCallback([this] { if (const auto action = *_nightThemeAction) { @@ -120,32 +130,6 @@ void MainMenu::refreshMenu() { updatePhone(); } -void MainMenu::checkSelf() { - if (auto self = App::self()) { - auto showSelfChat = [] { - if (auto self = App::self()) { - App::main()->choosePeer(self->id, ShowAtUnreadMsgId); - } - }; - _userpicButton.create( - this, - _controller, - self, - Ui::UserpicButton::Role::Custom, - st::mainMenuUserpic); - _userpicButton->setClickedCallback(showSelfChat); - _userpicButton->show(); - _cloudButton.create(this, st::mainMenuCloudButton); - _cloudButton->setClickedCallback(showSelfChat); - _cloudButton->show(); - update(); - updateControlsGeometry(); - } else { - _userpicButton.destroy(); - _cloudButton.destroy(); - } -} - void MainMenu::resizeEvent(QResizeEvent *e) { _menu->setForceWidth(width()); updateControlsGeometry(); @@ -164,11 +148,7 @@ void MainMenu::updateControlsGeometry() { } void MainMenu::updatePhone() { - if (auto self = App::self()) { - _phoneText = App::formatPhone(self->phone()); - } else { - _phoneText = QString(); - } + _phoneText = App::formatPhone(Auth().user()->phone()); update(); } @@ -180,11 +160,14 @@ void MainMenu::paintEvent(QPaintEvent *e) { p.fillRect(cover, st::mainMenuCoverBg); p.setPen(st::mainMenuCoverFg); p.setFont(st::semiboldFont); - if (auto self = App::self()) { - self->nameText.drawLeftElided(p, st::mainMenuCoverTextLeft, st::mainMenuCoverNameTop, width() - 2 * st::mainMenuCoverTextLeft, width()); - p.setFont(st::normalFont); - p.drawTextLeft(st::mainMenuCoverTextLeft, st::mainMenuCoverStatusTop, width(), _phoneText); - } + Auth().user()->nameText.drawLeftElided( + p, + st::mainMenuCoverTextLeft, + st::mainMenuCoverNameTop, + width() - 2 * st::mainMenuCoverTextLeft, + width()); + p.setFont(st::normalFont); + p.drawTextLeft(st::mainMenuCoverTextLeft, st::mainMenuCoverStatusTop, width(), _phoneText); if (_cloudButton) { Ui::EmptyUserpic::PaintSavedMessages( p, diff --git a/Telegram/SourceFiles/window/window_main_menu.h b/Telegram/SourceFiles/window/window_main_menu.h index 979e64208..78bf1c488 100644 --- a/Telegram/SourceFiles/window/window_main_menu.h +++ b/Telegram/SourceFiles/window/window_main_menu.h @@ -33,7 +33,6 @@ protected: void resizeEvent(QResizeEvent *e) override; private: - void checkSelf(); void updateControlsGeometry(); void updatePhone(); void refreshMenu(); diff --git a/Telegram/SourceFiles/window/window_peer_menu.cpp b/Telegram/SourceFiles/window/window_peer_menu.cpp index d993f5716..178c8577c 100644 --- a/Telegram/SourceFiles/window/window_peer_menu.cpp +++ b/Telegram/SourceFiles/window/window_peer_menu.cpp @@ -352,7 +352,7 @@ void Filler::addUserActions(not_null user) { _addAction( lang(lng_profile_clear_history), ClearHistoryHandler(user)); - if (!user->isInaccessible() && user != App::self()) { + if (!user->isInaccessible() && user != Auth().user()) { addBlockUser(user); } }