Remove some more Auth() calls.

This commit is contained in:
John Preston 2019-08-06 17:40:08 +01:00
parent f48732f813
commit 4bad642190
36 changed files with 280 additions and 196 deletions

View File

@ -2787,7 +2787,7 @@ void ApiWrap::requestAttachedStickerSets(not_null<PhotoData*> photo) {
Ui::show(Box<InformBox>(tr::lng_stickers_not_found(tr::now))); Ui::show(Box<InformBox>(tr::lng_stickers_not_found(tr::now)));
return; return;
} else if (result.v.size() > 1) { } else if (result.v.size() > 1) {
Ui::show(Box<StickersBox>(result)); Ui::show(Box<StickersBox>(&session(), result));
return; return;
} }
// Single attached sticker pack. // Single attached sticker pack.

View File

@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/sender.h" #include "mtproto/sender.h"
#include "base/flat_set.h" #include "base/flat_set.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "boxes/confirm_phone_box.h" // ExtractPhonePrefix.
#include "boxes/photo_crop_box.h" #include "boxes/photo_crop_box.h"
#include "boxes/peer_list_controllers.h" #include "boxes/peer_list_controllers.h"
#include "boxes/peers/add_participants_box.h" #include "boxes/peers/add_participants_box.h"
@ -209,7 +210,12 @@ AddContactBox::AddContactBox(
: _session(session) : _session(session)
, _first(this, st::defaultInputField, tr::lng_signup_firstname(), fname) , _first(this, st::defaultInputField, tr::lng_signup_firstname(), fname)
, _last(this, st::defaultInputField, tr::lng_signup_lastname(), lname) , _last(this, st::defaultInputField, tr::lng_signup_lastname(), lname)
, _phone(this, st::defaultInputField, tr::lng_contact_phone(), phone) , _phone(
this,
st::defaultInputField,
tr::lng_contact_phone(),
ExtractPhonePrefix(session->user()->phone()),
phone)
, _invertOrder(langFirstNameGoesSecond()) { , _invertOrder(langFirstNameGoesSecond()) {
if (!phone.isEmpty()) { if (!phone.isEmpty()) {
_phone->setDisabled(true); _phone->setDisabled(true);

View File

@ -17,6 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "main/main_session.h" #include "main/main_session.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_user.h"
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
namespace { namespace {
@ -79,6 +80,7 @@ private:
} }
const not_null<Main::Session*> _session; const not_null<Main::Session*> _session;
object_ptr<Ui::PhoneInput> _phone = { nullptr }; object_ptr<Ui::PhoneInput> _phone = { nullptr };
object_ptr<Ui::FadeWrap<Ui::FlatLabel>> _error = { nullptr }; object_ptr<Ui::FadeWrap<Ui::FlatLabel>> _error = { nullptr };
mtpRequestId _requestId = 0; mtpRequestId _requestId = 0;
@ -137,7 +139,12 @@ void ChangePhoneBox::EnterPhone::prepare() {
setTitle(tr::lng_change_phone_title()); setTitle(tr::lng_change_phone_title());
auto phoneValue = QString(); auto phoneValue = QString();
_phone.create(this, st::defaultInputField, tr::lng_change_phone_new_title(), phoneValue); _phone.create(
this,
st::defaultInputField,
tr::lng_change_phone_new_title(),
ExtractPhonePrefix(_session->user()->phone()),
phoneValue);
_phone->resize(st::boxWidth - 2 * st::boxPadding.left(), _phone->height()); _phone->resize(st::boxWidth - 2 * st::boxPadding.left(), _phone->height());
_phone->moveToLeft(st::boxPadding.left(), st::boxLittleSkip); _phone->moveToLeft(st::boxPadding.left(), st::boxLittleSkip);

View File

@ -17,6 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "base/qthelp_url.h" // qthelp::url_encode #include "base/qthelp_url.h" // qthelp::url_encode
#include "platform/platform_info.h" // Platform::SystemVersionPretty #include "platform/platform_info.h" // Platform::SystemVersionPretty
#include "mainwidget.h" #include "mainwidget.h"
#include "numbers.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
namespace { namespace {
@ -64,7 +65,14 @@ void ShowPhoneBannedError(const QString &phone) {
tr::lng_signin_banned_help(tr::now), tr::lng_signin_banned_help(tr::now),
close, close,
[=] { SendToBannedHelp(phone); close(); })); [=] { SendToBannedHelp(phone); close(); }));
}
QString ExtractPhonePrefix(const QString &phone) {
const auto pattern = phoneNumberParse(phone);
if (!pattern.isEmpty()) {
return phone.mid(0, pattern[0]);
}
return QString();
} }
SentCodeField::SentCodeField( SentCodeField::SentCodeField(

View File

@ -17,6 +17,7 @@ class FlatLabel;
} // namespace Ui } // namespace Ui
void ShowPhoneBannedError(const QString &phone); void ShowPhoneBannedError(const QString &phone);
[[nodiscard]] QString ExtractPhonePrefix(const QString &phone);
class SentCodeField : public Ui::InputField { class SentCodeField : public Ui::InputField {
public: public:

View File

@ -43,24 +43,9 @@ constexpr auto kHandleMegagroupSetAddressChangeTimeout = crl::time(1000);
} // namespace } // namespace
int stickerPacksCount(bool includeArchivedOfficial) {
auto result = 0;
auto &order = Auth().data().stickerSetsOrder();
auto &sets = Auth().data().stickerSets();
for (const auto setId : order) {
const auto it = sets.constFind(setId);
if (it != sets.cend()) {
if (!(it->flags & MTPDstickerSet::Flag::f_archived) || ((it->flags & MTPDstickerSet::Flag::f_official) && includeArchivedOfficial)) {
++result;
}
}
}
return result;
}
class StickersBox::CounterWidget : public Ui::RpWidget { class StickersBox::CounterWidget : public Ui::RpWidget {
public: public:
CounterWidget(QWidget *parent); CounterWidget(QWidget *parent, rpl::producer<int> count);
protected: protected:
void paintEvent(QPaintEvent *e) override; void paintEvent(QPaintEvent *e) override;
@ -73,7 +58,9 @@ private:
}; };
StickersBox::CounterWidget::CounterWidget(QWidget *parent) StickersBox::CounterWidget::CounterWidget(
QWidget *parent,
rpl::producer<int> count)
: RpWidget(parent) { : RpWidget(parent) {
setAttribute(Qt::WA_TransparentForMouseEvents); setAttribute(Qt::WA_TransparentForMouseEvents);
@ -83,8 +70,9 @@ StickersBox::CounterWidget::CounterWidget(QWidget *parent)
_st.padding = st::stickersFeaturedBadgePadding; _st.padding = st::stickersFeaturedBadgePadding;
_st.font = st::stickersFeaturedBadgeFont; _st.font = st::stickersFeaturedBadgeFont;
Auth().data().featuredStickerSetsUnreadCountValue( std::move(
) | rpl::start_with_next([this](int count) { count
) | rpl::start_with_next([=](int count) {
setCounter(count); setCounter(count);
update(); update();
}, lifetime()); }, lifetime());
@ -131,26 +119,35 @@ void StickersBox::Tab::saveScrollTop() {
_scrollTop = widget()->getVisibleTop(); _scrollTop = widget()->getVisibleTop();
} }
StickersBox::StickersBox(QWidget*, Section section) StickersBox::StickersBox(
: _tabs(this, st::stickersTabs) QWidget*,
, _unreadBadge(this) not_null<Main::Session*> session,
Section section)
: _session(session)
, _tabs(this, st::stickersTabs)
, _unreadBadge(this, _session->data().featuredStickerSetsUnreadCountValue())
, _section(section) , _section(section)
, _installed(0, this, Section::Installed) , _installed(0, this, session, Section::Installed)
, _featured(1, this, Section::Featured) , _featured(1, this, session, Section::Featured)
, _archived(2, this, Section::Archived) { , _archived(2, this, session, Section::Archived) {
_tabs->setRippleTopRoundRadius(st::boxRadius); _tabs->setRippleTopRoundRadius(st::boxRadius);
} }
StickersBox::StickersBox(QWidget*, not_null<ChannelData*> megagroup) StickersBox::StickersBox(QWidget*, not_null<ChannelData*> megagroup)
: _section(Section::Installed) : _session(&megagroup->session())
, _section(Section::Installed)
, _installed(0, this, megagroup) , _installed(0, this, megagroup)
, _megagroupSet(megagroup) { , _megagroupSet(megagroup) {
subscribe(_installed.widget()->scrollToY, [this](int y) { onScrollToY(y); }); subscribe(_installed.widget()->scrollToY, [this](int y) { onScrollToY(y); });
} }
StickersBox::StickersBox(QWidget*, const MTPVector<MTPStickerSetCovered> &attachedSets) StickersBox::StickersBox(
: _section(Section::Attached) QWidget*,
, _attached(0, this, Section::Attached) not_null<Main::Session*> session,
const MTPVector<MTPStickerSetCovered> &attachedSets)
: _session(session)
, _section(Section::Attached)
, _attached(0, this, session, Section::Attached)
, _attachedSets(attachedSets) { , _attachedSets(attachedSets) {
} }
@ -167,7 +164,7 @@ void StickersBox::showAttachedStickers() {
if (_attached.widget()->appendSet(*set)) { if (_attached.widget()->appendSet(*set)) {
addedSet = true; addedSet = true;
if (set->stickers.isEmpty() || (set->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (set->stickers.isEmpty() || (set->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
Auth().api().scheduleStickerSetRequest(set->id, set->access); _session->api().scheduleStickerSetRequest(set->id, set->access);
} }
} }
} }
@ -177,7 +174,7 @@ void StickersBox::showAttachedStickers() {
} }
if (_section == Section::Attached && addedSet) { if (_section == Section::Attached && addedSet) {
Auth().api().requestStickerSets(); _session->api().requestStickerSets();
} }
} }
@ -189,7 +186,7 @@ void StickersBox::getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedSti
} }
auto &stickers = result.c_messages_archivedStickers(); auto &stickers = result.c_messages_archivedStickers();
auto &archived = Auth().data().archivedStickerSetsOrderRef(); auto &archived = _session->data().archivedStickerSetsOrderRef();
if (offsetId) { if (offsetId) {
auto index = archived.indexOf(offsetId); auto index = archived.indexOf(offsetId);
if (index >= 0) { if (index >= 0) {
@ -231,7 +228,7 @@ void StickersBox::getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedSti
if (_archived.widget()->appendSet(*set)) { if (_archived.widget()->appendSet(*set)) {
addedSet = true; addedSet = true;
if (set->stickers.isEmpty() || (set->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (set->stickers.isEmpty() || (set->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
Auth().api().scheduleStickerSetRequest(set->id, set->access); _session->api().scheduleStickerSetRequest(set->id, set->access);
} }
} }
} }
@ -249,7 +246,7 @@ void StickersBox::getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedSti
refreshTabs(); refreshTabs();
_someArchivedLoaded = true; _someArchivedLoaded = true;
if (_section == Section::Archived && addedSet) { if (_section == Section::Archived && addedSet) {
Auth().api().requestStickerSets(); _session->api().requestStickerSets();
} }
} }
@ -266,7 +263,7 @@ void StickersBox::prepare() {
setTitle(tr::lng_stickers_attached_sets()); setTitle(tr::lng_stickers_attached_sets());
} }
if (_tabs) { if (_tabs) {
if (Auth().data().archivedStickerSetsOrder().isEmpty()) { if (_session->data().archivedStickerSetsOrder().isEmpty()) {
preloadArchivedSets(); preloadArchivedSets();
} }
setNoContentMargin(true); setNoContentMargin(true);
@ -317,11 +314,11 @@ void StickersBox::prepare() {
setInnerWidget(_tab->takeWidget(), getTopSkip()); setInnerWidget(_tab->takeWidget(), getTopSkip());
setDimensions(st::boxWideWidth, st::boxMaxListHeight); setDimensions(st::boxWideWidth, st::boxMaxListHeight);
Auth().data().stickersUpdated( _session->data().stickersUpdated(
) | rpl::start_with_next( ) | rpl::start_with_next(
[this] { handleStickersUpdated(); }, [this] { handleStickersUpdated(); },
lifetime()); lifetime());
Auth().api().updateStickers(); _session->api().updateStickers();
if (_installed.widget()) { if (_installed.widget()) {
connect(_installed.widget(), SIGNAL(draggingScrollDelta(int)), this, SLOT(onDraggingScrollDelta(int))); connect(_installed.widget(), SIGNAL(draggingScrollDelta(int)), this, SLOT(onDraggingScrollDelta(int)));
@ -346,11 +343,11 @@ void StickersBox::refreshTabs() {
auto sections = QStringList(); auto sections = QStringList();
sections.push_back(tr::lng_stickers_installed_tab(tr::now).toUpper()); sections.push_back(tr::lng_stickers_installed_tab(tr::now).toUpper());
_tabIndices.push_back(Section::Installed); _tabIndices.push_back(Section::Installed);
if (!Auth().data().featuredStickerSetsOrder().isEmpty()) { if (!_session->data().featuredStickerSetsOrder().isEmpty()) {
sections.push_back(tr::lng_stickers_featured_tab(tr::now).toUpper()); sections.push_back(tr::lng_stickers_featured_tab(tr::now).toUpper());
_tabIndices.push_back(Section::Featured); _tabIndices.push_back(Section::Featured);
} }
if (!Auth().data().archivedStickerSetsOrder().isEmpty()) { if (!_session->data().archivedStickerSetsOrder().isEmpty()) {
sections.push_back(tr::lng_stickers_archived_tab(tr::now).toUpper()); sections.push_back(tr::lng_stickers_archived_tab(tr::now).toUpper());
_tabIndices.push_back(Section::Archived); _tabIndices.push_back(Section::Archived);
} }
@ -372,10 +369,10 @@ void StickersBox::loadMoreArchived() {
} }
uint64 lastId = 0; uint64 lastId = 0;
for (auto setIt = Auth().data().archivedStickerSetsOrder().cend(), e = Auth().data().archivedStickerSetsOrder().cbegin(); setIt != e;) { for (auto setIt = _session->data().archivedStickerSetsOrder().cend(), e = _session->data().archivedStickerSetsOrder().cbegin(); setIt != e;) {
--setIt; --setIt;
auto it = Auth().data().stickerSets().constFind(*setIt); auto it = _session->data().stickerSets().constFind(*setIt);
if (it != Auth().data().stickerSets().cend()) { if (it != _session->data().stickerSets().cend()) {
if (it->flags & MTPDstickerSet::Flag::f_archived) { if (it->flags & MTPDstickerSet::Flag::f_archived) {
lastId = it->id; lastId = it->id;
break; break;
@ -488,7 +485,7 @@ QPixmap StickersBox::grabContentCache() {
} }
void StickersBox::installSet(uint64 setId) { void StickersBox::installSet(uint64 setId) {
auto &sets = Auth().data().stickerSetsRef(); auto &sets = _session->data().stickerSetsRef();
auto it = sets.find(setId); auto it = sets.find(setId);
if (it == sets.cend()) { if (it == sets.cend()) {
rebuildList(); rebuildList();
@ -525,7 +522,7 @@ void StickersBox::installDone(const MTPmessages_StickerSetInstallResult &result)
bool StickersBox::installFail(uint64 setId, const RPCError &error) { bool StickersBox::installFail(uint64 setId, const RPCError &error) {
if (MTP::isDefaultHandledError(error)) return false; if (MTP::isDefaultHandledError(error)) return false;
auto &sets = Auth().data().stickerSetsRef(); auto &sets = _session->data().stickerSetsRef();
auto it = sets.find(setId); auto it = sets.find(setId);
if (it == sets.cend()) { if (it == sets.cend()) {
rebuildList(); rebuildList();
@ -549,16 +546,16 @@ void StickersBox::requestArchivedSets() {
preloadArchivedSets(); preloadArchivedSets();
} }
auto &sets = Auth().data().stickerSets(); auto &sets = _session->data().stickerSets();
for_const (auto setId, Auth().data().archivedStickerSetsOrder()) { for_const (auto setId, _session->data().archivedStickerSetsOrder()) {
auto it = sets.constFind(setId); auto it = sets.constFind(setId);
if (it != sets.cend()) { if (it != sets.cend()) {
if (it->stickers.isEmpty() && (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (it->stickers.isEmpty() && (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
Auth().api().scheduleStickerSetRequest(setId, it->access); _session->api().scheduleStickerSetRequest(setId, it->access);
} }
} }
} }
Auth().api().requestStickerSets(); _session->api().requestStickerSets();
} }
void StickersBox::resizeEvent(QResizeEvent *e) { void StickersBox::resizeEvent(QResizeEvent *e) {
@ -582,7 +579,7 @@ void StickersBox::handleStickersUpdated() {
} else { } else {
_tab->widget()->updateRows(); _tab->widget()->updateRows();
} }
if (Auth().data().archivedStickerSetsOrder().isEmpty()) { if (_session->data().archivedStickerSetsOrder().isEmpty()) {
preloadArchivedSets(); preloadArchivedSets();
} else { } else {
refreshTabs(); refreshTabs();
@ -611,9 +608,7 @@ void StickersBox::saveChanges() {
if (_someArchivedLoaded) { if (_someArchivedLoaded) {
Local::writeArchivedStickers(); Local::writeArchivedStickers();
} }
if (Main::Session::Exists()) { _session->api().saveStickerSets(_installed.widget()->getOrder(), _installed.widget()->getRemovedSets());
Auth().api().saveStickerSets(_installed.widget()->getOrder(), _installed.widget()->getRemovedSets());
}
} }
void StickersBox::setInnerFocus() { void StickersBox::setInnerFocus() {
@ -657,8 +652,12 @@ StickersBox::Inner::Row::Row(
StickersBox::Inner::Row::~Row() = default; StickersBox::Inner::Row::~Row() = default;
StickersBox::Inner::Inner(QWidget *parent, StickersBox::Section section) StickersBox::Inner::Inner(
QWidget *parent,
not_null<Main::Session*> session,
StickersBox::Section section)
: RpWidget(parent) : RpWidget(parent)
, _session(session)
, _section(section) , _section(section)
, _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) , _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom())
, _shiftingAnimation([=](crl::time now) { , _shiftingAnimation([=](crl::time now) {
@ -674,6 +673,7 @@ StickersBox::Inner::Inner(QWidget *parent, StickersBox::Section section)
StickersBox::Inner::Inner(QWidget *parent, not_null<ChannelData*> megagroup) StickersBox::Inner::Inner(QWidget *parent, not_null<ChannelData*> megagroup)
: RpWidget(parent) : RpWidget(parent)
, _session(&megagroup->session())
, _section(StickersBox::Section::Installed) , _section(StickersBox::Section::Installed)
, _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom()) , _rowHeight(st::contactsPadding.top() + st::contactsPhotoSize + st::contactsPadding.bottom())
, _shiftingAnimation([=](crl::time now) { , _shiftingAnimation([=](crl::time now) {
@ -707,7 +707,7 @@ StickersBox::Inner::Inner(QWidget *parent, not_null<ChannelData*> megagroup)
} }
void StickersBox::Inner::setup() { void StickersBox::Inner::setup() {
subscribe(Auth().downloaderTaskFinished(), [this] { subscribe(_session->downloaderTaskFinished(), [this] {
update(); update();
readVisibleSets(); readVisibleSets();
}); });
@ -1284,7 +1284,7 @@ void StickersBox::Inner::mouseReleaseEvent(QMouseEvent *e) {
return -1; return -1;
}(); }();
auto getSetByRow = [&](const Row &row) -> const Stickers::Set* { auto getSetByRow = [&](const Row &row) -> const Stickers::Set* {
auto &sets = Auth().data().stickerSetsRef(); auto &sets = _session->data().stickerSetsRef();
if (!row.isRecentSet()) { if (!row.isRecentSet()) {
auto it = sets.find(row.id); auto it = sets.find(row.id);
if (it != sets.cend()) { if (it != sets.cend()) {
@ -1327,8 +1327,8 @@ void StickersBox::Inner::saveGroupSet() {
auto oldId = (_megagroupSet->mgInfo->stickerSet.type() == mtpc_inputStickerSetID) ? _megagroupSet->mgInfo->stickerSet.c_inputStickerSetID().vid().v : 0; auto oldId = (_megagroupSet->mgInfo->stickerSet.type() == mtpc_inputStickerSetID) ? _megagroupSet->mgInfo->stickerSet.c_inputStickerSetID().vid().v : 0;
auto newId = (_megagroupSetInput.type() == mtpc_inputStickerSetID) ? _megagroupSetInput.c_inputStickerSetID().vid().v : 0; auto newId = (_megagroupSetInput.type() == mtpc_inputStickerSetID) ? _megagroupSetInput.c_inputStickerSetID().vid().v : 0;
if (newId != oldId) { if (newId != oldId) {
Auth().api().setGroupStickerSet(_megagroupSet, _megagroupSetInput); _session->api().setGroupStickerSet(_megagroupSet, _megagroupSetInput);
Auth().api().stickerSetInstalled(Stickers::MegagroupSetId); _session->api().stickerSetInstalled(Stickers::MegagroupSetId);
} }
} }
@ -1460,8 +1460,8 @@ void StickersBox::Inner::handleMegagroupSetAddressChange() {
auto text = _megagroupSetField->getLastText().trimmed(); auto text = _megagroupSetField->getLastText().trimmed();
if (text.isEmpty()) { if (text.isEmpty()) {
if (_megagroupSelectedSet) { if (_megagroupSelectedSet) {
auto it = Auth().data().stickerSets().constFind(_megagroupSelectedSet->id); auto it = _session->data().stickerSets().constFind(_megagroupSelectedSet->id);
if (it != Auth().data().stickerSets().cend() && !it->shortName.isEmpty()) { if (it != _session->data().stickerSets().cend() && !it->shortName.isEmpty()) {
setMegagroupSelectedSet(MTP_inputStickerSetEmpty()); setMegagroupSelectedSet(MTP_inputStickerSetEmpty());
} }
} }
@ -1493,10 +1493,10 @@ void StickersBox::Inner::rebuildMegagroupSet() {
} }
auto &set = _megagroupSetInput.c_inputStickerSetID(); auto &set = _megagroupSetInput.c_inputStickerSetID();
auto setId = set.vid().v; auto setId = set.vid().v;
auto &sets = Auth().data().stickerSets(); auto &sets = _session->data().stickerSets();
auto it = sets.find(setId); auto it = sets.find(setId);
if (it == sets.cend() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (it == sets.cend() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
Auth().api().scheduleStickerSetRequest(set.vid().v, set.vaccess_hash().v); _session->api().scheduleStickerSetRequest(set.vid().v, set.vaccess_hash().v);
return; return;
} }
@ -1555,22 +1555,22 @@ void StickersBox::Inner::rebuild() {
clear(); clear();
auto &order = ([&]() -> const Stickers::Order & { auto &order = ([&]() -> const Stickers::Order & {
if (_section == Section::Installed) { if (_section == Section::Installed) {
auto &result = Auth().data().stickerSetsOrder(); auto &result = _session->data().stickerSetsOrder();
if (_megagroupSet && result.empty()) { if (_megagroupSet && result.empty()) {
return Auth().data().featuredStickerSetsOrder(); return _session->data().featuredStickerSetsOrder();
} }
return result; return result;
} else if (_section == Section::Featured) { } else if (_section == Section::Featured) {
return Auth().data().featuredStickerSetsOrder(); return _session->data().featuredStickerSetsOrder();
} }
return Auth().data().archivedStickerSetsOrder(); return _session->data().archivedStickerSetsOrder();
})(); })();
_rows.reserve(order.size() + 1); _rows.reserve(order.size() + 1);
_shiftingStartTimes.reserve(order.size() + 1); _shiftingStartTimes.reserve(order.size() + 1);
auto &sets = Auth().data().stickerSets(); auto &sets = _session->data().stickerSets();
if (_megagroupSet) { if (_megagroupSet) {
auto usingFeatured = Auth().data().stickerSetsOrder().empty(); auto usingFeatured = _session->data().stickerSetsOrder().empty();
_megagroupSubTitle->setText(usingFeatured _megagroupSubTitle->setText(usingFeatured
? tr::lng_stickers_group_from_featured(tr::now) ? tr::lng_stickers_group_from_featured(tr::now)
: tr::lng_stickers_group_from_your(tr::now)); : tr::lng_stickers_group_from_your(tr::now));
@ -1590,10 +1590,10 @@ void StickersBox::Inner::rebuild() {
rebuildAppendSet(it.value(), maxNameWidth); rebuildAppendSet(it.value(), maxNameWidth);
if (it->stickers.isEmpty() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (it->stickers.isEmpty() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
Auth().api().scheduleStickerSetRequest(it->id, it->access); _session->api().scheduleStickerSetRequest(it->id, it->access);
} }
} }
Auth().api().requestStickerSets(); _session->api().requestStickerSets();
updateSize(); updateSize();
} }
@ -1618,7 +1618,7 @@ void StickersBox::Inner::updateSize(int newWidth) {
void StickersBox::Inner::updateRows() { void StickersBox::Inner::updateRows() {
int maxNameWidth = countMaxNameWidth(); int maxNameWidth = countMaxNameWidth();
auto &sets = Auth().data().stickerSets(); auto &sets = _session->data().stickerSets();
for (const auto &row : _rows) { for (const auto &row : _rows) {
const auto it = sets.constFind(row->id); const auto it = sets.constFind(row->id);
if (it == sets.cend()) { if (it == sets.cend()) {
@ -1758,8 +1758,8 @@ void StickersBox::Inner::fillSetCover(const Stickers::Set &set, ImagePtr *thumbn
int StickersBox::Inner::fillSetCount(const Stickers::Set &set) const { int StickersBox::Inner::fillSetCount(const Stickers::Set &set) const {
int result = set.stickers.isEmpty() ? set.count : set.stickers.size(), added = 0; int result = set.stickers.isEmpty() ? set.count : set.stickers.size(), added = 0;
if (set.id == Stickers::CloudRecentSetId) { if (set.id == Stickers::CloudRecentSetId) {
auto customIt = Auth().data().stickerSets().constFind(Stickers::CustomSetId); auto customIt = _session->data().stickerSets().constFind(Stickers::CustomSetId);
if (customIt != Auth().data().stickerSets().cend()) { if (customIt != _session->data().stickerSets().cend()) {
added = customIt->stickers.size(); added = customIt->stickers.size();
for_const (auto &sticker, Stickers::GetRecentPack()) { for_const (auto &sticker, Stickers::GetRecentPack()) {
if (customIt->stickers.indexOf(sticker.first) < 0) { if (customIt->stickers.indexOf(sticker.first) < 0) {
@ -1904,7 +1904,7 @@ void StickersBox::Inner::readVisibleSets() {
if (!thumbnail if (!thumbnail
|| thumbnail->loaded() || thumbnail->loaded()
|| _rows[i]->sticker->loaded()) { || _rows[i]->sticker->loaded()) {
Auth().api().readFeaturedSetDelayed(_rows[i]->id); _session->api().readFeaturedSetDelayed(_rows[i]->id);
} }
} }
} }

View File

@ -28,6 +28,10 @@ class SlideAnimation;
class CrossButton; class CrossButton;
} // namespace Ui } // namespace Ui
namespace Main {
class Session;
} // namespace Main
class StickersBox : public BoxContent, public RPCSender { class StickersBox : public BoxContent, public RPCSender {
public: public:
enum class Section { enum class Section {
@ -36,9 +40,16 @@ public:
Archived, Archived,
Attached, Attached,
}; };
StickersBox(QWidget*, Section section);
StickersBox(
QWidget*,
not_null<Main::Session*> session,
Section section);
StickersBox(QWidget*, not_null<ChannelData*> megagroup); StickersBox(QWidget*, not_null<ChannelData*> megagroup);
StickersBox(QWidget*, const MTPVector<MTPStickerSetCovered> &attachedSets); StickersBox(
QWidget*,
not_null<Main::Session*> session,
const MTPVector<MTPStickerSetCovered> &attachedSets);
void setInnerFocus() override; void setInnerFocus() override;
@ -102,6 +113,8 @@ private:
void getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedStickers &result); void getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedStickers &result);
void showAttachedStickers(); void showAttachedStickers();
const not_null<Main::Session*> _session;
object_ptr<Ui::SettingsSlider> _tabs = { nullptr }; object_ptr<Ui::SettingsSlider> _tabs = { nullptr };
QList<Section> _tabIndices; QList<Section> _tabIndices;
@ -133,8 +146,6 @@ private:
}; };
int stickerPacksCount(bool includeArchivedOfficial = false);
// This class is hold in header because it requires Qt preprocessing. // This class is hold in header because it requires Qt preprocessing.
class StickersBox::Inner class StickersBox::Inner
: public Ui::RpWidget : public Ui::RpWidget
@ -144,7 +155,11 @@ class StickersBox::Inner
public: public:
using Section = StickersBox::Section; using Section = StickersBox::Section;
Inner(QWidget *parent, Section section);
Inner(
QWidget *parent,
not_null<Main::Session*> session,
Section section);
Inner(QWidget *parent, not_null<ChannelData*> megagroup); Inner(QWidget *parent, not_null<ChannelData*> megagroup);
base::Observable<int> scrollToY; base::Observable<int> scrollToY;
@ -300,6 +315,8 @@ private:
int countMaxNameWidth() const; int countMaxNameWidth() const;
const not_null<Main::Session*> _session;
Section _section; Section _section;
int32 _rowHeight; int32 _rowHeight;

View File

@ -120,17 +120,18 @@ void UrlAuthBox::Request(
} }
}; };
*box = Ui::show( *box = Ui::show(
Box<UrlAuthBox>(url, qs(request.vdomain()), bot, callback), Box<UrlAuthBox>(session, url, qs(request.vdomain()), bot, callback),
LayerOption::KeepOther); LayerOption::KeepOther);
} }
UrlAuthBox::UrlAuthBox( UrlAuthBox::UrlAuthBox(
QWidget*, QWidget*,
not_null<Main::Session*> session,
const QString &url, const QString &url,
const QString &domain, const QString &domain,
UserData *bot, UserData *bot,
Fn<void(Result)> callback) Fn<void(Result)> callback)
: _content(setupContent(url, domain, bot, std::move(callback))) { : _content(setupContent(session, url, domain, bot, std::move(callback))) {
} }
void UrlAuthBox::prepare() { void UrlAuthBox::prepare() {
@ -140,6 +141,7 @@ void UrlAuthBox::prepare() {
} }
not_null<Ui::RpWidget*> UrlAuthBox::setupContent( not_null<Ui::RpWidget*> UrlAuthBox::setupContent(
not_null<Main::Session*> session,
const QString &url, const QString &url,
const QString &domain, const QString &domain,
UserData *bot, UserData *bot,
@ -174,7 +176,7 @@ not_null<Ui::RpWidget*> UrlAuthBox::setupContent(
textcmdStartSemibold() + domain + textcmdStopSemibold(), textcmdStartSemibold() + domain + textcmdStopSemibold(),
lt_user, lt_user,
(textcmdStartSemibold() (textcmdStartSemibold()
+ App::peerName(Auth().user()) + App::peerName(session->user())
+ textcmdStopSemibold()))); + textcmdStopSemibold())));
const auto allow = bot const auto allow = bot
? addCheckbox(tr::lng_url_auth_allow_messages( ? addCheckbox(tr::lng_url_auth_allow_messages(

View File

@ -12,6 +12,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
class HistoryItem; class HistoryItem;
struct HistoryMessageMarkupButton; struct HistoryMessageMarkupButton;
namespace Main {
class Session;
} // namespace Main
class UrlAuthBox : public BoxContent { class UrlAuthBox : public BoxContent {
public: public:
static void Activate( static void Activate(
@ -38,6 +42,7 @@ private:
public: public:
UrlAuthBox( UrlAuthBox(
QWidget*, QWidget*,
not_null<Main::Session*> session,
const QString &url, const QString &url,
const QString &domain, const QString &domain,
UserData *bot, UserData *bot,
@ -45,6 +50,7 @@ public:
private: private:
not_null<Ui::RpWidget*> setupContent( not_null<Ui::RpWidget*> setupContent(
not_null<Main::Session*> session,
const QString &url, const QString &url,
const QString &domain, const QString &domain,
UserData *bot, UserData *bot,

View File

@ -25,12 +25,13 @@ constexpr auto kMinUsernameLength = 5;
} // namespace } // namespace
UsernameBox::UsernameBox(QWidget*) UsernameBox::UsernameBox(QWidget*, not_null<Main::Session*> session)
: _username( : _session(session)
, _username(
this, this,
st::defaultInputField, st::defaultInputField,
rpl::single(qsl("@username")), rpl::single(qsl("@username")),
Auth().user()->username, session->user()->username,
false) false)
, _link(this, QString(), st::boxLinkButton) , _link(this, QString(), st::boxLinkButton)
, _about(st::boxWidth - st::usernamePadding.left()) , _about(st::boxWidth - st::usernamePadding.left())
@ -38,7 +39,7 @@ UsernameBox::UsernameBox(QWidget*)
} }
void UsernameBox::prepare() { void UsernameBox::prepare() {
_goodText = Auth().user()->username.isEmpty() _goodText = _session->user()->username.isEmpty()
? QString() ? QString()
: tr::lng_username_available(tr::now); : tr::lng_username_available(tr::now);
@ -171,7 +172,7 @@ void UsernameBox::linkClick() {
} }
void UsernameBox::onUpdateDone(const MTPUser &user) { void UsernameBox::onUpdateDone(const MTPUser &user) {
Auth().data().processUser(user); _session->data().processUser(user);
closeBox(); closeBox();
} }
@ -179,7 +180,7 @@ bool UsernameBox::onUpdateFail(const RPCError &error) {
if (MTP::isDefaultHandledError(error)) return false; if (MTP::isDefaultHandledError(error)) return false;
_saveRequestId = 0; _saveRequestId = 0;
const auto self = Auth().user(); const auto self = _session->user();
const auto &err = error.type(); const auto &err = error.type();
if (err == qstr("USERNAME_NOT_MODIFIED") || _sentUsername == self->username) { if (err == qstr("USERNAME_NOT_MODIFIED") || _sentUsername == self->username) {
self->setName( self->setName(
@ -209,7 +210,7 @@ bool UsernameBox::onUpdateFail(const RPCError &error) {
void UsernameBox::onCheckDone(const MTPBool &result) { void UsernameBox::onCheckDone(const MTPBool &result) {
_checkRequestId = 0; _checkRequestId = 0;
const auto newError = (mtpIsTrue(result) const auto newError = (mtpIsTrue(result)
|| _checkUsername == Auth().user()->username) || _checkUsername == _session->user()->username)
? QString() ? QString()
: tr::lng_username_occupied(tr::now); : tr::lng_username_occupied(tr::now);
const auto newGood = newError.isEmpty() const auto newGood = newError.isEmpty()
@ -231,7 +232,7 @@ bool UsernameBox::onCheckFail(const RPCError &error) {
_errorText = tr::lng_username_invalid(tr::now); _errorText = tr::lng_username_invalid(tr::now);
update(); update();
return true; return true;
} else if (err == qstr("USERNAME_OCCUPIED") && _checkUsername != Auth().user()->username) { } else if (err == qstr("USERNAME_OCCUPIED") && _checkUsername != _session->user()->username) {
_errorText = tr::lng_username_occupied(tr::now); _errorText = tr::lng_username_occupied(tr::now);
update(); update();
return true; return true;

View File

@ -14,9 +14,13 @@ class UsernameInput;
class LinkButton; class LinkButton;
} // namespace Ui } // namespace Ui
namespace Main {
class Session;
} // namespace Main
class UsernameBox : public BoxContent, public RPCSender { class UsernameBox : public BoxContent, public RPCSender {
public: public:
UsernameBox(QWidget*); UsernameBox(QWidget*, not_null<Main::Session*> session);
protected: protected:
void prepare() override; void prepare() override;
@ -42,6 +46,8 @@ private:
QString getName() const; QString getName() const;
void updateLinkText(); void updateLinkText();
const not_null<Main::Session*> _session;
object_ptr<Ui::UsernameInput> _username; object_ptr<Ui::UsernameInput> _username;
object_ptr<Ui::LinkButton> _link; object_ptr<Ui::LinkButton> _link;

View File

@ -20,6 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "main/main_session.h" #include "main/main_session.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_media_types.h" #include "data/data_media_types.h"
#include "data/data_user.h"
namespace Calls { namespace Calls {
namespace { namespace {
@ -234,7 +235,8 @@ void BoxController::prepare() {
delegate()->peerListRefreshRows(); delegate()->peerListRefreshRows();
} }
}, lifetime()); }, lifetime());
subscribe(Current().newServiceMessage(), [=](FullMsgId msgId) {
subscribe(session().calls().newServiceMessage(), [=](FullMsgId msgId) {
if (const auto item = session().data().message(msgId)) { if (const auto item = session().data().message(msgId)) {
insertRow(item, InsertWay::Prepend); insertRow(item, InsertWay::Prepend);
} }
@ -308,7 +310,7 @@ void BoxController::rowActionClicked(not_null<PeerListRow*> row) {
auto user = row->peer()->asUser(); auto user = row->peer()->asUser();
Assert(user != nullptr); Assert(user != nullptr);
Current().startOutgoingCall(user); user->session().calls().startOutgoingCall(user);
} }
void BoxController::receivedCalls(const QVector<MTPMessage> &result) { void BoxController::receivedCalls(const QVector<MTPMessage> &result) {

View File

@ -204,7 +204,7 @@ void Call::startOutgoing() {
setState(State::Waiting); setState(State::Waiting);
auto &call = result.c_phone_phoneCall(); auto &call = result.c_phone_phoneCall();
Auth().data().processUsers(call.vusers()); _user->session().data().processUsers(call.vusers());
if (call.vphone_call().type() != mtpc_phoneCallWaiting) { if (call.vphone_call().type() != mtpc_phoneCallWaiting) {
LOG(("Call Error: Expected phoneCallWaiting in response to phone.requestCall()")); LOG(("Call Error: Expected phoneCallWaiting in response to phone.requestCall()"));
finish(FinishType::Failed); finish(FinishType::Failed);
@ -277,7 +277,7 @@ void Call::actuallyAnswer() {
)).done([=](const MTPphone_PhoneCall &result) { )).done([=](const MTPphone_PhoneCall &result) {
Expects(result.type() == mtpc_phone_phoneCall); Expects(result.type() == mtpc_phone_phoneCall);
auto &call = result.c_phone_phoneCall(); auto &call = result.c_phone_phoneCall();
Auth().data().processUsers(call.vusers()); _user->session().data().processUsers(call.vusers());
if (call.vphone_call().type() != mtpc_phoneCallWaiting) { if (call.vphone_call().type() != mtpc_phoneCallWaiting) {
LOG(("Call Error: " LOG(("Call Error: "
"Not phoneCallWaiting in response to phone.acceptCall.")); "Not phoneCallWaiting in response to phone.acceptCall."));
@ -334,7 +334,7 @@ QString Call::getDebugLog() const {
void Call::startWaitingTrack() { void Call::startWaitingTrack() {
_waitingTrack = Media::Audio::Current().createTrack(); _waitingTrack = Media::Audio::Current().createTrack();
auto trackFileName = Auth().settings().getSoundPath( auto trackFileName = _user->session().settings().getSoundPath(
(_type == Type::Outgoing) (_type == Type::Outgoing)
? qsl("call_outgoing") ? qsl("call_outgoing")
: qsl("call_incoming")); : qsl("call_incoming"));
@ -374,10 +374,10 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
|| peerToUser(_user->id) != data.vadmin_id().v) { || peerToUser(_user->id) != data.vadmin_id().v) {
Unexpected("phoneCallRequested call inside an existing call handleUpdate()"); Unexpected("phoneCallRequested call inside an existing call handleUpdate()");
} }
if (Auth().userId() != data.vparticipant_id().v) { if (_user->session().userId() != data.vparticipant_id().v) {
LOG(("Call Error: Wrong call participant_id %1, expected %2." LOG(("Call Error: Wrong call participant_id %1, expected %2."
).arg(data.vparticipant_id().v ).arg(data.vparticipant_id().v
).arg(Auth().userId())); ).arg(_user->session().userId()));
finish(FinishType::Failed); finish(FinishType::Failed);
return true; return true;
} }
@ -446,7 +446,7 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
} }
} }
if (data.is_need_rating() && _id && _accessHash) { if (data.is_need_rating() && _id && _accessHash) {
Ui::show(Box<RateCallBox>(&Auth(), _id, _accessHash)); Ui::show(Box<RateCallBox>(&_user->session(), _id, _accessHash));
} }
const auto reason = data.vreason(); const auto reason = data.vreason();
if (reason && reason->type() == mtpc_phoneCallDiscardReasonDisconnect) { if (reason && reason->type() == mtpc_phoneCallDiscardReasonDisconnect) {
@ -516,7 +516,7 @@ void Call::confirmAcceptedCall(const MTPDphoneCallAccepted &call) {
Expects(result.type() == mtpc_phone_phoneCall); Expects(result.type() == mtpc_phone_phoneCall);
auto &call = result.c_phone_phoneCall(); auto &call = result.c_phone_phoneCall();
Auth().data().processUsers(call.vusers()); _user->session().data().processUsers(call.vusers());
if (call.vphone_call().type() != mtpc_phoneCall) { if (call.vphone_call().type() != mtpc_phoneCall) {
LOG(("Call Error: Expected phoneCall in response to phone.confirmCall()")); LOG(("Call Error: Expected phoneCall in response to phone.confirmCall()"));
finish(FinishType::Failed); finish(FinishType::Failed);
@ -702,8 +702,8 @@ bool Call::checkCallCommonFields(const T &call) {
LOG(("Call Error: Wrong call access_hash.")); LOG(("Call Error: Wrong call access_hash."));
return checkFailed(); return checkFailed();
} }
auto adminId = (_type == Type::Outgoing) ? Auth().userId() : peerToUser(_user->id); auto adminId = (_type == Type::Outgoing) ? _user->session().userId() : peerToUser(_user->id);
auto participantId = (_type == Type::Outgoing) ? peerToUser(_user->id) : Auth().userId(); auto participantId = (_type == Type::Outgoing) ? peerToUser(_user->id) : _user->session().userId();
if (call.vadmin_id().v != adminId) { if (call.vadmin_id().v != adminId) {
LOG(("Call Error: Wrong call admin_id %1, expected %2.").arg(call.vadmin_id().v).arg(adminId)); LOG(("Call Error: Wrong call admin_id %1, expected %2.").arg(call.vadmin_id().v).arg(adminId));
return checkFailed(); return checkFailed();
@ -848,10 +848,10 @@ void Call::finish(FinishType type, const MTPPhoneCallDiscardReason &reason) {
reason, reason,
MTP_long(connectionId) MTP_long(connectionId)
)).done([=](const MTPUpdates &result) { )).done([=](const MTPUpdates &result) {
// This could be destroyed by updates, so we set Ended after // Here 'this' could be destroyed by updates, so we set Ended after
// updates being handled, but in a guarded way. // updates being handled, but in a guarded way.
crl::on_main(this, [=] { setState(finalState); }); crl::on_main(this, [=] { setState(finalState); });
Auth().api().applyUpdates(result); _user->session().api().applyUpdates(result);
}).fail([this, finalState](const RPCError &error) { }).fail([this, finalState](const RPCError &error) {
setState(finalState); setState(finalState);
}).send(); }).send();

View File

@ -30,7 +30,8 @@ constexpr auto kServerConfigUpdateTimeoutMs = 24 * 3600 * crl::time(1000);
} // namespace } // namespace
Instance::Instance() = default; Instance::Instance(not_null<Main::Session*> session) : _session(session) {
}
void Instance::startOutgoingCall(not_null<UserData*> user) { void Instance::startOutgoingCall(not_null<UserData*> user) {
if (alreadyInCall()) { // Already in a call. if (alreadyInCall()) { // Already in a call.
@ -39,7 +40,7 @@ void Instance::startOutgoingCall(not_null<UserData*> user) {
} }
if (user->callsStatus() == UserData::CallsStatus::Private) { if (user->callsStatus() == UserData::CallsStatus::Private) {
// Request full user once more to refresh the setting in case it was changed. // Request full user once more to refresh the setting in case it was changed.
Auth().api().requestFullPeer(user); _session->api().requestFullPeer(user);
Ui::show(Box<InformBox>(tr::lng_call_error_not_available(tr::now, lt_user, App::peerName(user)))); Ui::show(Box<InformBox>(tr::lng_call_error_not_available(tr::now, lt_user, App::peerName(user))));
return; return;
} }
@ -68,7 +69,7 @@ void Instance::playSound(Sound sound) {
if (!_callBusyTrack) { if (!_callBusyTrack) {
_callBusyTrack = Media::Audio::Current().createTrack(); _callBusyTrack = Media::Audio::Current().createTrack();
_callBusyTrack->fillFromFile( _callBusyTrack->fillFromFile(
Auth().settings().getSoundPath(qsl("call_busy"))); _session->settings().getSoundPath(qsl("call_busy")));
} }
_callBusyTrack->playOnce(); _callBusyTrack->playOnce();
} break; } break;
@ -77,7 +78,7 @@ void Instance::playSound(Sound sound) {
if (!_callEndedTrack) { if (!_callEndedTrack) {
_callEndedTrack = Media::Audio::Current().createTrack(); _callEndedTrack = Media::Audio::Current().createTrack();
_callEndedTrack->fillFromFile( _callEndedTrack->fillFromFile(
Auth().settings().getSoundPath(qsl("call_end"))); _session->settings().getSoundPath(qsl("call_end")));
} }
_callEndedTrack->playOnce(); _callEndedTrack->playOnce();
} break; } break;
@ -86,7 +87,7 @@ void Instance::playSound(Sound sound) {
if (!_callConnectingTrack) { if (!_callConnectingTrack) {
_callConnectingTrack = Media::Audio::Current().createTrack(); _callConnectingTrack = Media::Audio::Current().createTrack();
_callConnectingTrack->fillFromFile( _callConnectingTrack->fillFromFile(
Auth().settings().getSoundPath(qsl("call_connect"))); _session->settings().getSoundPath(qsl("call_connect")));
} }
_callConnectingTrack->playOnce(); _callConnectingTrack->playOnce();
} break; } break;
@ -236,7 +237,7 @@ bool Instance::isQuitPrevent() {
void Instance::handleCallUpdate(const MTPPhoneCall &call) { void Instance::handleCallUpdate(const MTPPhoneCall &call) {
if (call.type() == mtpc_phoneCallRequested) { if (call.type() == mtpc_phoneCallRequested) {
auto &phoneCall = call.c_phoneCallRequested(); auto &phoneCall = call.c_phoneCallRequested();
auto user = Auth().data().userLoaded(phoneCall.vadmin_id().v); auto user = _session->data().userLoaded(phoneCall.vadmin_id().v);
if (!user) { if (!user) {
LOG(("API Error: User not loaded for phoneCallRequested.")); LOG(("API Error: User not loaded for phoneCallRequested."));
} else if (user->isSelf()) { } else if (user->isSelf()) {
@ -303,8 +304,4 @@ Instance::~Instance() {
} }
} }
Instance &Current() {
return Auth().calls();
}
} // namespace Calls } // namespace Calls

View File

@ -16,13 +16,21 @@ class Track;
} // namespace Audio } // namespace Audio
} // namespace Media } // namespace Media
namespace Main {
class Session;
} // namespace Main
namespace Calls { namespace Calls {
class Panel; class Panel;
class Instance : private MTP::Sender, private Call::Delegate, private base::Subscriber, public base::has_weak_ptr { class Instance
: private MTP::Sender
, private Call::Delegate
, private base::Subscriber
, public base::has_weak_ptr {
public: public:
Instance(); explicit Instance(not_null<Main::Session*> session);
void startOutgoingCall(not_null<UserData*> user); void startOutgoingCall(not_null<UserData*> user);
void handleUpdate(const MTPDupdatePhoneCall &update); void handleUpdate(const MTPDupdatePhoneCall &update);
@ -65,6 +73,8 @@ private:
bool alreadyInCall(); bool alreadyInCall();
void handleCallUpdate(const MTPPhoneCall &call); void handleCallUpdate(const MTPPhoneCall &call);
const not_null<Main::Session*> _session;
DhConfig _dhConfig; DhConfig _dhConfig;
crl::time _lastServerConfigUpdateTime = 0; crl::time _lastServerConfigUpdateTime = 0;
@ -82,6 +92,4 @@ private:
}; };
Instance &Current();
} // namespace Calls } // namespace Calls

View File

@ -430,7 +430,8 @@ void Panel::initLayout() {
) | rpl::start_with_next( ) | rpl::start_with_next(
[this] { processUserPhoto(); }, [this] { processUserPhoto(); },
lifetime()); lifetime());
subscribe(Auth().downloaderTaskFinished(), [this] {
subscribe(_user->session().downloaderTaskFinished(), [=] {
refreshUserPhoto(); refreshUserPhoto();
}); });
createDefaultCacheImage(); createDefaultCacheImage();

View File

@ -15,6 +15,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "calls/calls_instance.h" #include "calls/calls_instance.h"
#include "calls/calls_panel.h" #include "calls/calls_panel.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "main/main_session.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "boxes/abstract_box.h" #include "boxes/abstract_box.h"
#include "base/timer.h" #include "base/timer.h"
@ -89,13 +90,13 @@ TopBar::TopBar(
} }
void TopBar::initControls() { void TopBar::initControls() {
_mute->setClickedCallback([this] { _mute->setClickedCallback([=] {
if (auto call = _call.get()) { if (const auto call = _call.get()) {
call->setMute(!call->isMute()); call->setMute(!call->isMute());
} }
}); });
setMuted(_call->isMute()); setMuted(_call->isMute());
subscribe(_call->muteChanged(), [this](bool mute) { subscribe(_call->muteChanged(), [=](bool mute) {
setMuted(mute); setMuted(mute);
update(); update();
}); });
@ -107,13 +108,13 @@ void TopBar::initControls() {
} }
})); }));
setInfoLabels(); setInfoLabels();
_info->setClickedCallback([this] { _info->setClickedCallback([=] {
if (auto call = _call.get()) { if (const auto call = _call.get()) {
if (Logs::DebugEnabled() if (Logs::DebugEnabled()
&& (_info->clickModifiers() & Qt::ControlModifier)) { && (_info->clickModifiers() & Qt::ControlModifier)) {
Ui::show(Box<DebugInfoBox>(_call)); Ui::show(Box<DebugInfoBox>(_call));
} else { } else {
Current().showInfoPanel(call); call->user()->session().calls().showInfoPanel(call);
} }
} }
}); });

View File

@ -18,6 +18,10 @@ class LabelSimple;
class FlatLabel; class FlatLabel;
} // namespace Ui } // namespace Ui
namespace Main {
class Session;
} // namespace Main
namespace Calls { namespace Calls {
class Call; class Call;
@ -42,7 +46,7 @@ private:
void startDurationUpdateTimer(crl::time currentDuration); void startDurationUpdateTimer(crl::time currentDuration);
void setMuted(bool mute); void setMuted(bool mute);
base::weak_ptr<Call> _call; const base::weak_ptr<Call> _call;
bool _muted = false; bool _muted = false;
object_ptr<Ui::LabelSimple> _durationLabel; object_ptr<Ui::LabelSimple> _durationLabel;

View File

@ -80,7 +80,7 @@ void ApplyArchivedResult(const MTPDmessages_stickerSetInstallResultArchive &d) {
toast.multiline = true; toast.multiline = true;
toast.padding = st::stickersToastPadding; toast.padding = st::stickersToastPadding;
Ui::Toast::Show(toast); Ui::Toast::Show(toast);
// Ui::show(Box<StickersBox>(archived), LayerOption::KeepOther); // Ui::show(Box<StickersBox>(archived, &Auth()), LayerOption::KeepOther);
Auth().data().notifyStickersUpdated(); Auth().data().notifyStickersUpdated();
} }

View File

@ -144,7 +144,7 @@ private:
void resizeSearchControls(); void resizeSearchControls();
void scrollByWheelEvent(not_null<QWheelEvent*> e); void scrollByWheelEvent(not_null<QWheelEvent*> e);
not_null<StickersListWidget*> _pan; const not_null<StickersListWidget*> _pan;
static constexpr auto kVisibleIconsCount = 8; static constexpr auto kVisibleIconsCount = 8;
@ -501,9 +501,11 @@ void StickersListWidget::Footer::mousePressEvent(QMouseEvent *e) {
updateSelected(); updateSelected();
if (_iconOver == SpecialOver::Settings) { if (_iconOver == SpecialOver::Settings) {
Ui::show(Box<StickersBox>(hasOnlyFeaturedSets() Ui::show(Box<StickersBox>(
? StickersBox::Section::Featured &_pan->controller()->session(),
: StickersBox::Section::Installed)); (hasOnlyFeaturedSets()
? StickersBox::Section::Featured
: StickersBox::Section::Installed)));
} else if (_iconOver == SpecialOver::Search) { } else if (_iconOver == SpecialOver::Search) {
toggleSearch(true); toggleSearch(true);
} else { } else {
@ -833,8 +835,10 @@ StickersListWidget::StickersListWidget(
setMouseTracking(true); setMouseTracking(true);
setAttribute(Qt::WA_OpaquePaintEvent); setAttribute(Qt::WA_OpaquePaintEvent);
_settings->addClickHandler([] { _settings->addClickHandler([=] {
Ui::show(Box<StickersBox>(StickersBox::Section::Installed)); Ui::show(Box<StickersBox>(
&controller->session(),
StickersBox::Section::Installed));
}); });
subscribe(session().downloaderTaskFinished(), [=] { subscribe(session().downloaderTaskFinished(), [=] {

View File

@ -1177,7 +1177,8 @@ void History::applyServiceChanges(
} break; } break;
case mtpc_messageActionPhoneCall: { case mtpc_messageActionPhoneCall: {
Calls::Current().newServiceMessage().notify(item->fullId()); item->history()->session().calls().newServiceMessage().notify(
item->fullId());
} break; } break;
} }
} }

View File

@ -184,7 +184,7 @@ void TopBarWidget::onSearch() {
void TopBarWidget::onCall() { void TopBarWidget::onCall() {
if (const auto peer = _activeChat.peer()) { if (const auto peer = _activeChat.peer()) {
if (const auto user = peer->asUser()) { if (const auto user = peer->asUser()) {
Calls::Current().startOutgoingCall(user); user->session().calls().startOutgoingCall(user);
} }
} }
} }

View File

@ -15,6 +15,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "history/view/history_view_cursor_state.h" #include "history/view/history_view_cursor_state.h"
#include "calls/calls_instance.h" #include "calls/calls_instance.h"
#include "data/data_media_types.h" #include "data/data_media_types.h"
#include "data/data_user.h"
#include "main/main_session.h"
#include "styles/style_history.h" #include "styles/style_history.h"
namespace HistoryView { namespace HistoryView {
@ -48,7 +50,7 @@ QSize Call::countOptimalSize() {
const auto user = _parent->data()->history()->peer->asUser(); const auto user = _parent->data()->history()->peer->asUser();
_link = std::make_shared<LambdaClickHandler>([=] { _link = std::make_shared<LambdaClickHandler>([=] {
if (user) { if (user) {
Calls::Current().startOutgoingCall(user); user->session().calls().startOutgoingCall(user);
} }
}); });

View File

@ -495,7 +495,7 @@ void WrapWidget::addProfileCallsButton() {
? st::infoLayerTopBarCall ? st::infoLayerTopBarCall
: st::infoTopBarCall)) : st::infoTopBarCall))
)->addClickHandler([=] { )->addClickHandler([=] {
Calls::Current().startOutgoingCall(user); user->session().calls().startOutgoingCall(user);
}); });
}, _topBar->lifetime()); }, _topBar->lifetime());

View File

@ -512,7 +512,7 @@ Session::Session(
, _autoLockTimer([=] { checkAutoLock(); }) , _autoLockTimer([=] { checkAutoLock(); })
, _api(std::make_unique<ApiWrap>(this)) , _api(std::make_unique<ApiWrap>(this))
, _appConfig(std::make_unique<AppConfig>(this)) , _appConfig(std::make_unique<AppConfig>(this))
, _calls(std::make_unique<Calls::Instance>()) , _calls(std::make_unique<Calls::Instance>(this))
, _downloader(std::make_unique<Storage::Downloader>(_api.get())) , _downloader(std::make_unique<Storage::Downloader>(_api.get()))
, _uploader(std::make_unique<Storage::Uploader>(_api.get())) , _uploader(std::make_unique<Storage::Uploader>(_api.get()))
, _storage(std::make_unique<Storage::Facade>()) , _storage(std::make_unique<Storage::Facade>())

View File

@ -4295,7 +4295,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
} break; } break;
case mtpc_updatePhoneCall: { case mtpc_updatePhoneCall: {
Calls::Current().handleUpdate(update.c_updatePhoneCall()); session().calls().handleUpdate(update.c_updatePhoneCall());
} break; } break;
case mtpc_updateUserBlocked: { case mtpc_updateUserBlocked: {

View File

@ -51,13 +51,14 @@ Float::Float(
prepareShadow(); prepareShadow();
Auth().data().itemRepaintRequest( _controller->session().data().itemRepaintRequest(
) | rpl::start_with_next([this](auto item) { ) | rpl::start_with_next([this](auto item) {
if (_item == item) { if (_item == item) {
repaintItem(); repaintItem();
} }
}, lifetime()); }, lifetime());
Auth().data().itemRemoved(
_controller->session().data().itemRemoved(
) | rpl::start_with_next([this](auto item) { ) | rpl::start_with_next([this](auto item) {
if (_item == item) { if (_item == item) {
detach(); detach();
@ -360,7 +361,7 @@ void FloatController::checkCurrent() {
if (last) { if (last) {
last->widget->detach(); last->widget->detach();
} }
if (const auto item = Auth().data().message(fullId)) { if (const auto item = _controller->session().data().message(fullId)) {
if (const auto media = item->media()) { if (const auto media = item->media()) {
if (const auto document = media->document()) { if (const auto document = media->document()) {
if (document->isVideoMessage()) { if (document->isVideoMessage()) {
@ -383,8 +384,8 @@ void FloatController::create(not_null<HistoryItem*> item) {
[=](not_null<Item*> instance, bool closed) { [=](not_null<Item*> instance, bool closed) {
finishDrag(instance, closed); finishDrag(instance, closed);
})); }));
current()->column = Auth().settings().floatPlayerColumn(); current()->column = _controller->session().settings().floatPlayerColumn();
current()->corner = Auth().settings().floatPlayerCorner(); current()->corner = _controller->session().settings().floatPlayerCorner();
checkVisibility(); checkVisibility();
} }
@ -557,8 +558,8 @@ void FloatController::updateColumnCorner(QPoint center) {
auto size = _items.back()->widget->size(); auto size = _items.back()->widget->size();
auto min = INT_MAX; auto min = INT_MAX;
auto column = Auth().settings().floatPlayerColumn(); auto column = _controller->session().settings().floatPlayerColumn();
auto corner = Auth().settings().floatPlayerCorner(); auto corner = _controller->session().settings().floatPlayerCorner();
auto checkSection = [&]( auto checkSection = [&](
not_null<Window::AbstractSectionWidget*> widget, not_null<Window::AbstractSectionWidget*> widget,
Window::Column widgetColumn) { Window::Column widgetColumn) {
@ -583,13 +584,13 @@ void FloatController::updateColumnCorner(QPoint center) {
_delegate->floatPlayerEnumerateSections(checkSection); _delegate->floatPlayerEnumerateSections(checkSection);
if (Auth().settings().floatPlayerColumn() != column) { if (_controller->session().settings().floatPlayerColumn() != column) {
Auth().settings().setFloatPlayerColumn(column); _controller->session().settings().setFloatPlayerColumn(column);
Auth().saveSettingsDelayed(); _controller->session().saveSettingsDelayed();
} }
if (Auth().settings().floatPlayerCorner() != corner) { if (_controller->session().settings().floatPlayerCorner() != corner) {
Auth().settings().setFloatPlayerCorner(corner); _controller->session().settings().setFloatPlayerCorner(corner);
Auth().saveSettingsDelayed(); _controller->session().saveSettingsDelayed();
} }
} }
@ -601,8 +602,8 @@ void FloatController::finishDrag(not_null<Item*> instance, bool closed) {
instance->animationSide = getSide(center); instance->animationSide = getSide(center);
} }
updateColumnCorner(center); updateColumnCorner(center);
instance->column = Auth().settings().floatPlayerColumn(); instance->column = _controller->session().settings().floatPlayerColumn();
instance->corner = Auth().settings().floatPlayerCorner(); instance->corner = _controller->session().settings().floatPlayerCorner();
instance->draggedAnimation.stop(); instance->draggedAnimation.stop();
instance->draggedAnimation.start( instance->draggedAnimation.start(

View File

@ -227,7 +227,9 @@ void Panel::refreshList() {
const auto current = instance()->current(AudioMsgId::Type::Song); const auto current = instance()->current(AudioMsgId::Type::Song);
const auto contextId = current.contextId(); const auto contextId = current.contextId();
const auto peer = [&]() -> PeerData* { const auto peer = [&]() -> PeerData* {
const auto item = contextId ? Auth().data().message(contextId) : nullptr; const auto item = contextId
? session().data().message(contextId)
: nullptr;
const auto media = item ? item->media() : nullptr; const auto media = item ? item->media() : nullptr;
const auto document = media ? media->document() : nullptr; const auto document = media ? media->document() : nullptr;
if (!document || !document->isSharedMediaMusic()) { if (!document || !document->isSharedMediaMusic()) {

View File

@ -23,10 +23,10 @@ VolumeController::VolumeController(QWidget *parent)
: TWidget(parent) : TWidget(parent)
, _slider(this, st::mediaPlayerPanelPlayback) { , _slider(this, st::mediaPlayerPanelPlayback) {
_slider->setMoveByWheel(true); _slider->setMoveByWheel(true);
_slider->setChangeProgressCallback([this](float64 volume) { _slider->setChangeProgressCallback([=](float64 volume) {
applyVolumeChange(volume); applyVolumeChange(volume);
}); });
_slider->setChangeFinishedCallback([this](float64 volume) { _slider->setChangeFinishedCallback([=](float64 volume) {
if (volume > 0) { if (volume > 0) {
Global::SetRememberedSongVolume(volume); Global::SetRememberedSongVolume(volume);
} }

View File

@ -24,6 +24,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "media/audio/media_audio.h" #include "media/audio/media_audio.h"
#include "media/player/media_player_instance.h" #include "media/player/media_player_instance.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "history/history.h"
#include "history/history_item.h" #include "history/history_item.h"
#include "history/history_item_components.h" #include "history/history_item_components.h"
#include "history/view/history_view_cursor_state.h" #include "history/view/history_view_cursor_state.h"
@ -138,7 +139,7 @@ QDateTime ItemBase::dateTime() const {
void ItemBase::clickHandlerActiveChanged( void ItemBase::clickHandlerActiveChanged(
const ClickHandlerPtr &action, const ClickHandlerPtr &action,
bool active) { bool active) {
Auth().data().requestItemRepaint(_parent); _parent->history()->session().data().requestItemRepaint(_parent);
if (_check) { if (_check) {
_check->setActive(active); _check->setActive(active);
} }
@ -147,7 +148,7 @@ void ItemBase::clickHandlerActiveChanged(
void ItemBase::clickHandlerPressedChanged( void ItemBase::clickHandlerPressedChanged(
const ClickHandlerPtr &action, const ClickHandlerPtr &action,
bool pressed) { bool pressed) {
Auth().data().requestItemRepaint(_parent); _parent->history()->session().data().requestItemRepaint(_parent);
if (_check) { if (_check) {
_check->setPressed(pressed); _check->setPressed(pressed);
} }
@ -178,9 +179,10 @@ const style::RoundCheckbox &ItemBase::checkboxStyle() const {
void ItemBase::ensureCheckboxCreated() { void ItemBase::ensureCheckboxCreated() {
if (!_check) { if (!_check) {
_check = std::make_unique<Checkbox>( const auto repaint = [=] {
[=] { Auth().data().requestItemRepaint(_parent); }, _parent->history()->session().data().requestItemRepaint(_parent);
checkboxStyle()); };
_check = std::make_unique<Checkbox>(repaint, checkboxStyle());
} }
} }
@ -201,8 +203,12 @@ void RadialProgressItem::clickHandlerActiveChanged(
ItemBase::clickHandlerActiveChanged(action, active); ItemBase::clickHandlerActiveChanged(action, active);
if (action == _openl || action == _savel || action == _cancell) { if (action == _openl || action == _savel || action == _cancell) {
if (iconAnimated()) { if (iconAnimated()) {
const auto repaint = [=] {
parent()->history()->session().data().requestItemRepaint(
parent());
};
_a_iconOver.start( _a_iconOver.start(
[=] { Auth().data().requestItemRepaint(parent()); }, repaint,
active ? 0. : 1., active ? 0. : 1.,
active ? 1. : 0., active ? 1. : 0.,
st::msgFileOverDuration); st::msgFileOverDuration);
@ -224,7 +230,7 @@ void RadialProgressItem::radialAnimationCallback(crl::time now) const {
return _radial->update(dataProgress(), dataFinished(), now); return _radial->update(dataProgress(), dataFinished(), now);
}(); }();
if (!anim::Disabled() || updated) { if (!anim::Disabled() || updated) {
Auth().data().requestItemRepaint(parent()); parent()->history()->session().data().requestItemRepaint(parent());
} }
if (!_radial->animating()) { if (!_radial->animating()) {
checkRadialFinished(); checkRadialFinished();

View File

@ -20,6 +20,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/text/text_utilities.h" // Ui::Text::ToUpper #include "ui/text/text_utilities.h" // Ui::Text::ToUpper
#include "boxes/abstract_box.h" #include "boxes/abstract_box.h"
#include "boxes/confirm_phone_box.h" #include "boxes/confirm_phone_box.h"
#include "data/data_user.h"
#include "main/main_session.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "styles/style_passport.h" #include "styles/style_passport.h"
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
@ -274,6 +276,7 @@ void PanelEditContact::setupControls(
wrap.data(), wrap.data(),
fieldStyle, fieldStyle,
std::move(fieldPlaceholder), std::move(fieldPlaceholder),
ExtractPhonePrefix(_controller->bot()->session().user()->phone()),
data); data);
} else { } else {
_field = Ui::CreateChild<Ui::MaskedInputField>( _field = Ui::CreateChild<Ui::MaskedInputField>(

View File

@ -22,6 +22,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "layout.h" #include "layout.h"
#include "styles/style_settings.h" #include "styles/style_settings.h"
#include "ui/widgets/continuous_sliders.h" #include "ui/widgets/continuous_sliders.h"
#include "window/window_session_controller.h"
#include "calls/calls_instance.h" #include "calls/calls_instance.h"
#ifdef slots #ifdef slots
@ -128,7 +129,7 @@ void Calls::setupContent(not_null<Window::SessionController*> controller) {
: "default"; : "default";
Global::SetCallOutputDeviceID(QString::fromStdString(deviceId)); Global::SetCallOutputDeviceID(QString::fromStdString(deviceId));
Local::writeUserSettings(); Local::writeUserSettings();
if (const auto call = ::Calls::Current().currentCall()) { if (const auto call = controller->session().calls().currentCall()) {
call->setCurrentAudioDevice(false, deviceId); call->setCurrentAudioDevice(false, deviceId);
} }
}); });
@ -158,7 +159,7 @@ void Calls::setupContent(not_null<Window::SessionController*> controller) {
_needWriteSettings = true; _needWriteSettings = true;
updateOutputLabel(value); updateOutputLabel(value);
Global::SetCallOutputVolume(value); Global::SetCallOutputVolume(value);
if (const auto call = ::Calls::Current().currentCall()) { if (const auto call = controller->session().calls().currentCall()) {
call->setAudioVolume(false, value / 100.0f); call->setAudioVolume(false, value / 100.0f);
} }
}; };
@ -206,7 +207,7 @@ void Calls::setupContent(not_null<Window::SessionController*> controller) {
if (_micTester) { if (_micTester) {
stopTestingMicrophone(); stopTestingMicrophone();
} }
if (const auto call = ::Calls::Current().currentCall()) { if (const auto call = controller->session().calls().currentCall()) {
call->setCurrentAudioDevice(true, deviceId); call->setCurrentAudioDevice(true, deviceId);
} }
}); });
@ -236,9 +237,8 @@ void Calls::setupContent(not_null<Window::SessionController*> controller) {
_needWriteSettings = true; _needWriteSettings = true;
updateInputLabel(value); updateInputLabel(value);
Global::SetCallInputVolume(value); Global::SetCallInputVolume(value);
::Calls::Call *currentCall = ::Calls::Current().currentCall(); if (const auto call = controller->session().calls().currentCall()) {
if (currentCall) { call->setAudioVolume(true, value / 100.0f);
currentCall->setAudioVolume(true, value / 100.0f);
} }
}; };
inputSlider->resize(st::settingsAudioVolumeSlider.seekSize); inputSlider->resize(st::settingsAudioVolumeSlider.seekSize);
@ -289,10 +289,10 @@ void Calls::setupContent(not_null<Window::SessionController*> controller) {
rpl::single(Global::CallAudioDuckingEnabled()) rpl::single(Global::CallAudioDuckingEnabled())
)->toggledValue() | rpl::filter([](bool enabled) { )->toggledValue() | rpl::filter([](bool enabled) {
return (enabled != Global::CallAudioDuckingEnabled()); return (enabled != Global::CallAudioDuckingEnabled());
}) | rpl::start_with_next([](bool enabled) { }) | rpl::start_with_next([=](bool enabled) {
Global::SetCallAudioDuckingEnabled(enabled); Global::SetCallAudioDuckingEnabled(enabled);
Local::writeUserSettings(); Local::writeUserSettings();
if (const auto call = ::Calls::Current().currentCall()) { if (const auto call = controller->session().calls().currentCall()) {
call->setAudioDuckingEnabled(enabled); call->setAudioDuckingEnabled(enabled);
} }
}, content->lifetime()); }, content->lifetime());

View File

@ -506,8 +506,8 @@ void SetupStickersEmoji(
st::settingsChatButton, st::settingsChatButton,
&st::settingsIconStickers, &st::settingsIconStickers,
st::settingsChatIconLeft st::settingsChatIconLeft
)->addClickHandler([] { )->addClickHandler([=] {
Ui::show(Box<StickersBox>(StickersBox::Section::Installed)); Ui::show(Box<StickersBox>(session, StickersBox::Section::Installed));
}); });
AddButton( AddButton(

View File

@ -217,6 +217,8 @@ void AddRow(
void SetupRows( void SetupRows(
not_null<Ui::VerticalLayout*> container, not_null<Ui::VerticalLayout*> container,
not_null<UserData*> self) { not_null<UserData*> self) {
const auto session = &self->session();
AddSkip(container); AddSkip(container);
AddRow( AddRow(
@ -232,7 +234,7 @@ void SetupRows(
tr::lng_settings_phone_label(), tr::lng_settings_phone_label(),
Info::Profile::PhoneValue(self), Info::Profile::PhoneValue(self),
tr::lng_profile_copy_phone(tr::now), tr::lng_profile_copy_phone(tr::now),
[=] { Ui::show(Box<ChangePhoneBox>(&self->session())); }, [=] { Ui::show(Box<ChangePhoneBox>(session)); },
st::settingsInfoPhone); st::settingsInfoPhone);
auto username = Info::Profile::UsernameValue(self); auto username = Info::Profile::UsernameValue(self);
@ -267,7 +269,7 @@ void SetupRows(
std::move(label), std::move(label),
std::move(value), std::move(value),
tr::lng_context_copy_mention(tr::now), tr::lng_context_copy_mention(tr::now),
[=] { Ui::show(Box<UsernameBox>()); }, [=] { Ui::show(Box<UsernameBox>(session)); },
st::settingsInfoUsername); st::settingsInfoUsername);
AddSkip(container, st::settingsInfoAfterSkip); AddSkip(container, st::settingsInfoAfterSkip);

View File

@ -4317,14 +4317,15 @@ PhoneInput::PhoneInput(
QWidget *parent, QWidget *parent,
const style::InputField &st, const style::InputField &st,
rpl::producer<QString> placeholder, rpl::producer<QString> placeholder,
const QString &val) const QString &defaultValue,
: MaskedInputField(parent, st, std::move(placeholder), val) { QString value)
QString phone(val); : MaskedInputField(parent, st, std::move(placeholder), value)
if (phone.isEmpty()) { , _defaultValue(defaultValue) {
if (value.isEmpty()) {
clearText(); clearText();
} else { } else {
int32 pos = phone.size(); auto pos = value.size();
correctValue(QString(), 0, phone, pos); correctValue(QString(), 0, value, pos);
} }
} }
@ -4334,17 +4335,10 @@ void PhoneInput::focusInEvent(QFocusEvent *e) {
} }
void PhoneInput::clearText() { void PhoneInput::clearText() {
QString phone; auto value = _defaultValue;
if (Main::Session::Exists()) { setText(value);
const auto self = Auth().user(); auto pos = value.size();
QVector<int> newPattern = phoneNumberParse(self->phone()); correctValue(QString(), 0, value, pos);
if (!newPattern.isEmpty()) {
phone = self->phone().mid(0, newPattern.at(0));
}
}
setText(phone);
int32 pos = phone.size();
correctValue(QString(), 0, phone, pos);
} }
void PhoneInput::paintAdditionalPlaceholder(Painter &p) { void PhoneInput::paintAdditionalPlaceholder(Painter &p) {

View File

@ -770,7 +770,8 @@ public:
QWidget *parent, QWidget *parent,
const style::InputField &st, const style::InputField &st,
rpl::producer<QString> placeholder, rpl::producer<QString> placeholder,
const QString &val); const QString &defaultValue,
QString value);
void clearText(); void clearText();
@ -785,6 +786,7 @@ protected:
void paintAdditionalPlaceholder(Painter &p) override; void paintAdditionalPlaceholder(Painter &p) override;
private: private:
QString _defaultValue;
QVector<int> _pattern; QVector<int> _pattern;
QString _additionalPlaceholder; QString _additionalPlaceholder;