Application->Sandbox, Messenger->Application.

This commit is contained in:
John Preston 2019-01-21 17:42:21 +04:00
parent 4111da1dd0
commit a70e72f75d
117 changed files with 1363 additions and 1239 deletions

View file

@ -22,12 +22,11 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_user.h" #include "data/data_user.h"
#include "dialogs/dialogs_key.h" #include "dialogs/dialogs_key.h"
#include "core/core_cloud_password.h" #include "core/core_cloud_password.h"
#include "core/application.h"
#include "base/openssl_help.h" #include "base/openssl_help.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "boxes/add_contact_box.h" #include "boxes/add_contact_box.h"
#include "history/history.h" #include "history/history.h"
@ -329,7 +328,7 @@ void ApiWrap::requestTermsUpdate() {
const auto &data = result.c_help_termsOfServiceUpdate(); const auto &data = result.c_help_termsOfServiceUpdate();
const auto &terms = data.vterms_of_service; const auto &terms = data.vterms_of_service;
const auto &fields = terms.c_help_termsOfService(); const auto &fields = terms.c_help_termsOfService();
Messenger::Instance().lockByTerms( Core::App().lockByTerms(
Window::TermsLock::FromMTP(fields)); Window::TermsLock::FromMTP(fields));
requestNext(data); requestNext(data);
} break; } break;
@ -478,7 +477,7 @@ void ApiWrap::sendMessageFail(const RPCError &error) {
PeerFloodErrorText(PeerFloodType::Send))); PeerFloodErrorText(PeerFloodType::Send)));
} else if (error.type() == qstr("USER_BANNED_IN_CHANNEL")) { } else if (error.type() == qstr("USER_BANNED_IN_CHANNEL")) {
const auto link = textcmdLink( const auto link = textcmdLink(
Messenger::Instance().createInternalLinkFull(qsl("spambot")), Core::App().createInternalLinkFull(qsl("spambot")),
lang(lng_cant_more_info)); lang(lng_cant_more_info));
Ui::show(Box<InformBox>(lng_error_public_groups_denied( Ui::show(Box<InformBox>(lng_error_public_groups_denied(
lt_more_info, lt_more_info,
@ -2488,7 +2487,7 @@ void ApiWrap::checkQuitPreventFinished() {
if (App::quitting()) { if (App::quitting()) {
LOG(("ApiWrap doesn't prevent quit any more.")); LOG(("ApiWrap doesn't prevent quit any more."));
} }
Messenger::Instance().quitPreventFinished(); Core::App().quitPreventFinished();
} }
} }

View file

@ -7,11 +7,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/ */
#include "app.h" #include "app.h"
#include "styles/style_overview.h"
#include "styles/style_mediaview.h"
#include "styles/style_chat_helpers.h"
#include "styles/style_history.h"
#include "styles/style_boxes.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "data/data_channel.h" #include "data/data_channel.h"
@ -30,6 +25,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "inline_bots/inline_bot_layout_item.h" #include "inline_bots/inline_bot_layout_item.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"
#include "core/update_checker.h" #include "core/update_checker.h"
#include "core/sandbox.h"
#include "core/application.h"
#include "window/themes/window_theme.h" #include "window/themes/window_theme.h"
#include "window/notifications_manager.h" #include "window/notifications_manager.h"
#include "platform/platform_notifications_manager.h" #include "platform/platform_notifications_manager.h"
@ -37,14 +34,17 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "storage/storage_facade.h" #include "storage/storage_facade.h"
#include "storage/storage_shared_media.h" #include "storage/storage_shared_media.h"
#include "messenger.h"
#include "application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "numbers.h" #include "numbers.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "auth_session.h" #include "auth_session.h"
#include "styles/style_overview.h"
#include "styles/style_mediaview.h"
#include "styles/style_chat_helpers.h"
#include "styles/style_history.h"
#include "styles/style_boxes.h"
#ifdef OS_MAC_OLD #ifdef OS_MAC_OLD
#include <libexif/exif-data.h> #include <libexif/exif-data.h>
@ -117,8 +117,8 @@ namespace App {
} }
MainWindow *wnd() { MainWindow *wnd() {
if (auto instance = Messenger::InstancePointer()) { if (Core::Sandbox::Instance().applicationLaunched()) {
return instance->getActiveWindow(); return Core::App().getActiveWindow();
} }
return nullptr; return nullptr;
} }
@ -753,14 +753,14 @@ namespace App {
setLaunchState(QuitRequested); setLaunchState(QuitRequested);
if (auto window = App::wnd()) { if (auto window = App::wnd()) {
if (!Core::App().isSavingSession()) { if (!Core::Sandbox::Instance().isSavingSession()) {
window->hide(); window->hide();
} }
} }
if (auto mainwidget = App::main()) { if (auto mainwidget = App::main()) {
mainwidget->saveDraftToCloud(); mainwidget->saveDraftToCloud();
} }
Messenger::QuitAttempt(); Core::Application::QuitAttempt();
} }
bool quitting() { bool quitting() {

View file

@ -11,7 +11,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
enum NewMessageType : char; enum NewMessageType : char;
enum class ImageRoundRadius; enum class ImageRoundRadius;
class Messenger;
class MainWindow; class MainWindow;
class MainWidget; class MainWidget;
class HistoryItem; class HistoryItem;

View file

@ -8,7 +8,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "messenger.h" #include "core/application.h"
#include "core/sandbox.h"
#include "core/changelogs.h" #include "core/changelogs.h"
#include "storage/file_download.h" #include "storage/file_download.h"
#include "storage/file_upload.h" #include "storage/file_upload.h"
@ -372,7 +373,7 @@ rpl::producer<int> AuthSessionSettings::thirdColumnWidthChanges() const {
} }
AuthSession &Auth() { AuthSession &Auth() {
auto result = Messenger::Instance().authSession(); auto result = Core::App().authSession();
Assert(result != nullptr); Assert(result != nullptr);
return *result; return *result;
} }
@ -392,11 +393,11 @@ AuthSession::AuthSession(const MTPUser &user)
_saveDataTimer.setCallback([=] { _saveDataTimer.setCallback([=] {
Local::writeUserSettings(); Local::writeUserSettings();
}); });
Messenger::Instance().passcodeLockChanges( Core::App().passcodeLockChanges(
) | rpl::start_with_next([=] { ) | rpl::start_with_next([=] {
_shouldLockAt = 0; _shouldLockAt = 0;
}, _lifetime); }, _lifetime);
Messenger::Instance().lockChanges( Core::App().lockChanges(
) | rpl::start_with_next([=] { ) | rpl::start_with_next([=] {
notifications().updateAll(); notifications().updateAll();
}, _lifetime); }, _lifetime);
@ -429,10 +430,8 @@ AuthSession::AuthSession(const MTPUser &user)
} }
bool AuthSession::Exists() { bool AuthSession::Exists() {
if (const auto messenger = Messenger::InstancePointer()) { return Core::Sandbox::Instance().applicationLaunched()
return (messenger->authSession() != nullptr); && (Core::App().authSession() != nullptr);
}
return false;
} }
base::Observable<void> &AuthSession::downloaderTaskFinished() { base::Observable<void> &AuthSession::downloaderTaskFinished() {
@ -453,7 +452,7 @@ bool AuthSession::validateSelf(const MTPUser &user) {
return false; return false;
} else if (user.c_user().vid.v != userId()) { } else if (user.c_user().vid.v != userId()) {
LOG(("Auth Error: wrong self user received.")); LOG(("Auth Error: wrong self user received."));
crl::on_main(this, [] { Messenger::Instance().logOut(); }); crl::on_main(this, [] { Core::App().logOut(); });
return false; return false;
} }
return true; return true;
@ -479,18 +478,18 @@ void AuthSession::saveSettingsDelayed(TimeMs delay) {
void AuthSession::checkAutoLock() { void AuthSession::checkAutoLock() {
if (!Global::LocalPasscode() if (!Global::LocalPasscode()
|| Messenger::Instance().passcodeLocked()) { || Core::App().passcodeLocked()) {
return; return;
} }
Messenger::Instance().checkLocalTime(); Core::App().checkLocalTime();
auto now = getms(true); auto now = getms(true);
auto shouldLockInMs = Global::AutoLock() * 1000LL; auto shouldLockInMs = Global::AutoLock() * 1000LL;
auto idleForMs = psIdleTime(); auto idleForMs = psIdleTime();
auto notPlayingVideoForMs = now - settings().lastTimeVideoPlayedAt(); auto notPlayingVideoForMs = now - settings().lastTimeVideoPlayedAt();
auto checkTimeMs = qMin(idleForMs, notPlayingVideoForMs); auto checkTimeMs = qMin(idleForMs, notPlayingVideoForMs);
if (checkTimeMs >= shouldLockInMs || (_shouldLockAt > 0 && now > _shouldLockAt + kAutoLockTimeoutLateMs)) { if (checkTimeMs >= shouldLockInMs || (_shouldLockAt > 0 && now > _shouldLockAt + kAutoLockTimeoutLateMs)) {
Messenger::Instance().lockByPasscode(); Core::App().lockByPasscode();
} else { } else {
_shouldLockAt = now + (shouldLockInMs - checkTimeMs); _shouldLockAt = now + (shouldLockInMs - checkTimeMs);
_autoLockTimer.callOnce(shouldLockInMs - checkTimeMs); _autoLockTimer.callOnce(shouldLockInMs - checkTimeMs);

View file

@ -267,7 +267,6 @@ private:
}; };
// One per Messenger.
class AuthSession; class AuthSession;
AuthSession &Auth(); AuthSession &Auth();

View file

@ -10,7 +10,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
#include "styles/style_dialogs.h" #include "styles/style_dialogs.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "messenger.h"
#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"
@ -20,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/peers/edit_participant_box.h" #include "boxes/peers/edit_participant_box.h"
#include "boxes/peers/edit_participants_box.h" #include "boxes/peers/edit_participants_box.h"
#include "core/file_utilities.h" #include "core/file_utilities.h"
#include "core/application.h"
#include "chat_helpers/emoji_suggestions_widget.h" #include "chat_helpers/emoji_suggestions_widget.h"
#include "ui/widgets/checkbox.h" #include "ui/widgets/checkbox.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
@ -66,7 +66,7 @@ style::InputField CreateBioFieldStyle() {
QString PeerFloodErrorText(PeerFloodType type) { QString PeerFloodErrorText(PeerFloodType type) {
auto link = textcmdLink( auto link = textcmdLink(
Messenger::Instance().createInternalLinkFull(qsl("spambot")), Core::App().createInternalLinkFull(qsl("spambot")),
lang(lng_cant_more_info)); lang(lng_cant_more_info));
if (type == PeerFloodType::InviteGroup) { if (type == PeerFloodType::InviteGroup) {
return lng_cant_invite_not_contact(lt_more_info, link); return lng_cant_invite_not_contact(lt_more_info, link);
@ -1209,7 +1209,7 @@ RevokePublicLinkBox::Inner::Inner(QWidget *parent, Fn<void()> revokeCallback) :
Ui::NameTextOptions()); Ui::NameTextOptions());
row.status.setText( row.status.setText(
st::defaultTextStyle, st::defaultTextStyle,
Messenger::Instance().createInternalLink( Core::App().createInternalLink(
textcmdLink(1, peer->userName())), textcmdLink(1, peer->userName())),
Ui::DialogTextOptions()); Ui::DialogTextOptions());
_rows.push_back(std::move(row)); _rows.push_back(std::move(row));
@ -1284,7 +1284,7 @@ void RevokePublicLinkBox::Inner::mouseReleaseEvent(QMouseEvent *e) {
setCursor((_selected || _pressed) ? style::cur_pointer : style::cur_default); setCursor((_selected || _pressed) ? style::cur_pointer : style::cur_default);
if (pressed && pressed == _selected) { if (pressed && pressed == _selected) {
auto text_method = pressed->isMegagroup() ? lng_channels_too_much_public_revoke_confirm_group : lng_channels_too_much_public_revoke_confirm_channel; auto text_method = pressed->isMegagroup() ? lng_channels_too_much_public_revoke_confirm_group : lng_channels_too_much_public_revoke_confirm_channel;
auto text = text_method(lt_link, Messenger::Instance().createInternalLink(pressed->userName()), lt_group, pressed->name); auto text = text_method(lt_link, Core::App().createInternalLink(pressed->userName()), lt_group, pressed->name);
auto confirmText = lang(lng_channels_too_much_public_revoke); auto confirmText = lang(lng_channels_too_much_public_revoke);
_weakRevokeConfirmBox = Ui::show(Box<ConfirmBox>(text, confirmText, crl::guard(this, [this, pressed]() { _weakRevokeConfirmBox = Ui::show(Box<ConfirmBox>(text, confirmText, crl::guard(this, [this, pressed]() {
if (_revokeRequestId) return; if (_revokeRequestId) return;

View file

@ -19,10 +19,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "history/view/history_view_message.h" #include "history/view/history_view_message.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "messenger.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "data/data_document.h" #include "data/data_document.h"
#include "core/application.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "styles/style_overview.h" #include "styles/style_overview.h"
#include "styles/style_history.h" #include "styles/style_history.h"
@ -347,7 +347,7 @@ void BackgroundPreviewBox::share() {
Expects(!_paper.slug.isEmpty()); Expects(!_paper.slug.isEmpty());
QApplication::clipboard()->setText( QApplication::clipboard()->setText(
Messenger::Instance().createInternalLinkFull("bg/" + _paper.slug)); Core::App().createInternalLinkFull("bg/" + _paper.slug));
Ui::Toast::Show(lang(lng_background_link_copied)); Ui::Toast::Show(lang(lng_background_link_copied));
} }

View file

@ -12,7 +12,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "application.h"
#include "history/history.h" #include "history/history.h"
#include "history/history_item.h" #include "history/history_item.h"
#include "ui/widgets/checkbox.h" #include "ui/widgets/checkbox.h"

View file

@ -11,7 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "base/qthelp_url.h" #include "base/qthelp_url.h"
#include "messenger.h" #include "core/application.h"
#include "ui/widgets/checkbox.h" #include "ui/widgets/checkbox.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
#include "ui/widgets/input_fields.h" #include "ui/widgets/input_fields.h"
@ -975,7 +975,7 @@ void ProxiesBoxController::ShowApplyConfirmation(
if (ranges::find(proxies, proxy) == end(proxies)) { if (ranges::find(proxies, proxy) == end(proxies)) {
proxies.push_back(proxy); proxies.push_back(proxy);
} }
Messenger::Instance().setCurrentProxy( Core::App().setCurrentProxy(
proxy, proxy,
ProxyData::Settings::Enabled); ProxyData::Settings::Enabled);
Local::writeSettings(); Local::writeSettings();
@ -998,7 +998,7 @@ void ProxiesBoxController::refreshChecker(Item &item) {
const auto type = (item.data.type == Type::Http) const auto type = (item.data.type == Type::Http)
? Variants::Http ? Variants::Http
: Variants::Tcp; : Variants::Tcp;
const auto mtproto = Messenger::Instance().mtp(); const auto mtproto = Core::App().mtp();
const auto dcId = mtproto->mainDcId(); const auto dcId = mtproto->mainDcId();
item.state = ItemState::Checking; item.state = ItemState::Checking;
@ -1140,7 +1140,7 @@ void ProxiesBoxController::applyItem(int id) {
auto j = findByProxy(Global::SelectedProxy()); auto j = findByProxy(Global::SelectedProxy());
Messenger::Instance().setCurrentProxy( Core::App().setCurrentProxy(
item->data, item->data,
ProxyData::Settings::Enabled); ProxyData::Settings::Enabled);
saveDelayed(); saveDelayed();
@ -1163,7 +1163,7 @@ void ProxiesBoxController::setDeleted(int id, bool deleted) {
_lastSelectedProxy = base::take(Global::RefSelectedProxy()); _lastSelectedProxy = base::take(Global::RefSelectedProxy());
if (Global::ProxySettings() == ProxyData::Settings::Enabled) { if (Global::ProxySettings() == ProxyData::Settings::Enabled) {
_lastSelectedProxyUsed = true; _lastSelectedProxyUsed = true;
Messenger::Instance().setCurrentProxy( Core::App().setCurrentProxy(
ProxyData(), ProxyData(),
ProxyData::Settings::System); ProxyData::Settings::System);
saveDelayed(); saveDelayed();
@ -1188,7 +1188,7 @@ void ProxiesBoxController::setDeleted(int id, bool deleted) {
Assert(Global::ProxySettings() != ProxyData::Settings::Enabled); Assert(Global::ProxySettings() != ProxyData::Settings::Enabled);
if (base::take(_lastSelectedProxyUsed)) { if (base::take(_lastSelectedProxyUsed)) {
Messenger::Instance().setCurrentProxy( Core::App().setCurrentProxy(
base::take(_lastSelectedProxy), base::take(_lastSelectedProxy),
ProxyData::Settings::Enabled); ProxyData::Settings::Enabled);
} else { } else {
@ -1293,9 +1293,7 @@ bool ProxiesBoxController::setProxySettings(ProxyData::Settings value) {
} }
} }
} }
Messenger::Instance().setCurrentProxy( Core::App().setCurrentProxy(Global::SelectedProxy(), value);
Global::SelectedProxy(),
value);
saveDelayed(); saveDelayed();
return true; return true;
} }

View file

@ -24,7 +24,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h" #include "core/application.h"
#include "lang/lang_instance.h" #include "lang/lang_instance.h"
#include "lang/lang_cloud_manager.h" #include "lang/lang_cloud_manager.h"
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
@ -1132,7 +1132,7 @@ not_null<Ui::MultiSelect*> LanguageBox::createMultiSelect() {
base::binary_guard LanguageBox::Show() { base::binary_guard LanguageBox::Show() {
auto result = base::binary_guard(); auto result = base::binary_guard();
const auto manager = Messenger::Instance().langCloudManager(); const auto manager = Core::App().langCloudManager();
if (manager->languageList().empty()) { if (manager->languageList().empty()) {
auto guard = std::make_shared<base::binary_guard>(); auto guard = std::make_shared<base::binary_guard>();
std::tie(result, *guard) = base::make_binary_guard(); std::tie(result, *guard) = base::make_binary_guard();

View file

@ -31,7 +31,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/sender.h" #include "mtproto/sender.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "messenger.h" #include "core/application.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "auth_session.h" #include "auth_session.h"
#include "observer_peer.h" #include "observer_peer.h"

View file

@ -33,7 +33,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_user.h" #include "data/data_user.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "auth_session.h" #include "auth_session.h"
#include "messenger.h" #include "core/application.h"
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
#include "styles/style_history.h" #include "styles/style_history.h"

View file

@ -10,22 +10,21 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_document.h" #include "data/data_document.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mainwidget.h"
#include "mainwindow.h"
#include "chat_helpers/stickers.h" #include "chat_helpers/stickers.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "apiwrap.h" #include "core/application.h"
#include "application.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "dialogs/dialogs_layout.h" #include "dialogs/dialogs_layout.h"
#include "styles/style_boxes.h"
#include "styles/style_chat_helpers.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
#include "ui/widgets/scroll_area.h" #include "ui/widgets/scroll_area.h"
#include "ui/image/image.h" #include "ui/image/image.h"
#include "ui/emoji_config.h" #include "ui/emoji_config.h"
#include "auth_session.h" #include "auth_session.h"
#include "messenger.h" #include "apiwrap.h"
#include "mainwidget.h"
#include "mainwindow.h"
#include "styles/style_boxes.h"
#include "styles/style_chat_helpers.h"
namespace { namespace {
@ -142,7 +141,7 @@ void StickerSetBox::addStickers() {
} }
void StickerSetBox::shareStickers() { void StickerSetBox::shareStickers() {
auto url = Messenger::Instance().createInternalLinkFull(qsl("addstickers/") + _inner->shortName()); auto url = Core::App().createInternalLinkFull(qsl("addstickers/") + _inner->shortName());
QApplication::clipboard()->setText(url); QApplication::clipboard()->setText(url);
Ui::show(Box<InformBox>(lang(lng_stickers_copied))); Ui::show(Box<InformBox>(lang(lng_stickers_copied)));
} }

View file

@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_document.h" #include "data/data_document.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_channel.h" #include "data/data_channel.h"
#include "core/application.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "chat_helpers/stickers.h" #include "chat_helpers/stickers.h"
@ -30,7 +31,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/widgets/input_fields.h" #include "ui/widgets/input_fields.h"
#include "ui/image/image.h" #include "ui/image/image.h"
#include "auth_session.h" #include "auth_session.h"
#include "messenger.h"
namespace { namespace {
@ -623,7 +623,7 @@ StickersBox::Inner::Inner(QWidget *parent, not_null<ChannelData*> megagroup) : T
, _megagroupSetField(this, st::groupStickersField, [] { return qsl("stickerset"); }, QString(), true) , _megagroupSetField(this, st::groupStickersField, [] { return qsl("stickerset"); }, QString(), true)
, _megagroupDivider(this) , _megagroupDivider(this)
, _megagroupSubTitle(this, lang(lng_stickers_group_from_your), Ui::FlatLabel::InitType::Simple, st::boxTitle) { , _megagroupSubTitle(this, lang(lng_stickers_group_from_your), Ui::FlatLabel::InitType::Simple, st::boxTitle) {
_megagroupSetField->setLinkPlaceholder(Messenger::Instance().createInternalLink(qsl("addstickers/"))); _megagroupSetField->setLinkPlaceholder(Core::App().createInternalLink(qsl("addstickers/")));
_megagroupSetField->setPlaceholderHidden(false); _megagroupSetField->setPlaceholderHidden(false);
_megagroupSetAddressChangedTimer.setCallback([this] { handleMegagroupSetAddressChange(); }); _megagroupSetAddressChangedTimer.setCallback([this] { handleMegagroupSetAddressChange(); });
connect( connect(

View file

@ -13,7 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
#include "ui/widgets/input_fields.h" #include "ui/widgets/input_fields.h"
#include "ui/toast/toast.h" #include "ui/toast/toast.h"
#include "messenger.h" #include "core/application.h"
#include "auth_session.h" #include "auth_session.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_user.h" #include "data/data_user.h"
@ -88,7 +88,7 @@ void UsernameBox::paintEvent(QPaintEvent *e) {
if (_link->isHidden()) { if (_link->isHidden()) {
p.drawTextLeft(st::usernamePadding.left(), linky, width(), lang(lng_username_link_willbe)); p.drawTextLeft(st::usernamePadding.left(), linky, width(), lang(lng_username_link_willbe));
p.setPen(st::usernameDefaultFg); p.setPen(st::usernameDefaultFg);
p.drawTextLeft(st::usernamePadding.left(), linky + st::usernameTextStyle.lineHeight + ((st::usernameTextStyle.lineHeight - st::boxTextFont->height) / 2), width(), Messenger::Instance().createInternalLinkFull(qsl("username"))); p.drawTextLeft(st::usernamePadding.left(), linky + st::usernameTextStyle.lineHeight + ((st::usernameTextStyle.lineHeight - st::boxTextFont->height) / 2), width(), Core::App().createInternalLinkFull(qsl("username")));
} else { } else {
p.drawTextLeft(st::usernamePadding.left(), linky, width(), lang(lng_username_link)); p.drawTextLeft(st::usernamePadding.left(), linky, width(), lang(lng_username_link));
} }
@ -166,7 +166,7 @@ void UsernameBox::changed() {
} }
void UsernameBox::linkClick() { void UsernameBox::linkClick() {
QApplication::clipboard()->setText(Messenger::Instance().createInternalLinkFull(getName())); QApplication::clipboard()->setText(Core::App().createInternalLinkFull(getName()));
Ui::Toast::Show(lang(lng_username_copied)); Ui::Toast::Show(lang(lng_username_copied));
} }
@ -247,7 +247,7 @@ QString UsernameBox::getName() const {
void UsernameBox::updateLinkText() { void UsernameBox::updateLinkText() {
QString uname = getName(); QString uname = getName();
_link->setText(st::boxTextFont->elided(Messenger::Instance().createInternalLinkFull(uname), st::boxWidth - st::usernamePadding.left() - st::usernamePadding.right())); _link->setText(st::boxTextFont->elided(Core::App().createInternalLinkFull(uname), st::boxWidth - st::usernamePadding.left() - st::usernamePadding.right()));
if (uname.isEmpty()) { if (uname.isEmpty()) {
if (!_link->isHidden()) { if (!_link->isHidden()) {
_link->hide(); _link->hide();

View file

@ -8,7 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "calls/calls_instance.h" #include "calls/calls_instance.h"
#include "mtproto/connection.h" #include "mtproto/connection.h"
#include "messenger.h" #include "core/application.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
@ -101,7 +101,7 @@ void Instance::destroyCall(not_null<Call*> call) {
if (App::quitting()) { if (App::quitting()) {
LOG(("Calls::Instance doesn't prevent quit any more.")); LOG(("Calls::Instance doesn't prevent quit any more."));
} }
Messenger::Instance().quitPreventFinished(); Core::App().quitPreventFinished();
} }
} }

View file

@ -21,7 +21,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/wrap/fade_wrap.h" #include "ui/wrap/fade_wrap.h"
#include "ui/empty_userpic.h" #include "ui/empty_userpic.h"
#include "ui/emoji_config.h" #include "ui/emoji_config.h"
#include "messenger.h" #include "core/application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "auth_session.h" #include "auth_session.h"
@ -582,7 +582,7 @@ bool Panel::isGoodUserPhoto(PhotoData *photo) {
} }
void Panel::initGeometry() { void Panel::initGeometry() {
auto center = Messenger::Instance().getPointForCallPanelCenter(); auto center = Core::App().getPointForCallPanelCenter();
_useTransparency = Platform::TranslucentWindowsSupported(center); _useTransparency = Platform::TranslucentWindowsSupported(center);
setAttribute(Qt::WA_OpaquePaintEvent, !_useTransparency); setAttribute(Qt::WA_OpaquePaintEvent, !_useTransparency);
_padding = _useTransparency ? st::callShadow.extend : style::margins(st::lineWidth, st::lineWidth, st::lineWidth, st::lineWidth); _padding = _useTransparency ? st::callShadow.extend : style::margins(st::lineWidth, st::lineWidth, st::lineWidth, st::lineWidth);

View file

@ -17,7 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "base/zlib_help.h" #include "base/zlib_help.h"
#include "layout.h" #include "layout.h"
#include "messenger.h" #include "core/application.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
#include "styles/style_chat_helpers.h" #include "styles/style_chat_helpers.h"
@ -245,7 +245,7 @@ Loader::Loader(QObject *parent, int id)
, _id(id) , _id(id)
, _size(GetDownloadSize(_id)) , _size(GetDownloadSize(_id))
, _state(Loading{ 0, _size }) , _state(Loading{ 0, _size })
, _mtproto(Messenger::Instance().mtp()) { , _mtproto(Core::App().mtp()) {
const auto ready = [=](std::unique_ptr<MTP::DedicatedLoader> loader) { const auto ready = [=](std::unique_ptr<MTP::DedicatedLoader> loader) {
if (loader) { if (loader) {
setImplementation(std::move(loader)); setImplementation(std::move(loader));

View file

@ -12,7 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "chat_helpers/tabbed_selector.h" #include "chat_helpers/tabbed_selector.h"
#include "window/window_controller.h" #include "window/window_controller.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h" #include "core/application.h"
#include "styles/style_chat_helpers.h" #include "styles/style_chat_helpers.h"
namespace ChatHelpers { namespace ChatHelpers {
@ -192,7 +192,7 @@ void TabbedPanel::moveByBottom() {
} }
void TabbedPanel::enterEventHook(QEvent *e) { void TabbedPanel::enterEventHook(QEvent *e) {
Messenger::Instance().registerLeaveSubscription(this); Core::App().registerLeaveSubscription(this);
showAnimated(); showAnimated();
} }
@ -204,7 +204,7 @@ bool TabbedPanel::preventAutoHide() const {
} }
void TabbedPanel::leaveEventHook(QEvent *e) { void TabbedPanel::leaveEventHook(QEvent *e) {
Messenger::Instance().unregisterLeaveSubscription(this); Core::App().unregisterLeaveSubscription(this);
if (preventAutoHide()) { if (preventAutoHide()) {
return; return;
} }

View file

@ -17,15 +17,6 @@ constexpr str_const AppId = "{53F49750-6209-4FBF-9CA8-7A333C87D1ED}"; // used in
constexpr str_const AppFile = "Telegram"; constexpr str_const AppFile = "Telegram";
enum { enum {
MTPIdsBufferSize = 400, // received msgIds and wereAcked msgIds count stored
MTPCheckResendTimeout = 10000, // how much time passed from send till we resend request or check it's state, in ms
MTPCheckResendWaiting = 1000, // how much time to wait for some more requests, when resending request or checking it's state, in ms
MTPAckSendWaiting = 10000, // how much time to wait for some more requests, when sending msg acks
MTPResendThreshold = 1, // how much ints should message contain for us not to resend, but to check it's state
MTPContainerLives = 600, // container lives 10 minutes in haveSent map
MTPKillFileSessionTimeout = 5000, // how much time without upload / download causes additional session kill
MaxSelectedItems = 100, MaxSelectedItems = 100,
MaxPhoneCodeLength = 4, // max length of country phone code MaxPhoneCodeLength = 4, // max length of country phone code
@ -71,8 +62,6 @@ enum {
MaxMessageSize = 4096, MaxMessageSize = 4096,
WriteMapTimeout = 1000,
SetOnlineAfterActivity = 30, // user with hidden last seen stays online for such amount of seconds in the interface SetOnlineAfterActivity = 30, // user with hidden last seen stays online for such amount of seconds in the interface
ServiceUserId = 777000, ServiceUserId = 777000,

View file

@ -23,11 +23,6 @@ namespace Storage {
class Databases; class Databases;
} // namespace Storage } // namespace Storage
namespace Core {
class Launcher;
struct LocalUrlHandler;
} // namespace Core
namespace Window { namespace Window {
struct TermsLock; struct TermsLock;
} // namespace Window } // namespace Window
@ -56,21 +51,27 @@ class Translator;
class CloudManager; class CloudManager;
} // namespace Lang } // namespace Lang
class Messenger final : public QObject, public RPCSender, private base::Subscriber { namespace Core {
Q_OBJECT
class Launcher;
struct LocalUrlHandler;
class Application final
: public QObject
, public RPCSender
, private base::Subscriber {
public: public:
Messenger(not_null<Core::Launcher*> launcher); Application(not_null<Launcher*> launcher);
Messenger(const Messenger &other) = delete; Application(const Application &other) = delete;
Messenger &operator=(const Messenger &other) = delete; Application &operator=(const Application &other) = delete;
~Messenger(); not_null<Launcher*> launcher() const {
not_null<Core::Launcher*> launcher() const {
return _launcher; return _launcher;
} }
void run();
// Windows interface. // Windows interface.
MainWindow *getActiveWindow() const; MainWindow *getActiveWindow() const;
bool closeActiveWindow(); bool closeActiveWindow();
@ -97,13 +98,6 @@ public:
return _logoNoMargin; return _logoNoMargin;
} }
static Messenger *InstancePointer();
static Messenger &Instance() {
auto result = InstancePointer();
Assert(result != nullptr);
return *result;
}
// MTProto components. // MTProto components.
MTP::DcOptions *dcOptions() { MTP::DcOptions *dcOptions() {
return _dcOptions.get(); return _dcOptions.get();
@ -169,9 +163,6 @@ public:
void checkStartUrl(); void checkStartUrl();
bool openLocalUrl(const QString &url, QVariant context); bool openLocalUrl(const QString &url, QVariant context);
void killDownloadSessionsStart(MTP::DcId dcId);
void killDownloadSessionsStop(MTP::DcId dcId);
void forceLogOut(const TextWithEntities &explanation); void forceLogOut(const TextWithEntities &explanation);
void checkLocalTime(); void checkLocalTime();
void lockByPasscode(); void lockByPasscode();
@ -194,6 +185,14 @@ public:
void registerLeaveSubscription(QWidget *widget); void registerLeaveSubscription(QWidget *widget);
void unregisterLeaveSubscription(QWidget *widget); void unregisterLeaveSubscription(QWidget *widget);
// Sandbox interface.
void postponeCall(FnMut<void()> &&callable);
void refreshGlobalProxy();
void activateWindowDelayed(not_null<QWidget*> widget);
void pauseDelayedWindowActivations();
void resumeDelayedWindowActivations();
void preventWindowActivation();
void quitPreventFinished(); void quitPreventFinished();
void handleAppActivated(); void handleAppActivated();
@ -202,6 +201,7 @@ public:
void switchDebugMode(); void switchDebugMode();
void switchWorkMode(); void switchWorkMode();
void switchTestMode(); void switchTestMode();
void writeInstallBetaVersionsSetting();
void call_handleUnreadCounterUpdate(); void call_handleUnreadCounterUpdate();
void call_handleDelayedPeerUpdates(); void call_handleDelayedPeerUpdates();
@ -211,13 +211,11 @@ public:
_callDelayedTimer.call(duration, std::move(lambda)); _callDelayedTimer.call(duration, std::move(lambda));
} }
~Application();
protected: protected:
bool eventFilter(QObject *object, QEvent *event) override; bool eventFilter(QObject *object, QEvent *event) override;
public slots:
void killDownloadSessions();
void onAppStateChanged(Qt::ApplicationState state);
private: private:
void destroyMtpKeys(MTP::AuthKeysList &&keys); void destroyMtpKeys(MTP::AuthKeysList &&keys);
void allKeysDestroyed(); void allKeysDestroyed();
@ -225,6 +223,8 @@ private:
void startLocalStorage(); void startLocalStorage();
void startShortcuts(); void startShortcuts();
void stateChanged(Qt::ApplicationState state);
friend void App::quit(); friend void App::quit();
static void QuitAttempt(); static void QuitAttempt();
void quitDelayed(); void quitDelayed();
@ -234,12 +234,7 @@ private:
void clearPasscodeLock(); void clearPasscodeLock();
void loggedOut(); void loggedOut();
void fillLocalUrlHandlers(); not_null<Launcher*> _launcher;
not_null<Core::Launcher*> _launcher;
base::flat_map<MTP::DcId, TimeMs> _killDownloadSessionTimes;
base::Timer _killDownloadSessionsTimer;
// Some fields are just moved from the declaration. // Some fields are just moved from the declaration.
struct Private; struct Private;
@ -286,3 +281,7 @@ private:
rpl::lifetime _lifetime; rpl::lifetime _lifetime;
}; };
Application &App();
} // namespace Core

View file

@ -8,10 +8,11 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/click_handler_types.h" #include "core/click_handler_types.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "messenger.h" #include "core/application.h"
#include "core/local_url_handlers.h"
#include "core/file_utilities.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "auth_session.h" #include "auth_session.h"
#include "application.h"
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "history/view/history_view_element.h" #include "history/view/history_view_element.h"
#include "history/history_item.h" #include "history/history_item.h"
@ -20,7 +21,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "base/qthelp_url.h" #include "base/qthelp_url.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "ui/widgets/tooltip.h" #include "ui/widgets/tooltip.h"
#include "core/file_utilities.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "data/data_session.h" #include "data/data_session.h"
@ -117,7 +117,7 @@ QString UrlClickHandler::url() const {
void UrlClickHandler::Open(QString url, QVariant context) { void UrlClickHandler::Open(QString url, QVariant context) {
url = tryConvertUrlToLocal(url); url = tryConvertUrlToLocal(url);
if (InternalPassportLink(url)) { if (Core::InternalPassportLink(url)) {
return; return;
} }
@ -125,7 +125,7 @@ void UrlClickHandler::Open(QString url, QVariant context) {
if (isEmail(url)) { if (isEmail(url)) {
File::OpenEmailLink(url); File::OpenEmailLink(url);
} else if (url.startsWith(qstr("tg://"), Qt::CaseInsensitive)) { } else if (url.startsWith(qstr("tg://"), Qt::CaseInsensitive)) {
Messenger::Instance().openLocalUrl(url, context); Core::App().openLocalUrl(url, context);
} else if (!url.isEmpty()) { } else if (!url.isEmpty()) {
QDesktopServices::openUrl(url); QDesktopServices::openUrl(url);
} }
@ -153,7 +153,7 @@ TextWithEntities UrlClickHandler::getExpandedLinkTextWithEntities(ExpandLinksMod
void HiddenUrlClickHandler::Open(QString url, QVariant context) { void HiddenUrlClickHandler::Open(QString url, QVariant context) {
url = tryConvertUrlToLocal(url); url = tryConvertUrlToLocal(url);
if (InternalPassportLink(url)) { if (Core::InternalPassportLink(url)) {
return; return;
} }
@ -165,7 +165,7 @@ void HiddenUrlClickHandler::Open(QString url, QVariant context) {
} else { } else {
const auto parsedUrl = QUrl::fromUserInput(url); const auto parsedUrl = QUrl::fromUserInput(url);
if (UrlRequiresConfirmation(url)) { if (UrlRequiresConfirmation(url)) {
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
const auto displayUrl = parsedUrl.isValid() const auto displayUrl = parsedUrl.isValid()
? parsedUrl.toDisplayString() ? parsedUrl.toDisplayString()
: url; : url;
@ -183,7 +183,7 @@ void HiddenUrlClickHandler::Open(QString url, QVariant context) {
void BotGameUrlClickHandler::onClick(ClickContext context) const { void BotGameUrlClickHandler::onClick(ClickContext context) const {
const auto url = tryConvertUrlToLocal(this->url()); const auto url = tryConvertUrlToLocal(this->url());
if (InternalPassportLink(url)) { if (Core::InternalPassportLink(url)) {
return; return;
} }

View file

@ -8,11 +8,18 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/crash_report_window.h" #include "core/crash_report_window.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"
#include "core/launcher.h"
#include "core/sandbox.h"
#include "core/update_checker.h"
#include "window/main_window.h" #include "window/main_window.h"
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "application.h"
#include "base/zlib_help.h" #include "base/zlib_help.h"
#include "core/update_checker.h"
namespace {
constexpr auto kDefaultProxyPort = 80;
} // namespace
PreLaunchWindow *PreLaunchWindowInstance = nullptr; PreLaunchWindow *PreLaunchWindowInstance = nullptr;
@ -198,8 +205,12 @@ LastCrashedWindow::UpdaterData::UpdaterData(QWidget *buttonParent)
, skip(buttonParent, false) { , skip(buttonParent, false) {
} }
LastCrashedWindow::LastCrashedWindow() LastCrashedWindow::LastCrashedWindow(
: _port(80) not_null<Core::Launcher*> launcher,
const QByteArray &crashdump,
Fn<void()> launch)
: _dumpraw(crashdump)
, _port(kDefaultProxyPort)
, _label(this) , _label(this)
, _pleaseSendReport(this) , _pleaseSendReport(this)
, _yourReportName(this) , _yourReportName(this)
@ -213,18 +224,15 @@ LastCrashedWindow::LastCrashedWindow()
, _saveReport(this) , _saveReport(this)
, _getApp(this) , _getApp(this)
, _includeUsername(this) , _includeUsername(this)
, _reportText(QString::fromUtf8(Sandbox::LastCrashDump())) , _reportText(QString::fromUtf8(crashdump))
, _reportShown(false) , _reportShown(false)
, _reportSaved(false) , _reportSaved(false)
, _sendingState(Sandbox::LastCrashDump().isEmpty() ? SendingNoReport : SendingUpdateCheck) , _sendingState(crashdump.isEmpty() ? SendingNoReport : SendingUpdateCheck)
, _updating(this) , _updating(this)
, _sendingProgress(0)
, _sendingTotal(0)
, _checkReply(0)
, _sendReply(0)
, _updaterData(Core::UpdaterDisabled() , _updaterData(Core::UpdaterDisabled()
? nullptr ? nullptr
: std::make_unique<UpdaterData>(this)) { : std::make_unique<UpdaterData>(this))
, _launch(std::move(launch)) {
excludeReportUsername(); excludeReportUsername();
if (!cInstallBetaVersion() && !cAlphaVersion()) { // currently accept crash reports only from testers if (!cInstallBetaVersion() && !cAlphaVersion()) { // currently accept crash reports only from testers
@ -339,7 +347,7 @@ LastCrashedWindow::LastCrashedWindow()
} }
_pleaseSendReport.setText(qsl("Please send us a crash report.")); _pleaseSendReport.setText(qsl("Please send us a crash report."));
_yourReportName.setText(qsl("Your Report Tag: %1\nYour User Tag: %2").arg(QString(_minidumpName).replace(".dmp", "")).arg(Sandbox::UserTag(), 0, 16)); _yourReportName.setText(qsl("Your Report Tag: %1\nYour User Tag: %2").arg(QString(_minidumpName).replace(".dmp", "")).arg(launcher->installationTag(), 0, 16));
_yourReportName.setCursor(style::cur_text); _yourReportName.setCursor(style::cur_text);
_yourReportName.setTextInteractionFlags(Qt::TextSelectableByMouse); _yourReportName.setTextInteractionFlags(Qt::TextSelectableByMouse);
@ -386,9 +394,11 @@ void LastCrashedWindow::onSaveReport() {
} }
QByteArray LastCrashedWindow::getCrashReportRaw() const { QByteArray LastCrashedWindow::getCrashReportRaw() const {
QByteArray result(Sandbox::LastCrashDump()); auto result = _dumpraw;
if (!_reportUsername.isEmpty() && _includeUsername.checkState() != Qt::Checked) { if (!_reportUsername.isEmpty() && _includeUsername.checkState() != Qt::Checked) {
result.replace((qsl("Username: ") + _reportUsername).toUtf8(), "Username: _not_included_"); result.replace(
(qsl("Username: ") + _reportUsername).toUtf8(),
"Username: _not_included_");
} }
return result; return result;
} }
@ -775,7 +785,7 @@ void LastCrashedWindow::updateControls() {
} }
void LastCrashedWindow::onNetworkSettings() { void LastCrashedWindow::onNetworkSettings() {
const auto &proxy = Sandbox::PreLaunchProxy(); const auto &proxy = Core::Sandbox::Instance().sandboxProxy();
const auto box = new NetworkSettingsWindow( const auto box = new NetworkSettingsWindow(
this, this,
proxy.host, proxy.host,
@ -797,7 +807,7 @@ void LastCrashedWindow::onNetworkSettingsSaved(
QString password) { QString password) {
Expects(host.isEmpty() || port != 0); Expects(host.isEmpty() || port != 0);
auto &proxy = Sandbox::RefPreLaunchProxy(); auto proxy = ProxyData();
proxy.type = host.isEmpty() proxy.type = host.isEmpty()
? ProxyData::Type::None ? ProxyData::Type::None
: ProxyData::Type::Http; : ProxyData::Type::Http;
@ -805,9 +815,11 @@ void LastCrashedWindow::onNetworkSettingsSaved(
proxy.port = port; proxy.port = port;
proxy.user = username; proxy.user = username;
proxy.password = password; proxy.password = password;
_proxyChanges.fire(std::move(proxy));
proxyUpdated();
}
Core::App().refreshGlobalProxy(); void LastCrashedWindow::proxyUpdated() {
if (_updaterData if (_updaterData
&& ((_updaterData->state == UpdatingCheck) && ((_updaterData->state == UpdatingCheck)
|| (_updaterData->state == UpdatingFail || (_updaterData->state == UpdatingFail
@ -824,6 +836,10 @@ void LastCrashedWindow::onNetworkSettingsSaved(
activate(); activate();
} }
rpl::producer<ProxyData> LastCrashedWindow::proxyChanges() const {
return _proxyChanges.events();
}
void LastCrashedWindow::setUpdatingState(UpdatingState state, bool force) { void LastCrashedWindow::setUpdatingState(UpdatingState state, bool force) {
Expects(_updaterData != nullptr); Expects(_updaterData != nullptr);
@ -932,8 +948,8 @@ void LastCrashedWindow::onUpdateFailed() {
void LastCrashedWindow::onContinue() { void LastCrashedWindow::onContinue() {
if (CrashReports::Restart() == CrashReports::CantOpen) { if (CrashReports::Restart() == CrashReports::CantOpen) {
new NotStartedWindow(); new NotStartedWindow();
} else if (!Global::started()) { } else {
Sandbox::launch(); _launch();
} }
close(); close();
} }

View file

@ -7,6 +7,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/ */
#pragma once #pragma once
namespace Core {
class Launcher;
} // namespace Core
class PreLaunchWindow : public QWidget { class PreLaunchWindow : public QWidget {
public: public:
PreLaunchWindow(QString title = QString()); PreLaunchWindow(QString title = QString());
@ -62,8 +66,8 @@ public:
NotStartedWindow(); NotStartedWindow();
protected: protected:
void closeEvent(QCloseEvent *e); void closeEvent(QCloseEvent *e) override;
void resizeEvent(QResizeEvent *e); void resizeEvent(QResizeEvent *e) override;
private: private:
void updateControls(); void updateControls();
@ -78,7 +82,16 @@ class LastCrashedWindow : public PreLaunchWindow {
Q_OBJECT Q_OBJECT
public: public:
LastCrashedWindow(); LastCrashedWindow(
not_null<Core::Launcher*> launcher,
const QByteArray &crashdump,
Fn<void()> launch);
rpl::producer<ProxyData> proxyChanges() const;
rpl::lifetime &lifetime() {
return _lifetime;
}
public slots: public slots:
void onViewReport(); void onViewReport();
@ -105,10 +118,11 @@ public slots:
void onUpdateFailed(); void onUpdateFailed();
protected: protected:
void closeEvent(QCloseEvent *e); void closeEvent(QCloseEvent *e) override;
void resizeEvent(QResizeEvent *e); void resizeEvent(QResizeEvent *e) override;
private: private:
void proxyUpdated();
QString minidumpFileName(); QString minidumpFileName();
void updateControls(); void updateControls();
@ -117,6 +131,8 @@ private:
QString getReportField(const QLatin1String &name, const QLatin1String &prefix); QString getReportField(const QLatin1String &name, const QLatin1String &prefix);
void addReportFieldPart(const QLatin1String &name, const QLatin1String &prefix, QHttpMultiPart *multipart); void addReportFieldPart(const QLatin1String &name, const QLatin1String &prefix, QHttpMultiPart *multipart);
QByteArray _dumpraw;
QString _host, _username, _password; QString _host, _username, _password;
quint32 _port; quint32 _port;
@ -146,10 +162,12 @@ private:
SendingState _sendingState; SendingState _sendingState;
PreLaunchLabel _updating; PreLaunchLabel _updating;
qint64 _sendingProgress, _sendingTotal; qint64 _sendingProgress = 0;
qint64 _sendingTotal = 0;
QNetworkAccessManager _sendManager; QNetworkAccessManager _sendManager;
QNetworkReply *_checkReply, *_sendReply; QNetworkReply *_checkReply = nullptr;
QNetworkReply *_sendReply = nullptr;
enum UpdatingState { enum UpdatingState {
UpdatingNone, UpdatingNone,
@ -171,6 +189,8 @@ private:
void setUpdatingState(UpdatingState state, bool force = false); void setUpdatingState(UpdatingState state, bool force = false);
void setDownloadProgress(qint64 ready, qint64 total); void setDownloadProgress(qint64 ready, qint64 total);
Fn<void()> _launch;
rpl::event_stream<ProxyData> _proxyChanges;
rpl::lifetime _lifetime; rpl::lifetime _lifetime;
}; };

View file

@ -8,6 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/crash_reports.h" #include "core/crash_reports.h"
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "core/launcher.h"
#include <signal.h> #include <signal.h>
#include <new> #include <new>
@ -319,14 +320,14 @@ bool DumpCallback(const google_breakpad::MinidumpDescriptor &md, void *context,
} // namespace } // namespace
void StartCatching() { void StartCatching(not_null<Core::Launcher*> launcher) {
#ifndef TDESKTOP_DISABLE_CRASH_REPORTS #ifndef TDESKTOP_DISABLE_CRASH_REPORTS
ProcessAnnotations["Binary"] = cExeName().toUtf8().constData(); ProcessAnnotations["Binary"] = cExeName().toUtf8().constData();
ProcessAnnotations["ApiId"] = QString::number(ApiId).toUtf8().constData(); ProcessAnnotations["ApiId"] = QString::number(ApiId).toUtf8().constData();
ProcessAnnotations["Version"] = (cAlphaVersion() ? qsl("%1 alpha").arg(cAlphaVersion()) : (AppBetaVersion ? qsl("%1 beta") : qsl("%1")).arg(AppVersion)).toUtf8().constData(); ProcessAnnotations["Version"] = (cAlphaVersion() ? qsl("%1 alpha").arg(cAlphaVersion()) : (AppBetaVersion ? qsl("%1 beta") : qsl("%1")).arg(AppVersion)).toUtf8().constData();
ProcessAnnotations["Launched"] = QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss").toUtf8().constData(); ProcessAnnotations["Launched"] = QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss").toUtf8().constData();
ProcessAnnotations["Platform"] = cPlatformString().toUtf8().constData(); ProcessAnnotations["Platform"] = cPlatformString().toUtf8().constData();
ProcessAnnotations["UserTag"] = QString::number(Sandbox::UserTag(), 16).toUtf8().constData(); ProcessAnnotations["UserTag"] = QString::number(launcher->installationTag(), 16).toUtf8().constData();
QString dumpspath = cWorkingDir() + qsl("tdata/dumps"); QString dumpspath = cWorkingDir() + qsl("tdata/dumps");
QDir().mkpath(dumpspath); QDir().mkpath(dumpspath);
@ -393,7 +394,7 @@ void FinishCatching() {
#endif // !TDESKTOP_DISABLE_CRASH_REPORTS #endif // !TDESKTOP_DISABLE_CRASH_REPORTS
} }
Status Start() { StartResult Start() {
#ifndef TDESKTOP_DISABLE_CRASH_REPORTS #ifndef TDESKTOP_DISABLE_CRASH_REPORTS
ReportPath = cWorkingDir() + qsl("tdata/working"); ReportPath = cWorkingDir() + qsl("tdata/working");
@ -413,11 +414,11 @@ Status Start() {
} }
fclose(f); fclose(f);
Sandbox::SetLastCrashDump(lastdump); LOG(("Opened '%1' for reading, the previous "
"Telegram Desktop launch was not finished properly :( "
"Crash log size: %2").arg(ReportPath).arg(lastdump.size()));
LOG(("Opened '%1' for reading, the previous Telegram Desktop launch was not finished properly :( Crash log size: %2").arg(ReportPath).arg(lastdump.size())); return lastdump;
return LastCrashed;
} }
#endif // !TDESKTOP_DISABLE_CRASH_REPORTS #endif // !TDESKTOP_DISABLE_CRASH_REPORTS

View file

@ -7,6 +7,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/ */
#pragma once #pragma once
namespace Core {
class Launcher;
} // namespace Core
namespace CrashReports { namespace CrashReports {
#ifndef TDESKTOP_DISABLE_CRASH_REPORTS #ifndef TDESKTOP_DISABLE_CRASH_REPORTS
@ -26,10 +30,11 @@ const dump &operator<<(const dump &stream, double num);
enum Status { enum Status {
CantOpen, CantOpen,
LastCrashed,
Started Started
}; };
Status Start(); // Open status or crash report dump.
using StartResult = base::variant<Status, QByteArray>;
StartResult Start();
Status Restart(); // can be only CantOpen or Started Status Restart(); // can be only CantOpen or Started
void Finish(); void Finish();
@ -46,7 +51,7 @@ inline void ClearAnnotationRef(const std::string &key) {
SetAnnotationRef(key, nullptr); SetAnnotationRef(key, nullptr);
} }
void StartCatching(); void StartCatching(not_null<Core::Launcher*> launcher);
void FinishCatching(); void FinishCatching();
} // namespace CrashReports } // namespace CrashReports

View file

@ -9,17 +9,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "platform/platform_file_utilities.h" #include "platform/platform_file_utilities.h"
#include "messenger.h" #include "core/application.h"
#include "application.h"
#include "mainwindow.h" #include "mainwindow.h"
void PreventWindowActivation() {
Core::App().pauseDelayedWindowActivations();
Core::App().postponeCall([] {
Core::App().resumeDelayedWindowActivations();
});
}
bool filedialogGetSaveFile( bool filedialogGetSaveFile(
QPointer<QWidget> parent, QPointer<QWidget> parent,
QString &file, QString &file,
@ -28,7 +20,7 @@ bool filedialogGetSaveFile(
const QString &initialPath) { const QString &initialPath) {
QStringList files; QStringList files;
QByteArray remoteContent; QByteArray remoteContent;
PreventWindowActivation(); Core::App().preventWindowActivation();
bool result = Platform::FileDialog::Get( bool result = Platform::FileDialog::Get(
parent, parent,
files, files,
@ -47,7 +39,7 @@ bool filedialogGetSaveFile(
const QString &filter, const QString &filter,
const QString &initialPath) { const QString &initialPath) {
return filedialogGetSaveFile( return filedialogGetSaveFile(
Messenger::Instance().getFileDialogParent(), Core::App().getFileDialogParent(),
file, file,
caption, caption,
filter, filter,
@ -121,7 +113,7 @@ namespace File {
void OpenEmailLink(const QString &email) { void OpenEmailLink(const QString &email) {
crl::on_main([=] { crl::on_main([=] {
PreventWindowActivation(); Core::App().preventWindowActivation();
Platform::File::UnsafeOpenEmailLink(email); Platform::File::UnsafeOpenEmailLink(email);
}); });
} }
@ -129,7 +121,7 @@ void OpenEmailLink(const QString &email) {
void OpenWith(const QString &filepath, QPoint menuPosition) { void OpenWith(const QString &filepath, QPoint menuPosition) {
InvokeQueued(QApplication::instance(), [=] { InvokeQueued(QApplication::instance(), [=] {
if (!Platform::File::UnsafeShowOpenWithDropdown(filepath, menuPosition)) { if (!Platform::File::UnsafeShowOpenWithDropdown(filepath, menuPosition)) {
PreventWindowActivation(); Core::App().preventWindowActivation();
if (!Platform::File::UnsafeShowOpenWith(filepath)) { if (!Platform::File::UnsafeShowOpenWith(filepath)) {
Platform::File::UnsafeLaunch(filepath); Platform::File::UnsafeLaunch(filepath);
} }
@ -139,14 +131,14 @@ void OpenWith(const QString &filepath, QPoint menuPosition) {
void Launch(const QString &filepath) { void Launch(const QString &filepath) {
crl::on_main([=] { crl::on_main([=] {
PreventWindowActivation(); Core::App().preventWindowActivation();
Platform::File::UnsafeLaunch(filepath); Platform::File::UnsafeLaunch(filepath);
}); });
} }
void ShowInFolder(const QString &filepath) { void ShowInFolder(const QString &filepath) {
crl::on_main([=] { crl::on_main([=] {
PreventWindowActivation(); Core::App().preventWindowActivation();
Platform::File::UnsafeShowInFolder(filepath); Platform::File::UnsafeShowInFolder(filepath);
}); });
} }
@ -186,7 +178,7 @@ void GetOpenPath(
InvokeQueued(QApplication::instance(), [=] { InvokeQueued(QApplication::instance(), [=] {
auto files = QStringList(); auto files = QStringList();
auto remoteContent = QByteArray(); auto remoteContent = QByteArray();
PreventWindowActivation(); Core::App().preventWindowActivation();
const auto success = Platform::FileDialog::Get( const auto success = Platform::FileDialog::Get(
parent, parent,
files, files,
@ -220,7 +212,7 @@ void GetOpenPaths(
InvokeQueued(QApplication::instance(), [=] { InvokeQueued(QApplication::instance(), [=] {
auto files = QStringList(); auto files = QStringList();
auto remoteContent = QByteArray(); auto remoteContent = QByteArray();
PreventWindowActivation(); Core::App().preventWindowActivation();
const auto success = Platform::FileDialog::Get( const auto success = Platform::FileDialog::Get(
parent, parent,
files, files,
@ -269,7 +261,7 @@ void GetFolder(
InvokeQueued(QApplication::instance(), [=] { InvokeQueued(QApplication::instance(), [=] {
auto files = QStringList(); auto files = QStringList();
auto remoteContent = QByteArray(); auto remoteContent = QByteArray();
PreventWindowActivation(); Core::App().preventWindowActivation();
const auto success = Platform::FileDialog::Get( const auto success = Platform::FileDialog::Get(
parent, parent,
files, files,
@ -320,7 +312,7 @@ bool GetDefault(
} }
QString file; QString file;
if (type == Type::ReadFiles) { if (type == Type::ReadFiles) {
files = QFileDialog::getOpenFileNames(Messenger::Instance().getFileDialogParent(), caption, startFile, filter); files = QFileDialog::getOpenFileNames(Core::App().getFileDialogParent(), caption, startFile, filter);
QString path = files.isEmpty() ? QString() : QFileInfo(files.back()).absoluteDir().absolutePath(); QString path = files.isEmpty() ? QString() : QFileInfo(files.back()).absoluteDir().absolutePath();
if (!path.isEmpty() && path != cDialogLastPath()) { if (!path.isEmpty() && path != cDialogLastPath()) {
cSetDialogLastPath(path); cSetDialogLastPath(path);
@ -328,11 +320,11 @@ bool GetDefault(
} }
return !files.isEmpty(); return !files.isEmpty();
} else if (type == Type::ReadFolder) { } else if (type == Type::ReadFolder) {
file = QFileDialog::getExistingDirectory(Messenger::Instance().getFileDialogParent(), caption, startFile); file = QFileDialog::getExistingDirectory(Core::App().getFileDialogParent(), caption, startFile);
} else if (type == Type::WriteFile) { } else if (type == Type::WriteFile) {
file = QFileDialog::getSaveFileName(Messenger::Instance().getFileDialogParent(), caption, startFile, filter); file = QFileDialog::getSaveFileName(Core::App().getFileDialogParent(), caption, startFile, filter);
} else { } else {
file = QFileDialog::getOpenFileName(Messenger::Instance().getFileDialogParent(), caption, startFile, filter); file = QFileDialog::getOpenFileName(Core::App().getFileDialogParent(), caption, startFile, filter);
} }
if (file.isEmpty()) { if (file.isEmpty()) {
files = QStringList(); files = QStringList();

View file

@ -12,10 +12,179 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/crash_reports.h" #include "core/crash_reports.h"
#include "core/main_queue_processor.h" #include "core/main_queue_processor.h"
#include "core/update_checker.h" #include "core/update_checker.h"
#include "core/sandbox.h"
#include "base/concurrent_timer.h" #include "base/concurrent_timer.h"
#include "application.h"
namespace Core { namespace Core {
namespace {
uint64 InstallationTag = 0;
QString DebugModeSettingPath() {
return cWorkingDir() + qsl("tdata/withdebug");
}
void WriteDebugModeSetting() {
auto file = QFile(DebugModeSettingPath());
if (file.open(QIODevice::WriteOnly)) {
file.write(Logs::DebugEnabled() ? "1" : "0");
}
}
void ComputeDebugMode() {
Logs::SetDebugEnabled(cAlphaVersion() != 0);
const auto debugModeSettingPath = DebugModeSettingPath();
auto file = QFile(debugModeSettingPath);
if (file.exists() && file.open(QIODevice::ReadOnly)) {
Logs::SetDebugEnabled(file.read(1) != "0");
}
}
void ComputeTestMode() {
if (QFile(cWorkingDir() + qsl("tdata/withtestmode")).exists()) {
cSetTestMode(true);
}
}
QString InstallBetaVersionsSettingPath() {
return cWorkingDir() + qsl("tdata/devversion");
}
void WriteInstallBetaVersionsSetting() {
QFile f(InstallBetaVersionsSettingPath());
if (f.open(QIODevice::WriteOnly)) {
f.write(cInstallBetaVersion() ? "1" : "0");
}
}
void ComputeInstallBetaVersions() {
const auto installBetaSettingPath = InstallBetaVersionsSettingPath();
if (cAlphaVersion()) {
cSetInstallBetaVersion(false);
} else if (QFile(installBetaSettingPath).exists()) {
QFile f(installBetaSettingPath);
if (f.open(QIODevice::ReadOnly)) {
cSetInstallBetaVersion(f.read(1) != "0");
}
} else if (AppBetaVersion) {
WriteInstallBetaVersionsSetting();
}
}
void ComputeInstallationTag() {
InstallationTag = 0;
auto file = QFile(cWorkingDir() + qsl("tdata/usertag"));
if (file.open(QIODevice::ReadOnly)) {
const auto result = file.read(
reinterpret_cast<char*>(&InstallationTag),
sizeof(uint64));
if (result != sizeof(uint64)) {
InstallationTag = 0;
}
file.close();
}
if (!InstallationTag) {
do {
memsetrnd_bad(InstallationTag);
} while (!InstallationTag);
if (file.open(QIODevice::WriteOnly)) {
file.write(
reinterpret_cast<char*>(&InstallationTag),
sizeof(uint64));
file.close();
}
}
}
bool MoveLegacyAlphaFolder(const QString &folder, const QString &file) {
const auto was = cExeDir() + folder;
const auto now = cExeDir() + qsl("TelegramForcePortable");
if (QDir(was).exists() && !QDir(now).exists()) {
const auto oldFile = was + "/tdata/" + file;
const auto newFile = was + "/tdata/alpha";
if (QFile(oldFile).exists() && !QFile(newFile).exists()) {
if (!QFile(oldFile).copy(newFile)) {
LOG(("FATAL: Could not copy '%1' to '%2'"
).arg(oldFile
).arg(newFile));
return false;
}
}
if (!QDir().rename(was, now)) {
LOG(("FATAL: Could not rename '%1' to '%2'"
).arg(was
).arg(now));
return false;
}
}
return true;
}
bool MoveLegacyAlphaFolder() {
if (!MoveLegacyAlphaFolder(qsl("TelegramAlpha_data"), qsl("alpha"))
|| !MoveLegacyAlphaFolder(qsl("TelegramBeta_data"), qsl("beta"))) {
return false;
}
return true;
}
bool CheckPortableVersionFolder() {
if (!MoveLegacyAlphaFolder()) {
return false;
}
const auto portable = cExeDir() + qsl("TelegramForcePortable");
QFile key(portable + qsl("/tdata/alpha"));
if (cAlphaVersion()) {
Assert(*AlphaPrivateKey != 0);
cForceWorkingDir(portable + '/');
QDir().mkpath(cWorkingDir() + qstr("tdata"));
cSetAlphaPrivateKey(QByteArray(AlphaPrivateKey));
if (!key.open(QIODevice::WriteOnly)) {
LOG(("FATAL: Could not open '%1' for writing private key!"
).arg(key.fileName()));
return false;
}
QDataStream dataStream(&key);
dataStream.setVersion(QDataStream::Qt_5_3);
dataStream << quint64(cRealAlphaVersion()) << cAlphaPrivateKey();
return true;
}
if (!QDir(portable).exists()) {
return true;
}
cForceWorkingDir(portable + '/');
if (!key.exists()) {
return true;
}
if (!key.open(QIODevice::ReadOnly)) {
LOG(("FATAL: could not open '%1' for reading private key. "
"Delete it or reinstall private alpha version."
).arg(key.fileName()));
return false;
}
QDataStream dataStream(&key);
dataStream.setVersion(QDataStream::Qt_5_3);
quint64 v;
QByteArray k;
dataStream >> v >> k;
if (dataStream.status() != QDataStream::Ok || k.isEmpty()) {
LOG(("FATAL: '%1' is corrupted. "
"Delete it or reinstall private alpha version."
).arg(key.fileName()));
return false;
}
cSetAlphaVersion(AppVersion * 1000ULL);
cSetAlphaPrivateKey(k);
cSetRealAlphaVersion(v);
return true;
}
} // namespace
std::unique_ptr<Launcher> Launcher::Create(int argc, char *argv[]) { std::unique_ptr<Launcher> Launcher::Create(int argc, char *argv[]) {
return std::make_unique<Platform::Launcher>(argc, argv); return std::make_unique<Platform::Launcher>(argc, argv);
@ -37,10 +206,10 @@ void Launcher::init() {
prepareSettings(); prepareSettings();
QCoreApplication::setApplicationName(qsl("TelegramDesktop")); QApplication::setApplicationName(qsl("TelegramDesktop"));
#ifndef OS_MAC_OLD #ifndef OS_MAC_OLD
QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true); QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true);
#endif // OS_MAC_OLD #endif // OS_MAC_OLD
initHook(); initHook();
@ -55,21 +224,21 @@ int Launcher::exec() {
return psCleanup(); return psCleanup();
} }
// both are finished in Application::closeApplication // both are finished in Sandbox::closeApplication
Logs::start(this); // must be started before Platform is started Logs::start(this); // must be started before Platform is started
Platform::start(); // must be started before QApplication is created Platform::start(); // must be started before Sandbox is created
auto result = executeApplication(); auto result = executeApplication();
DEBUG_LOG(("Telegram finished, result: %1").arg(result)); DEBUG_LOG(("Telegram finished, result: %1").arg(result));
if (!UpdaterDisabled() && cRestartingUpdate()) { if (!UpdaterDisabled() && cRestartingUpdate()) {
DEBUG_LOG(("Application Info: executing updater to install update...")); DEBUG_LOG(("Sandbox Info: executing updater to install update."));
if (!launchUpdater(UpdaterLaunch::PerformUpdate)) { if (!launchUpdater(UpdaterLaunch::PerformUpdate)) {
psDeleteDir(cWorkingDir() + qsl("tupdates/temp")); psDeleteDir(cWorkingDir() + qsl("tupdates/temp"));
} }
} else if (cRestarting()) { } else if (cRestarting()) {
DEBUG_LOG(("Application Info: executing Telegram, because of restart...")); DEBUG_LOG(("Sandbox Info: executing Telegram because of restart."));
launchUpdater(UpdaterLaunch::JustRelaunch); launchUpdater(UpdaterLaunch::JustRelaunch);
} }
@ -80,6 +249,27 @@ int Launcher::exec() {
return result; return result;
} }
void Launcher::workingFolderReady() {
srand((unsigned int)time(nullptr));
ComputeTestMode();
ComputeDebugMode();
ComputeInstallBetaVersions();
ComputeInstallationTag();
}
void Launcher::writeDebugModeSetting() {
WriteDebugModeSetting();
}
void Launcher::writeInstallBetaVersionsSetting() {
WriteInstallBetaVersionsSetting();
}
bool Launcher::checkPortableVersionFolder() {
return CheckPortableVersionFolder();
}
QStringList Launcher::readArguments(int argc, char *argv[]) const { QStringList Launcher::readArguments(int argc, char *argv[]) const {
Expects(argc >= 0); Expects(argc >= 0);
@ -170,6 +360,10 @@ QString Launcher::systemVersion() const {
return _systemVersion; return _systemVersion;
} }
uint64 Launcher::installationTag() const {
return InstallationTag;
}
void Launcher::processArguments() { void Launcher::processArguments() {
enum class KeyFormat { enum class KeyFormat {
NoValues, NoValues,
@ -243,10 +437,10 @@ void Launcher::processArguments() {
} }
int Launcher::executeApplication() { int Launcher::executeApplication() {
Application application(this, _argc, _argv); Sandbox sandbox(this, _argc, _argv);
MainQueueProcessor processor; MainQueueProcessor processor;
base::ConcurrentTimerEnvironment environment; base::ConcurrentTimerEnvironment environment;
return application.execute(); return sandbox.start();
} }
} // namespace Core } // namespace Core

View file

@ -27,6 +27,12 @@ public:
// Thread safe. // Thread safe.
QString deviceModel() const; QString deviceModel() const;
QString systemVersion() const; QString systemVersion() const;
uint64 installationTag() const;
bool checkPortableVersionFolder();
void workingFolderReady();
void writeDebugModeSetting();
void writeInstallBetaVersionsSetting();
virtual ~Launcher() = default; virtual ~Launcher() = default;

View file

@ -23,7 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_session.h" #include "data/data_session.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "messenger.h" #include "core/application.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
@ -38,7 +38,7 @@ bool JoinGroupByHash(const Match &match, const QVariant &context) {
} }
const auto hash = match->captured(1); const auto hash = match->captured(1);
Auth().api().checkChatInvite(hash, [=](const MTPChatInvite &result) { Auth().api().checkChatInvite(hash, [=](const MTPChatInvite &result) {
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
result.match([=](const MTPDchatInvite &data) { result.match([=](const MTPDchatInvite &data) {
Ui::show(Box<ConfirmInviteBox>(data, [=] { Ui::show(Box<ConfirmInviteBox>(data, [=] {
Auth().api().importChatInvite(hash); Auth().api().importChatInvite(hash);
@ -54,7 +54,7 @@ bool JoinGroupByHash(const Match &match, const QVariant &context) {
if (error.code() != 400) { if (error.code() != 400) {
return; return;
} }
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
Ui::show(Box<InformBox>(lang(lng_group_invite_bad_link))); Ui::show(Box<InformBox>(lang(lng_group_invite_bad_link)));
}); });
return true; return true;
@ -64,7 +64,7 @@ bool ShowStickerSet(const Match &match, const QVariant &context) {
if (!AuthSession::Exists()) { if (!AuthSession::Exists()) {
return false; return false;
} }
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
Ui::show(Box<StickerSetBox>( Ui::show(Box<StickerSetBox>(
MTP_inputStickerSetShortName(MTP_string(match->captured(1))))); MTP_inputStickerSetShortName(MTP_string(match->captured(1)))));
return true; return true;
@ -310,4 +310,36 @@ const std::vector<LocalUrlHandler> &LocalUrlHandlers() {
return Result; return Result;
} }
bool InternalPassportLink(const QString &url) {
const auto urlTrimmed = url.trimmed();
if (!urlTrimmed.startsWith(qstr("tg://"), Qt::CaseInsensitive)) {
return false;
}
const auto command = urlTrimmed.midRef(qstr("tg://").size());
using namespace qthelp;
const auto matchOptions = RegExOption::CaseInsensitive;
const auto authMatch = regex_match(
qsl("^passport/?\\?(.+)(#|$)"),
command,
matchOptions);
const auto usernameMatch = regex_match(
qsl("^resolve/?\\?(.+)(#|$)"),
command,
matchOptions);
const auto usernameValue = usernameMatch->hasMatch()
? url_parse_params(
usernameMatch->captured(1),
UrlParamNameTransform::ToLower).value(qsl("domain"))
: QString();
const auto authLegacy = (usernameValue == qstr("telegrampassport"));
return authMatch->hasMatch() || authLegacy;
}
bool StartUrlRequiresActivate(const QString &url) {
return Core::App().locked()
? true
: !InternalPassportLink(url);
}
} // namespace Core } // namespace Core

View file

@ -22,4 +22,8 @@ struct LocalUrlHandler {
const std::vector<LocalUrlHandler> &LocalUrlHandlers(); const std::vector<LocalUrlHandler> &LocalUrlHandlers();
bool InternalPassportLink(const QString &url);
bool StartUrlRequiresActivate(const QString &url);
} // namespace Core } // namespace Core

View file

@ -7,7 +7,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/ */
#include "core/main_queue_processor.h" #include "core/main_queue_processor.h"
#include "application.h" #include "core/sandbox.h"
namespace Core { namespace Core {
namespace { namespace {
@ -54,12 +54,12 @@ MainQueueProcessor::MainQueueProcessor() {
if (ProcessorInstance) { if (ProcessorInstance) {
const auto event = new ProcessorEvent(callable, argument); const auto event = new ProcessorEvent(callable, argument);
QCoreApplication::postEvent(ProcessorInstance, event); QApplication::postEvent(ProcessorInstance, event);
} }
}); });
crl::wrap_main_queue([](void (*callable)(void*), void *argument) { crl::wrap_main_queue([](void (*callable)(void*), void *argument) {
App().registerEnterFromEventLoop(); Sandbox::Instance().registerEnterFromEventLoop();
const auto wrap = App().createEventNestingLevel(); const auto wrap = Sandbox::Instance().createEventNestingLevel();
callable(argument); callable(argument);
}); });

View file

@ -5,7 +5,7 @@ the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link: For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/ */
#include "application.h" #include "core/sandbox.h"
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "mainwidget.h" #include "mainwidget.h"
@ -13,7 +13,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "window/notifications_manager.h" #include "window/notifications_manager.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"
#include "messenger.h" #include "core/application.h"
#include "core/launcher.h"
#include "core/local_url_handlers.h"
#include "base/timer.h" #include "base/timer.h"
#include "base/concurrent_timer.h" #include "base/concurrent_timer.h"
#include "base/qthelp_url.h" #include "base/qthelp_url.h"
@ -21,10 +23,14 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/update_checker.h" #include "core/update_checker.h"
#include "core/crash_report_window.h" #include "core/crash_report_window.h"
namespace Core {
namespace { namespace {
constexpr auto kEmptyPidForCommandResponse = 0ULL; constexpr auto kEmptyPidForCommandResponse = 0ULL;
using ErrorSignal = void(QLocalSocket::*)(QLocalSocket::LocalSocketError);
const auto QLocalSocket_error = ErrorSignal(&QLocalSocket::error);
QChar _toHex(ushort v) { QChar _toHex(ushort v) {
v = v & 0x000F; v = v & 0x000F;
return QChar::fromLatin1((v >= 10) ? ('a' + (v - 10)) : ('0' + v)); return QChar::fromLatin1((v >= 10) ? ('a' + (v - 10)) : ('0' + v));
@ -65,48 +71,16 @@ QString _escapeFrom7bit(const QString &str) {
} // namespace } // namespace
bool InternalPassportLink(const QString &url) { Sandbox::Sandbox(
const auto urlTrimmed = url.trimmed(); not_null<Core::Launcher*> launcher,
if (!urlTrimmed.startsWith(qstr("tg://"), Qt::CaseInsensitive)) { int &argc,
return false; char **argv)
} : QApplication(argc, argv)
const auto command = urlTrimmed.midRef(qstr("tg://").size()); , _mainThreadId(QThread::currentThreadId())
, _launcher(launcher) {
using namespace qthelp;
const auto matchOptions = RegExOption::CaseInsensitive;
const auto authMatch = regex_match(
qsl("^passport/?\\?(.+)(#|$)"),
command,
matchOptions);
const auto usernameMatch = regex_match(
qsl("^resolve/?\\?(.+)(#|$)"),
command,
matchOptions);
const auto usernameValue = usernameMatch->hasMatch()
? url_parse_params(
usernameMatch->captured(1),
UrlParamNameTransform::ToLower).value(qsl("domain"))
: QString();
const auto authLegacy = (usernameValue == qstr("telegrampassport"));
return authMatch->hasMatch() || authLegacy;
} }
bool StartUrlRequiresActivate(const QString &url) { int Sandbox::start() {
return Messenger::Instance().locked()
? true
: !InternalPassportLink(url);
}
Application::Application(
not_null<Core::Launcher*> launcher,
int &argc,
char **argv)
: QApplication(argc, argv)
, _mainThreadId(QThread::currentThreadId())
, _launcher(launcher) {
}
int Application::execute() {
if (!Core::UpdaterDisabled()) { if (!Core::UpdaterDisabled()) {
_updateChecker = std::make_unique<Core::UpdateChecker>(); _updateChecker = std::make_unique<Core::UpdateChecker>();
} }
@ -120,37 +94,96 @@ int Application::execute() {
_localServerName = psServerPrefix() + h; _localServerName = psServerPrefix() + h;
#endif // OS_MAC_STORE #endif // OS_MAC_STORE
connect(&_localSocket, SIGNAL(connected()), this, SLOT(socketConnected())); connect(
connect(&_localSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); &_localSocket,
connect(&_localSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError))); &QLocalSocket::connected,
connect(&_localSocket, SIGNAL(bytesWritten(qint64)), this, SLOT(socketWritten(qint64))); [=] { socketConnected(); });
connect(&_localSocket, SIGNAL(readyRead()), this, SLOT(socketReading())); connect(
connect(&_localServer, SIGNAL(newConnection()), this, SLOT(newInstanceConnected())); &_localSocket,
&QLocalSocket::disconnected,
[=] { socketDisconnected(); });
connect(
&_localSocket,
QLocalSocket_error,
[=](QLocalSocket::LocalSocketError error) { socketError(error); });
connect(
&_localSocket,
&QLocalSocket::bytesWritten,
[=](qint64 bytes) { socketWritten(bytes); });
connect(
&_localSocket,
&QLocalSocket::readyRead,
[=] { socketReading(); });
connect(
&_localServer,
&QLocalServer::newConnection,
[=] { newInstanceConnected(); });
QTimer::singleShot(0, this, SLOT(startApplication())); crl::on_main(this, [=] { checkForQuit(); });
connect(this, SIGNAL(aboutToQuit()), this, SLOT(closeApplication())); connect(
this,
&QCoreApplication::aboutToQuit,
[=] { closeApplication(); });
if (cManyInstance()) { if (cManyInstance()) {
LOG(("Many instance allowed, starting...")); LOG(("Many instance allowed, starting..."));
singleInstanceChecked(); singleInstanceChecked();
} else { } else {
LOG(("Connecting local socket to %1...").arg(_localServerName)); LOG(("Connecting local socket to %1...").arg(_localServerName));
_localSocket.connectToServer(_localServerName); _localSocket.connectToServer(_localServerName);
} }
return exec(); return exec();
} }
Application::~Application() = default; void Sandbox::launchApplication() {
if (_application) {
return;
}
bool Application::event(QEvent *e) { const auto dpi = Sandbox::primaryScreen()->logicalDotsPerInch();
LOG(("Primary screen DPI: %1").arg(dpi));
if (dpi <= 108) {
cSetScreenScale(100); // 100%: 96 DPI (0-108)
} else if (dpi <= 132) {
cSetScreenScale(125); // 125%: 120 DPI (108-132)
} else if (dpi <= 168) {
cSetScreenScale(150); // 150%: 144 DPI (132-168)
} else if (dpi <= 216) {
cSetScreenScale(200); // 200%: 192 DPI (168-216)
} else if (dpi <= 264) {
cSetScreenScale(250); // 250%: 240 DPI (216-264)
} else {
cSetScreenScale(300); // 300%: 288 DPI (264-inf)
}
const auto ratio = devicePixelRatio();
if (ratio > 1.) {
if ((cPlatform() != dbipMac && cPlatform() != dbipMacOld) || (ratio != 2.)) {
LOG(("Found non-trivial Device Pixel Ratio: %1").arg(ratio));
LOG(("Environmental variables: QT_DEVICE_PIXEL_RATIO='%1'").arg(QString::fromLatin1(qgetenv("QT_DEVICE_PIXEL_RATIO"))));
LOG(("Environmental variables: QT_SCALE_FACTOR='%1'").arg(QString::fromLatin1(qgetenv("QT_SCALE_FACTOR"))));
LOG(("Environmental variables: QT_AUTO_SCREEN_SCALE_FACTOR='%1'").arg(QString::fromLatin1(qgetenv("QT_AUTO_SCREEN_SCALE_FACTOR"))));
LOG(("Environmental variables: QT_SCREEN_SCALE_FACTORS='%1'").arg(QString::fromLatin1(qgetenv("QT_SCREEN_SCALE_FACTORS"))));
}
cSetRetinaFactor(ratio);
cSetIntRetinaFactor(int32(ratio));
cSetScreenScale(kInterfaceScaleDefault);
}
runApplication();
}
Sandbox::~Sandbox() = default;
bool Sandbox::event(QEvent *e) {
if (e->type() == QEvent::Close) { if (e->type() == QEvent::Close) {
App::quit(); App::quit();
} }
return QApplication::event(e); return QApplication::event(e);
} }
void Application::socketConnected() { void Sandbox::socketConnected() {
LOG(("Socket connected, this is not the first application instance, sending show command...")); LOG(("Socket connected, this is not the first application instance, sending show command..."));
_secondInstance = true; _secondInstance = true;
@ -165,11 +198,11 @@ void Application::socketConnected() {
commands += qsl("CMD:show;"); commands += qsl("CMD:show;");
} }
DEBUG_LOG(("Application Info: writing commands %1").arg(commands)); DEBUG_LOG(("Sandbox Info: writing commands %1").arg(commands));
_localSocket.write(commands.toLatin1()); _localSocket.write(commands.toLatin1());
} }
void Application::socketWritten(qint64/* bytes*/) { void Sandbox::socketWritten(qint64/* bytes*/) {
if (_localSocket.state() != QLocalSocket::ConnectedState) { if (_localSocket.state() != QLocalSocket::ConnectedState) {
LOG(("Socket is not connected %1").arg(_localSocket.state())); LOG(("Socket is not connected %1").arg(_localSocket.state()));
return; return;
@ -180,7 +213,7 @@ void Application::socketWritten(qint64/* bytes*/) {
LOG(("Show command written, waiting response...")); LOG(("Show command written, waiting response..."));
} }
void Application::socketReading() { void Sandbox::socketReading() {
if (_localSocket.state() != QLocalSocket::ConnectedState) { if (_localSocket.state() != QLocalSocket::ConnectedState) {
LOG(("Socket is not connected %1").arg(_localSocket.state())); LOG(("Socket is not connected %1").arg(_localSocket.state()));
return; return;
@ -196,7 +229,7 @@ void Application::socketReading() {
} }
} }
void Application::socketError(QLocalSocket::LocalSocketError e) { void Sandbox::socketError(QLocalSocket::LocalSocketError e) {
if (App::quitting()) return; if (App::quitting()) return;
if (_secondInstance) { if (_secondInstance) {
@ -211,7 +244,7 @@ void Application::socketError(QLocalSocket::LocalSocketError e) {
} }
_localSocket.close(); _localSocket.close();
// Local server does not work in WinRT build. // Local server does not work in WinRT build.
#ifndef Q_OS_WINRT #ifndef Q_OS_WINRT
psCheckLocalSocket(_localServerName); psCheckLocalSocket(_localServerName);
@ -225,61 +258,78 @@ void Application::socketError(QLocalSocket::LocalSocketError e) {
&& !cNoStartUpdate() && !cNoStartUpdate()
&& Core::checkReadyUpdate()) { && Core::checkReadyUpdate()) {
cSetRestartingUpdate(true); cSetRestartingUpdate(true);
DEBUG_LOG(("Application Info: installing update instead of starting app...")); DEBUG_LOG(("Sandbox Info: installing update instead of starting app..."));
return App::quit(); return App::quit();
} }
singleInstanceChecked(); singleInstanceChecked();
} }
void Application::singleInstanceChecked() { void Sandbox::singleInstanceChecked() {
if (cManyInstance()) { if (cManyInstance()) {
Logs::multipleInstances(); Logs::multipleInstances();
} }
Sandbox::start();
refreshGlobalProxy(); refreshGlobalProxy();
if (!Logs::started() || (!cManyInstance() && !Logs::instanceChecked())) { if (!Logs::started() || (!cManyInstance() && !Logs::instanceChecked())) {
new NotStartedWindow(); new NotStartedWindow();
} else { return;
const auto status = CrashReports::Start(); }
const auto result = CrashReports::Start();
result.match([&](CrashReports::Status status) {
if (status == CrashReports::CantOpen) { if (status == CrashReports::CantOpen) {
new NotStartedWindow(); new NotStartedWindow();
} else if (status == CrashReports::LastCrashed) {
if (Sandbox::LastCrashDump().isEmpty()) { // don't handle bad closing for now
if (CrashReports::Restart() == CrashReports::CantOpen) {
new NotStartedWindow();
} else {
Sandbox::launch();
}
} else {
new LastCrashedWindow();
}
} else { } else {
Sandbox::launch(); launchApplication();
} }
} }, [&](const QByteArray &crashdump) {
// If crash dump is empty with that status it means that we
// didn't close the application properly. Just ignore for now.
if (crashdump.isEmpty()) {
if (CrashReports::Restart() == CrashReports::CantOpen) {
new NotStartedWindow();
} else {
launchApplication();
}
return;
}
_lastCrashDump = crashdump;
auto window = new LastCrashedWindow(
_launcher,
_lastCrashDump,
[=] { launchApplication(); });
window->proxyChanges(
) | rpl::start_with_next([=](ProxyData &&proxy) {
_sandboxProxy = std::move(proxy);
refreshGlobalProxy();
}, window->lifetime());
});
} }
void Application::socketDisconnected() { void Sandbox::socketDisconnected() {
if (_secondInstance) { if (_secondInstance) {
DEBUG_LOG(("Application Error: socket disconnected before command response received, quitting...")); DEBUG_LOG(("Sandbox Error: socket disconnected before command response received, quitting..."));
return App::quit(); return App::quit();
} }
} }
void Application::newInstanceConnected() { void Sandbox::newInstanceConnected() {
DEBUG_LOG(("Application Info: new local socket connected")); DEBUG_LOG(("Sandbox Info: new local socket connected"));
for (QLocalSocket *client = _localServer.nextPendingConnection(); client; client = _localServer.nextPendingConnection()) { for (auto client = _localServer.nextPendingConnection(); client; client = _localServer.nextPendingConnection()) {
_localClients.push_back(LocalClient(client, QByteArray())); _localClients.push_back(LocalClient(client, QByteArray()));
connect(client, SIGNAL(readyRead()), this, SLOT(readClients())); connect(
connect(client, SIGNAL(disconnected()), this, SLOT(removeClients())); client,
&QLocalSocket::readyRead,
[=] { readClients(); });
connect(
client,
&QLocalSocket::disconnected,
[=] { removeClients(); });
} }
} }
void Application::readClients() { void Sandbox::readClients() {
// This method can be called before Messenger is constructed. // This method can be called before Application is constructed.
QString startUrl; QString startUrl;
QStringList toSend; QStringList toSend;
for (LocalClients::iterator i = _localClients.begin(), e = _localClients.end(); i != e; ++i) { for (LocalClients::iterator i = _localClients.begin(), e = _localClients.end(); i != e; ++i) {
@ -290,8 +340,8 @@ void Application::readClients() {
for (int32 to = cmds.indexOf(QChar(';'), from); to >= from; to = (from < l) ? cmds.indexOf(QChar(';'), from) : -1) { for (int32 to = cmds.indexOf(QChar(';'), from); to >= from; to = (from < l) ? cmds.indexOf(QChar(';'), from) : -1) {
QStringRef cmd(&cmds, from, to - from); QStringRef cmd(&cmds, from, to - from);
if (cmd.startsWith(qsl("CMD:"))) { if (cmd.startsWith(qsl("CMD:"))) {
Sandbox::execExternal(cmds.mid(from + 4, to - from - 4)); execExternal(cmds.mid(from + 4, to - from - 4));
const auto response = qsl("RES:%1;").arg(QCoreApplication::applicationPid()).toLatin1(); const auto response = qsl("RES:%1;").arg(QApplication::applicationPid()).toLatin1();
i->first->write(response.data(), response.size()); i->first->write(response.data(), response.size());
} else if (cmd.startsWith(qsl("SEND:"))) { } else if (cmd.startsWith(qsl("SEND:"))) {
if (cSendPaths().isEmpty()) { if (cSendPaths().isEmpty()) {
@ -304,15 +354,15 @@ void Application::readClients() {
activateRequired = StartUrlRequiresActivate(startUrl); activateRequired = StartUrlRequiresActivate(startUrl);
} }
if (activateRequired) { if (activateRequired) {
Sandbox::execExternal("show"); execExternal("show");
} }
const auto responsePid = activateRequired const auto responsePid = activateRequired
? QCoreApplication::applicationPid() ? QApplication::applicationPid()
: kEmptyPidForCommandResponse; : kEmptyPidForCommandResponse;
const auto response = qsl("RES:%1;").arg(responsePid).toLatin1(); const auto response = qsl("RES:%1;").arg(responsePid).toLatin1();
i->first->write(response.data(), response.size()); i->first->write(response.data(), response.size());
} else { } else {
LOG(("Application Error: unknown command %1 passed in local socket").arg(QString(cmd.constData(), cmd.length()))); LOG(("Sandbox Error: unknown command %1 passed in local socket").arg(QString(cmd.constData(), cmd.length())));
} }
from = to + 1; from = to + 1;
} }
@ -334,16 +384,17 @@ void Application::readClients() {
if (!startUrl.isEmpty()) { if (!startUrl.isEmpty()) {
cSetStartUrl(startUrl); cSetStartUrl(startUrl);
} }
if (auto messenger = Messenger::InstancePointer()) { if (_application) {
messenger->checkStartUrl(); _application->checkStartUrl();
} }
} }
void Application::removeClients() { void Sandbox::removeClients() {
DEBUG_LOG(("Application Info: remove clients slot called, clients %1").arg(_localClients.size())); DEBUG_LOG(("Sandbox Info: remove clients slot called, clients %1"
for (LocalClients::iterator i = _localClients.begin(), e = _localClients.end(); i != e;) { ).arg(_localClients.size()));
for (auto i = _localClients.begin(), e = _localClients.end(); i != e;) {
if (i->first->state() != QLocalSocket::ConnectedState) { if (i->first->state() != QLocalSocket::ConnectedState) {
DEBUG_LOG(("Application Info: removing client")); DEBUG_LOG(("Sandbox Info: removing client"));
i = _localClients.erase(i); i = _localClients.erase(i);
e = _localClients.end(); e = _localClients.end();
} else { } else {
@ -352,34 +403,33 @@ void Application::removeClients() {
} }
} }
void Application::startApplication() { void Sandbox::checkForQuit() {
if (App::quitting()) { if (App::quitting()) {
quit(); quit();
} }
} }
void Application::createMessenger() { void Sandbox::runApplication() {
Expects(!App::quitting()); Expects(!App::quitting());
_messengerInstance = std::make_unique<Messenger>(_launcher); _application = std::make_unique<Application>(_launcher);
// Ideally this should go to constructor. // Ideally this should go to constructor.
// But we want to catch all native events and Messenger installs // But we want to catch all native events and Application installs
// its own filter that can filter out some of them. So we install // its own filter that can filter out some of them. So we install
// our filter after the Messenger constructor installs his. // our filter after the Application constructor installs his.
installNativeEventFilter(this); installNativeEventFilter(this);
_application->run();
} }
void Application::refreshGlobalProxy() { void Sandbox::refreshGlobalProxy() {
#ifndef TDESKTOP_DISABLE_NETWORK_PROXY #ifndef TDESKTOP_DISABLE_NETWORK_PROXY
const auto proxy = [&] { const auto proxy = !Global::started()
if (Global::started()) { ? _sandboxProxy
return (Global::ProxySettings() == ProxyData::Settings::Enabled) : (Global::ProxySettings() == ProxyData::Settings::Enabled)
? Global::SelectedProxy() ? Global::SelectedProxy()
: ProxyData(); : ProxyData();
}
return Sandbox::PreLaunchProxy();
}();
if (proxy.type == ProxyData::Type::Socks5 if (proxy.type == ProxyData::Type::Socks5
|| proxy.type == ProxyData::Type::Http) { || proxy.type == ProxyData::Type::Http) {
QNetworkProxy::setApplicationProxy( QNetworkProxy::setApplicationProxy(
@ -393,7 +443,11 @@ void Application::refreshGlobalProxy() {
#endif // TDESKTOP_DISABLE_NETWORK_PROXY #endif // TDESKTOP_DISABLE_NETWORK_PROXY
} }
void Application::postponeCall(FnMut<void()> &&callable) { uint64 Sandbox::installationTag() const {
return _launcher->installationTag();
}
void Sandbox::postponeCall(FnMut<void()> &&callable) {
Expects(callable != nullptr); Expects(callable != nullptr);
Expects(_eventNestingLevel >= _loopNestingLevel); Expects(_eventNestingLevel >= _loopNestingLevel);
@ -413,14 +467,14 @@ void Application::postponeCall(FnMut<void()> &&callable) {
_postponedCalls.push_back({ _postponedCalls.push_back({
_loopNestingLevel, _loopNestingLevel,
std::move(callable) std::move(callable)
}); });
} }
void Application::incrementEventNestingLevel() { void Sandbox::incrementEventNestingLevel() {
++_eventNestingLevel; ++_eventNestingLevel;
} }
void Application::decrementEventNestingLevel() { void Sandbox::decrementEventNestingLevel() {
if (_eventNestingLevel == _loopNestingLevel) { if (_eventNestingLevel == _loopNestingLevel) {
_loopNestingLevel = _previousLoopNestingLevels.back(); _loopNestingLevel = _previousLoopNestingLevels.back();
_previousLoopNestingLevels.pop_back(); _previousLoopNestingLevels.pop_back();
@ -430,14 +484,14 @@ void Application::decrementEventNestingLevel() {
_eventNestingLevel = processTillLevel; _eventNestingLevel = processTillLevel;
} }
void Application::registerEnterFromEventLoop() { void Sandbox::registerEnterFromEventLoop() {
if (_eventNestingLevel > _loopNestingLevel) { if (_eventNestingLevel > _loopNestingLevel) {
_previousLoopNestingLevels.push_back(_loopNestingLevel); _previousLoopNestingLevels.push_back(_loopNestingLevel);
_loopNestingLevel = _eventNestingLevel; _loopNestingLevel = _eventNestingLevel;
} }
} }
bool Application::notify(QObject *receiver, QEvent *e) { bool Sandbox::notify(QObject *receiver, QEvent *e) {
if (QThread::currentThreadId() != _mainThreadId) { if (QThread::currentThreadId() != _mainThreadId) {
return QApplication::notify(receiver, e); return QApplication::notify(receiver, e);
} }
@ -446,7 +500,7 @@ bool Application::notify(QObject *receiver, QEvent *e) {
return QApplication::notify(receiver, e); return QApplication::notify(receiver, e);
} }
void Application::processPostponedCalls(int level) { void Sandbox::processPostponedCalls(int level) {
while (!_postponedCalls.empty()) { while (!_postponedCalls.empty()) {
auto &last = _postponedCalls.back(); auto &last = _postponedCalls.back();
if (last.loopNestingLevel != level) { if (last.loopNestingLevel != level) {
@ -458,15 +512,15 @@ void Application::processPostponedCalls(int level) {
} }
} }
bool Application::nativeEventFilter( bool Sandbox::nativeEventFilter(
const QByteArray &eventType, const QByteArray &eventType,
void *message, void *message,
long *result) { long *result) {
registerEnterFromEventLoop(); registerEnterFromEventLoop();
return false; return false;
} }
void Application::activateWindowDelayed(not_null<QWidget*> widget) { void Sandbox::activateWindowDelayed(not_null<QWidget*> widget) {
if (_delayedActivationsPaused) { if (_delayedActivationsPaused) {
return; return;
} else if (std::exchange(_windowForDelayedActivation, widget.get())) { } else if (std::exchange(_windowForDelayedActivation, widget.get())) {
@ -481,27 +535,30 @@ void Application::activateWindowDelayed(not_null<QWidget*> widget) {
}); });
} }
void Application::pauseDelayedWindowActivations() { void Sandbox::pauseDelayedWindowActivations() {
_windowForDelayedActivation = nullptr; _windowForDelayedActivation = nullptr;
_delayedActivationsPaused = true; _delayedActivationsPaused = true;
} }
void Application::resumeDelayedWindowActivations() { void Sandbox::resumeDelayedWindowActivations() {
_delayedActivationsPaused = false; _delayedActivationsPaused = false;
} }
void Application::closeApplication() { ProxyData Sandbox::sandboxProxy() const {
if (App::launchState() == App::QuitProcessed) return; return _sandboxProxy;
}
void Sandbox::closeApplication() {
if (App::launchState() == App::QuitProcessed) {
return;
}
App::setLaunchState(App::QuitProcessed); App::setLaunchState(App::QuitProcessed);
_messengerInstance.reset(); _application = nullptr;
Sandbox::finish();
_localServer.close(); _localServer.close();
for (LocalClients::iterator i = _localClients.begin(), e = _localClients.end(); i != e; ++i) { for (const auto &localClient : base::take(_localClients)) {
disconnect(i->first, SIGNAL(disconnected()), this, SLOT(removeClients())); localClient.first->close();
i->first->close();
} }
_localClients.clear(); _localClients.clear();
@ -510,10 +567,8 @@ void Application::closeApplication() {
_updateChecker = nullptr; _updateChecker = nullptr;
} }
namespace Sandbox { void Sandbox::execExternal(const QString &cmd) {
DEBUG_LOG(("Sandbox Info: executing external command '%1'").arg(cmd));
void execExternal(const QString &cmd) {
DEBUG_LOG(("Application Info: executing external command '%1'").arg(cmd));
if (cmd == "show") { if (cmd == "show") {
if (App::wnd()) { if (App::wnd()) {
App::wnd()->activate(); App::wnd()->activate();
@ -523,38 +578,4 @@ void execExternal(const QString &cmd) {
} }
} }
void launch() { } // namespace Core
const auto dpi = Application::primaryScreen()->logicalDotsPerInch();
LOG(("Primary screen DPI: %1").arg(dpi));
if (dpi <= 108) {
cSetScreenScale(100); // 100%: 96 DPI (0-108)
} else if (dpi <= 132) {
cSetScreenScale(125); // 125%: 120 DPI (108-132)
} else if (dpi <= 168) {
cSetScreenScale(150); // 150%: 144 DPI (132-168)
} else if (dpi <= 216) {
cSetScreenScale(200); // 200%: 192 DPI (168-216)
} else if (dpi <= 264) {
cSetScreenScale(250); // 250%: 240 DPI (216-264)
} else {
cSetScreenScale(300); // 300%: 288 DPI (264-inf)
}
auto devicePixelRatio = Core::App().devicePixelRatio();
if (devicePixelRatio > 1.) {
if ((cPlatform() != dbipMac && cPlatform() != dbipMacOld) || (devicePixelRatio != 2.)) {
LOG(("Found non-trivial Device Pixel Ratio: %1").arg(devicePixelRatio));
LOG(("Environmental variables: QT_DEVICE_PIXEL_RATIO='%1'").arg(QString::fromLatin1(qgetenv("QT_DEVICE_PIXEL_RATIO"))));
LOG(("Environmental variables: QT_SCALE_FACTOR='%1'").arg(QString::fromLatin1(qgetenv("QT_SCALE_FACTOR"))));
LOG(("Environmental variables: QT_AUTO_SCREEN_SCALE_FACTOR='%1'").arg(QString::fromLatin1(qgetenv("QT_AUTO_SCREEN_SCALE_FACTOR"))));
LOG(("Environmental variables: QT_SCREEN_SCALE_FACTORS='%1'").arg(QString::fromLatin1(qgetenv("QT_SCREEN_SCALE_FACTORS"))));
}
cSetRetinaFactor(devicePixelRatio);
cSetIntRetinaFactor(int32(cRetinaFactor()));
cSetScreenScale(kInterfaceScaleDefault);
}
Core::App().createMessenger();
}
} // namespace Sandbox

View file

@ -8,23 +8,24 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#pragma once #pragma once
namespace Core { namespace Core {
class Launcher; class Launcher;
class UpdateChecker; class UpdateChecker;
} // namespace Core class Application;
bool InternalPassportLink(const QString &url);
bool StartUrlRequiresActivate(const QString &url);
class Application : public QApplication, private QAbstractNativeEventFilter {
Q_OBJECT
class Sandbox final
: public QApplication
, private QAbstractNativeEventFilter {
public: public:
Application(not_null<Core::Launcher*> launcher, int &argc, char **argv); Sandbox(not_null<Launcher*> launcher, int &argc, char **argv);
int execute(); Sandbox(const Sandbox &other) = delete;
Sandbox &operator=(const Sandbox &other) = delete;
int start();
void createMessenger();
void refreshGlobalProxy(); void refreshGlobalProxy();
uint64 installationTag() const;
void postponeCall(FnMut<void()> &&callable); void postponeCall(FnMut<void()> &&callable);
bool notify(QObject *receiver, QEvent *e) override; bool notify(QObject *receiver, QEvent *e) override;
@ -38,22 +39,24 @@ public:
void pauseDelayedWindowActivations(); void pauseDelayedWindowActivations();
void resumeDelayedWindowActivations(); void resumeDelayedWindowActivations();
~Application(); ProxyData sandboxProxy() const;
// Single instance application static Sandbox &Instance() {
public slots: Expects(QApplication::instance() != nullptr);
void socketConnected();
void socketError(QLocalSocket::LocalSocketError e);
void socketDisconnected();
void socketWritten(qint64 bytes);
void socketReading();
void newInstanceConnected();
void readClients(); return *static_cast<Sandbox*>(QApplication::instance());
void removeClients(); }
void startApplication(); // will be done in exec() bool applicationLaunched() const {
void closeApplication(); // will be done in aboutToQuit() return _application != nullptr;
}
Application &application() const {
Expects(_application != nullptr);
return *_application;
}
~Sandbox();
protected: protected:
bool event(QEvent *e) override; bool event(QEvent *e) override;
@ -67,6 +70,8 @@ private:
FnMut<void()> callable; FnMut<void()> callable;
}; };
void closeApplication(); // will be done in aboutToQuit()
void checkForQuit(); // will be done in exec()
void incrementEventNestingLevel(); void incrementEventNestingLevel();
void decrementEventNestingLevel(); void decrementEventNestingLevel();
bool nativeEventFilter( bool nativeEventFilter(
@ -74,6 +79,21 @@ private:
void *message, void *message,
long *result) override; long *result) override;
void processPostponedCalls(int level); void processPostponedCalls(int level);
void singleInstanceChecked();
void launchApplication();
void runApplication();
void execExternal(const QString &cmd);
// Single instance application
void socketConnected();
void socketError(QLocalSocket::LocalSocketError e);
void socketDisconnected();
void socketWritten(qint64 bytes);
void socketReading();
void newInstanceConnected();
void readClients();
void removeClients();
const Qt::HANDLE _mainThreadId = nullptr; const Qt::HANDLE _mainThreadId = nullptr;
int _eventNestingLevel = 0; int _eventNestingLevel = 0;
@ -84,8 +104,8 @@ private:
QPointer<QWidget> _windowForDelayedActivation; QPointer<QWidget> _windowForDelayedActivation;
bool _delayedActivationsPaused = false; bool _delayedActivationsPaused = false;
not_null<Core::Launcher*> _launcher; not_null<Launcher*> _launcher;
std::unique_ptr<Messenger> _messengerInstance; std::unique_ptr<Application> _application;
QString _localServerName, _localSocketReadData; QString _localServerName, _localSocketReadData;
QLocalServer _localServer; QLocalServer _localServer;
@ -93,26 +113,11 @@ private:
LocalClients _localClients; LocalClients _localClients;
bool _secondInstance = false; bool _secondInstance = false;
void singleInstanceChecked(); std::unique_ptr<UpdateChecker> _updateChecker;
private: QByteArray _lastCrashDump;
std::unique_ptr<Core::UpdateChecker> _updateChecker; ProxyData _sandboxProxy;
}; };
namespace Core {
inline Application &App() {
Expects(QCoreApplication::instance() != nullptr);
return *static_cast<Application*>(QCoreApplication::instance());
}
} // namespace Core } // namespace Core
namespace Sandbox {
void execExternal(const QString &cmd);
void launch();
} // namespace Sandbox

View file

@ -9,7 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "messenger.h" #include "core/application.h"
#include "media/player/media_player_instance.h" #include "media/player/media_player_instance.h"
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "base/parse_helper.h" #include "base/parse_helper.h"
@ -371,7 +371,7 @@ void Manager::set(const QString &keys, Command command) {
} }
auto shortcut = base::make_unique_q<QShortcut>( auto shortcut = base::make_unique_q<QShortcut>(
result, result,
Messenger::Instance().getActiveWindow(), Core::App().getActiveWindow(),
nullptr, nullptr,
nullptr, nullptr,
Qt::ApplicationShortcut); Qt::ApplicationShortcut);

View file

@ -7,12 +7,12 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/ */
#include "core/update_checker.h" #include "core/update_checker.h"
#include "application.h"
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "base/timer.h" #include "base/timer.h"
#include "base/bytes.h" #include "base/bytes.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "messenger.h" #include "core/application.h"
#include "core/sandbox.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "core/click_handler_types.h" #include "core/click_handler_types.h"
#include "info/info_memento.h" #include "info/info_memento.h"
@ -1187,7 +1187,7 @@ void Updater::stop() {
} }
void Updater::start(bool forceWait) { void Updater::start(bool forceWait) {
if (!Sandbox::started() || cExeName().isEmpty()) { if (cExeName().isEmpty()) {
return; return;
} }
@ -1382,8 +1382,8 @@ Updater::~Updater() {
UpdateChecker::UpdateChecker() UpdateChecker::UpdateChecker()
: _updater(GetUpdaterInstance()) { : _updater(GetUpdaterInstance()) {
if (const auto messenger = Messenger::InstancePointer()) { if (Sandbox::Instance().applicationLaunched()) {
if (const auto mtproto = messenger->mtp()) { if (const auto mtproto = Core::App().mtp()) {
_updater->setMtproto(mtproto); _updater->setMtproto(mtproto);
} }
} }

View file

@ -27,7 +27,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/image/image_source.h" #include "ui/image/image_source.h"
#include "auth_session.h" #include "auth_session.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h" #include "core/application.h"
namespace { namespace {
@ -299,7 +299,7 @@ void DocumentOpenClickHandler::Open(
auto &location = data->location(true); auto &location = data->location(true);
if (data->isTheme()) { if (data->isTheme()) {
if (!location.isEmpty() && location.accessEnable()) { if (!location.isEmpty() && location.accessEnable()) {
Messenger::Instance().showDocument(data, context); Core::App().showDocument(data, context);
location.accessDisable(); location.accessDisable();
return; return;
} }
@ -335,9 +335,9 @@ void DocumentOpenClickHandler::Open(
} }
} else if (playVideo) { } else if (playVideo) {
if (!data->data().isEmpty()) { if (!data->data().isEmpty()) {
Messenger::Instance().showDocument(data, context); Core::App().showDocument(data, context);
} else if (location.accessEnable()) { } else if (location.accessEnable()) {
Messenger::Instance().showDocument(data, context); Core::App().showDocument(data, context);
location.accessDisable(); location.accessDisable();
} else { } else {
const auto filepath = location.name(); const auto filepath = location.name();
@ -357,14 +357,14 @@ void DocumentOpenClickHandler::Open(
if (action == ActionOnLoadPlayInline && context) { if (action == ActionOnLoadPlayInline && context) {
data->session()->data().requestAnimationPlayInline(context); data->session()->data().requestAnimationPlayInline(context);
} else { } else {
Messenger::Instance().showDocument(data, context); Core::App().showDocument(data, context);
} }
} else if (location.accessEnable()) { } else if (location.accessEnable()) {
if (playAnimation || QImageReader(location.name()).canRead()) { if (playAnimation || QImageReader(location.name()).canRead()) {
if (playAnimation && action == ActionOnLoadPlayInline && context) { if (playAnimation && action == ActionOnLoadPlayInline && context) {
data->session()->data().requestAnimationPlayInline(context); data->session()->data().requestAnimationPlayInline(context);
} else { } else {
Messenger::Instance().showDocument(data, context); Core::App().showDocument(data, context);
} }
} else { } else {
LaunchWithWarning(location.name(), context); LaunchWithWarning(location.name(), context);
@ -720,7 +720,7 @@ void DocumentData::performActionOnLoad() {
&& item; && item;
if (auto applyTheme = isTheme()) { if (auto applyTheme = isTheme()) {
if (!loc.isEmpty() && loc.accessEnable()) { if (!loc.isEmpty() && loc.accessEnable()) {
Messenger::Instance().showDocument(this, item); Core::App().showDocument(this, item);
loc.accessDisable(); loc.accessDisable();
return; return;
} }
@ -760,7 +760,7 @@ void DocumentData::performActionOnLoad() {
if (_actionOnLoad == ActionOnLoadPlayInline && item) { if (_actionOnLoad == ActionOnLoadPlayInline && item) {
_session->data().requestAnimationPlayInline(item); _session->data().requestAnimationPlayInline(item);
} else { } else {
Messenger::Instance().showDocument(this, item); Core::App().showDocument(this, item);
} }
} }
} else { } else {
@ -776,7 +776,7 @@ void DocumentData::performActionOnLoad() {
_session->data().markMediaRead(this); _session->data().markMediaRead(this);
} else if (loc.accessEnable()) { } else if (loc.accessEnable()) {
if (showImage && QImageReader(loc.name()).canRead()) { if (showImage && QImageReader(loc.name()).canRead()) {
Messenger::Instance().showDocument(this, item); Core::App().showDocument(this, item);
} else { } else {
LaunchWithWarning(already, item); LaunchWithWarning(already, item);
} }

View file

@ -20,7 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "apiwrap.h" #include "apiwrap.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "auth_session.h" #include "auth_session.h"
#include "messenger.h" #include "core/application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "window/window_controller.h" #include "window/window_controller.h"
#include "ui/image/image.h" #include "ui/image/image.h"
@ -315,7 +315,7 @@ void PeerData::clearUserpic() {
const auto loc = StorageImageLocation(); const auto loc = StorageImageLocation();
const auto photo = [&] { const auto photo = [&] {
if (id == peerFromUser(ServiceUserId)) { if (id == peerFromUser(ServiceUserId)) {
auto image = Messenger::Instance().logoNoMargin().scaledToWidth( auto image = Core::App().logoNoMargin().scaledToWidth(
kUserpicSize, kUserpicSize,
Qt::SmoothTransformation); Qt::SmoothTransformation);
return _userpic return _userpic

View file

@ -13,7 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/image/image_source.h" #include "ui/image/image_source.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "auth_session.h" #include "auth_session.h"
#include "messenger.h" #include "core/application.h"
PhotoData::PhotoData(const PhotoId &id) PhotoData::PhotoData(const PhotoId &id)
: id(id) { : id(id) {
@ -167,7 +167,7 @@ void PhotoData::collectLocalData(PhotoData *local) {
} }
void PhotoOpenClickHandler::onClickImpl() const { void PhotoOpenClickHandler::onClickImpl() const {
Messenger::Instance().showPhoto(this); Core::App().showPhoto(this);
} }
void PhotoSaveClickHandler::onClickImpl() const { void PhotoSaveClickHandler::onClickImpl() const {

View file

@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "observer_peer.h" #include "observer_peer.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "messenger.h" #include "core/application.h"
#include "core/crash_reports.h" // for CrashReports::SetAnnotation #include "core/crash_reports.h" // for CrashReports::SetAnnotation
#include "ui/image/image.h" #include "ui/image/image.h"
#include "export/export_controller.h" #include "export/export_controller.h"
@ -145,7 +145,7 @@ MTPPhotoSize FindDocumentThumb(const MTPDdocument &data) {
Session::Session(not_null<AuthSession*> session) Session::Session(not_null<AuthSession*> session)
: _session(session) : _session(session)
, _cache(Messenger::Instance().databases().get( , _cache(Core::App().databases().get(
Local::cachePath(), Local::cachePath(),
Local::cacheSettings())) Local::cacheSettings()))
, _selfDestructTimer([=] { checkSelfDestructItems(); }) , _selfDestructTimer([=] { checkSelfDestructItems(); })

View file

@ -18,13 +18,12 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/wrap/fade_wrap.h" #include "ui/wrap/fade_wrap.h"
#include "ui/effects/radial_animation.h" #include "ui/effects/radial_animation.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "core/update_checker.h" #include "core/update_checker.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "messenger.h" #include "core/application.h"
#include "boxes/peer_list_box.h" #include "boxes/peer_list_box.h"
#include "boxes/peers/edit_participants_box.h" #include "boxes/peers/edit_participants_box.h"
#include "window/window_controller.h" #include "window/window_controller.h"
@ -207,7 +206,7 @@ DialogsWidget::DialogsWidget(QWidget *parent, not_null<Window::Controller*> cont
subscribe(Global::RefLocalPasscodeChanged(), [this] { updateLockUnlockVisibility(); }); subscribe(Global::RefLocalPasscodeChanged(), [this] { updateLockUnlockVisibility(); });
_lockUnlock->setClickedCallback([this] { _lockUnlock->setClickedCallback([this] {
_lockUnlock->setIconOverride(&st::dialogsUnlockIcon, &st::dialogsUnlockIconOver); _lockUnlock->setIconOverride(&st::dialogsUnlockIcon, &st::dialogsUnlockIconOver);
Messenger::Instance().lockByPasscode(); Core::App().lockByPasscode();
_lockUnlock->setIconOverride(nullptr); _lockUnlock->setIconOverride(nullptr);
}); });
_mainMenuToggle->setClickedCallback([this] { showMainMenu(); }); _mainMenuToggle->setClickedCallback([this] { showMainMenu(); });

View file

@ -9,6 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "info/info_memento.h" #include "info/info_memento.h"
#include "core/click_handler_types.h" #include "core/click_handler_types.h"
#include "core/application.h"
#include "media/media_clip_reader.h" #include "media/media_clip_reader.h"
#include "window/window_controller.h" #include "window/window_controller.h"
#include "history/history_item_components.h" #include "history/history_item_components.h"
@ -18,7 +19,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "messenger.h"
#include "auth_session.h" #include "auth_session.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "window/layer_widget.h" #include "window/layer_widget.h"
@ -34,7 +34,7 @@ namespace App {
namespace internal { namespace internal {
void CallDelayed(int duration, FnMut<void()> &&lambda) { void CallDelayed(int duration, FnMut<void()> &&lambda) {
Messenger::Instance().callDelayed(duration, std::move(lambda)); Core::App().callDelayed(duration, std::move(lambda));
} }
} // namespace internal } // namespace internal
@ -153,7 +153,7 @@ void activateBotCommand(
void searchByHashtag(const QString &tag, PeerData *inPeer) { void searchByHashtag(const QString &tag, PeerData *inPeer) {
if (const auto m = App::main()) { if (const auto m = App::main()) {
Ui::hideSettingsAndLayer(); Ui::hideSettingsAndLayer();
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
if (inPeer && (!inPeer->isChannel() || inPeer->isMegagroup())) { if (inPeer && (!inPeer->isChannel() || inPeer->isMegagroup())) {
inPeer = nullptr; inPeer = nullptr;
} }
@ -271,7 +271,7 @@ void showPeerHistory(const PeerData *peer, MsgId msgId) {
} }
PeerData *getPeerForMouseAction() { PeerData *getPeerForMouseAction() {
return Messenger::Instance().ui_getPeerForMouseAction(); return Core::App().ui_getPeerForMouseAction();
} }
bool skipPaintEvent(QWidget *widget, QPaintEvent *event) { bool skipPaintEvent(QWidget *widget, QPaintEvent *event) {
@ -346,220 +346,13 @@ void Set##Name(const Type &Name) { \
Namespace##Data->Name = Name; \ Namespace##Data->Name = Name; \
} }
namespace Sandbox {
namespace internal {
struct Data {
QByteArray LastCrashDump;
ProxyData PreLaunchProxy;
};
} // namespace internal
} // namespace Sandbox
std::unique_ptr<Sandbox::internal::Data> SandboxData;
uint64 SandboxUserTag = 0;
namespace Sandbox {
bool MoveLegacyAlphaFolder(const QString &folder, const QString &file) {
const auto was = cExeDir() + folder;
const auto now = cExeDir() + qsl("TelegramForcePortable");
if (QDir(was).exists() && !QDir(now).exists()) {
const auto oldFile = was + "/tdata/" + file;
const auto newFile = was + "/tdata/alpha";
if (QFile(oldFile).exists() && !QFile(newFile).exists()) {
if (!QFile(oldFile).copy(newFile)) {
LOG(("FATAL: Could not copy '%1' to '%2'"
).arg(oldFile
).arg(newFile));
return false;
}
}
if (!QDir().rename(was, now)) {
LOG(("FATAL: Could not rename '%1' to '%2'"
).arg(was
).arg(now));
return false;
}
}
return true;
}
bool MoveLegacyAlphaFolder() {
if (!MoveLegacyAlphaFolder(qsl("TelegramAlpha_data"), qsl("alpha"))
|| !MoveLegacyAlphaFolder(qsl("TelegramBeta_data"), qsl("beta"))) {
return false;
}
return true;
}
bool CheckPortableVersionDir() {
if (!MoveLegacyAlphaFolder()) {
return false;
}
const auto portable = cExeDir() + qsl("TelegramForcePortable");
QFile key(portable + qsl("/tdata/alpha"));
if (cAlphaVersion()) {
Assert(*AlphaPrivateKey != 0);
cForceWorkingDir(portable + '/');
QDir().mkpath(cWorkingDir() + qstr("tdata"));
cSetAlphaPrivateKey(QByteArray(AlphaPrivateKey));
if (!key.open(QIODevice::WriteOnly)) {
LOG(("FATAL: Could not open '%1' for writing private key!"
).arg(key.fileName()));
return false;
}
QDataStream dataStream(&key);
dataStream.setVersion(QDataStream::Qt_5_3);
dataStream << quint64(cRealAlphaVersion()) << cAlphaPrivateKey();
return true;
}
if (!QDir(portable).exists()) {
return true;
}
cForceWorkingDir(portable + '/');
if (!key.exists()) {
return true;
}
if (!key.open(QIODevice::ReadOnly)) {
LOG(("FATAL: could not open '%1' for reading private key. "
"Delete it or reinstall private alpha version."
).arg(key.fileName()));
return false;
}
QDataStream dataStream(&key);
dataStream.setVersion(QDataStream::Qt_5_3);
quint64 v;
QByteArray k;
dataStream >> v >> k;
if (dataStream.status() != QDataStream::Ok || k.isEmpty()) {
LOG(("FATAL: '%1' is corrupted. "
"Delete it or reinstall private alpha version."
).arg(key.fileName()));
return false;
}
cSetAlphaVersion(AppVersion * 1000ULL);
cSetAlphaPrivateKey(k);
cSetRealAlphaVersion(v);
return true;
}
QString InstallBetaVersionsSettingPath() {
return cWorkingDir() + qsl("tdata/devversion");
}
void WriteInstallBetaVersionsSetting() {
QFile f(InstallBetaVersionsSettingPath());
if (f.open(QIODevice::WriteOnly)) {
f.write(cInstallBetaVersion() ? "1" : "0");
}
}
QString DebugModeSettingPath() {
return cWorkingDir() + qsl("tdata/withdebug");
}
void WriteDebugModeSetting() {
QFile f(DebugModeSettingPath());
if (f.open(QIODevice::WriteOnly)) {
f.write(Logs::DebugEnabled() ? "1" : "0");
}
}
void ComputeTestMode() {
if (QFile(cWorkingDir() + qsl("tdata/withtestmode")).exists()) {
cSetTestMode(true);
}
}
void ComputeDebugMode() {
Logs::SetDebugEnabled(cAlphaVersion() != 0);
const auto debugModeSettingPath = DebugModeSettingPath();
if (QFile(debugModeSettingPath).exists()) {
QFile f(debugModeSettingPath);
if (f.open(QIODevice::ReadOnly)) {
Logs::SetDebugEnabled(f.read(1) != "0");
}
}
}
void ComputeInstallBetaVersions() {
const auto installBetaSettingPath = InstallBetaVersionsSettingPath();
if (cAlphaVersion()) {
cSetInstallBetaVersion(false);
} else if (QFile(installBetaSettingPath).exists()) {
QFile f(installBetaSettingPath);
if (f.open(QIODevice::ReadOnly)) {
cSetInstallBetaVersion(f.read(1) != "0");
}
} else if (AppBetaVersion) {
WriteInstallBetaVersionsSetting();
}
}
void ComputeUserTag() {
SandboxUserTag = 0;
QFile usertag(cWorkingDir() + qsl("tdata/usertag"));
if (usertag.open(QIODevice::ReadOnly)) {
if (usertag.read(reinterpret_cast<char*>(&SandboxUserTag), sizeof(uint64)) != sizeof(uint64)) {
SandboxUserTag = 0;
}
usertag.close();
}
if (!SandboxUserTag) {
do {
memsetrnd_bad(SandboxUserTag);
} while (!SandboxUserTag);
if (usertag.open(QIODevice::WriteOnly)) {
usertag.write(reinterpret_cast<char*>(&SandboxUserTag), sizeof(uint64));
usertag.close();
}
}
}
void WorkingDirReady() {
srand((int32)time(NULL));
ComputeTestMode();
ComputeDebugMode();
ComputeInstallBetaVersions();
ComputeUserTag();
}
void start() {
SandboxData = std::make_unique<internal::Data>();
}
bool started() {
return (SandboxData != nullptr);
}
void finish() {
SandboxData.reset();
}
uint64 UserTag() {
return SandboxUserTag;
}
DefineVar(Sandbox, QByteArray, LastCrashDump);
DefineVar(Sandbox, ProxyData, PreLaunchProxy);
} // namespace Sandbox
namespace Global { namespace Global {
namespace internal { namespace internal {
struct Data { struct Data {
SingleQueuedInvokation HandleUnreadCounterUpdate = { [] { Messenger::Instance().call_handleUnreadCounterUpdate(); } }; SingleQueuedInvokation HandleUnreadCounterUpdate = { [] { Core::App().call_handleUnreadCounterUpdate(); } };
SingleQueuedInvokation HandleDelayedPeerUpdates = { [] { Messenger::Instance().call_handleDelayedPeerUpdates(); } }; SingleQueuedInvokation HandleDelayedPeerUpdates = { [] { Core::App().call_handleDelayedPeerUpdates(); } };
SingleQueuedInvokation HandleObservables = { [] { Messenger::Instance().call_handleObservables(); } }; SingleQueuedInvokation HandleObservables = { [] { Core::App().call_handleObservables(); } };
Adaptive::WindowLayout AdaptiveWindowLayout = Adaptive::WindowLayout::Normal; Adaptive::WindowLayout AdaptiveWindowLayout = Adaptive::WindowLayout::Normal;
Adaptive::ChatLayout AdaptiveChatLayout = Adaptive::ChatLayout::Normal; Adaptive::ChatLayout AdaptiveChatLayout = Adaptive::ChatLayout::Normal;

View file

@ -175,24 +175,6 @@ inline bool IsTopCorner(ScreenCorner corner) {
#define DeclareVar(Type, Name) DeclareRefVar(Type, Name) \ #define DeclareVar(Type, Name) DeclareRefVar(Type, Name) \
void Set##Name(const Type &Name); void Set##Name(const Type &Name);
namespace Sandbox {
bool CheckPortableVersionDir();
void WorkingDirReady();
void WriteInstallBetaVersionsSetting();
void WriteDebugModeSetting();
void start();
bool started();
void finish();
uint64 UserTag();
DeclareVar(QByteArray, LastCrashDump);
DeclareVar(ProxyData, PreLaunchProxy);
} // namespace Sandbox
namespace Adaptive { namespace Adaptive {
enum class WindowLayout { enum class WindowLayout {

View file

@ -23,7 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/sticker_set_box.h" #include "boxes/sticker_set_box.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "messenger.h" #include "core/application.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "layout.h" #include "layout.h"
#include "window/window_controller.h" #include "window/window_controller.h"
@ -1125,7 +1125,7 @@ void InnerWidget::openContextGif(FullMsgId itemId) {
if (const auto item = App::histItemById(itemId)) { if (const auto item = App::histItemById(itemId)) {
if (auto media = item->media()) { if (auto media = item->media()) {
if (auto document = media->document()) { if (auto document = media->document()) {
Messenger::Instance().showDocument(document, item); Core::App().showDocument(document, item);
} }
} }
} }

View file

@ -17,7 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_session.h" #include "data/data_session.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "boxes/sticker_set_box.h" #include "boxes/sticker_set_box.h"
#include "messenger.h" #include "core/application.h"
#include "auth_session.h" #include "auth_session.h"
namespace AdminLog { namespace AdminLog {
@ -434,10 +434,10 @@ void GenerateItems(
auto bodyFlags = Flag::f_entities | Flag::f_from_id; auto bodyFlags = Flag::f_entities | Flag::f_from_id;
auto bodyReplyTo = 0; auto bodyReplyTo = 0;
auto bodyViaBotId = 0; auto bodyViaBotId = 0;
auto newLink = newValue.isEmpty() ? TextWithEntities() : PrepareText(Messenger::Instance().createInternalLinkFull(newValue), QString()); auto newLink = newValue.isEmpty() ? TextWithEntities() : PrepareText(Core::App().createInternalLinkFull(newValue), QString());
auto body = new HistoryMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), newLink); auto body = new HistoryMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), newLink);
if (!oldValue.isEmpty()) { if (!oldValue.isEmpty()) {
auto oldLink = PrepareText(Messenger::Instance().createInternalLinkFull(oldValue), QString()); auto oldLink = PrepareText(Core::App().createInternalLinkFull(oldValue), QString());
body->addLogEntryOriginal(id, lang(lng_admin_log_previous_link), oldLink); body->addLogEntryOriginal(id, lang(lng_admin_log_previous_link), oldLink);
} }
addPart(body); addPart(body);

View file

@ -21,7 +21,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "observer_peer.h" #include "observer_peer.h"

View file

@ -37,7 +37,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwidget.h" #include "mainwidget.h"
#include "layout.h" #include "layout.h"
#include "auth_session.h" #include "auth_session.h"
#include "messenger.h" #include "core/application.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "data/data_session.h" #include "data/data_session.h"
@ -1820,7 +1820,7 @@ void HistoryInner::openContextGif(FullMsgId itemId) {
if (const auto item = App::histItemById(itemId)) { if (const auto item = App::histItemById(itemId)) {
if (const auto media = item->media()) { if (const auto media = item->media()) {
if (const auto document = media->document()) { if (const auto document = media->document()) {
Messenger::Instance().showDocument(document, item); Core::App().showDocument(document, item);
} }
} }
} }

View file

@ -27,7 +27,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "media/media_audio.h" #include "media/media_audio.h"
#include "messenger.h" #include "core/application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "window/window_controller.h" #include "window/window_controller.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"
@ -572,7 +572,7 @@ QString HistoryItem::directLink() const {
} }
} }
} }
return Messenger::Instance().createInternalLinkFull(query); return Core::App().createInternalLinkFull(query);
} }
return QString(); return QString();
} }

View file

@ -21,7 +21,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "ui/toast/toast.h" #include "ui/toast/toast.h"
#include "ui/text_options.h" #include "ui/text_options.h"
#include "messenger.h" #include "core/application.h"
#include "layout.h" #include "layout.h"
#include "window/notifications_manager.h" #include "window/notifications_manager.h"
#include "window/window_controller.h" #include "window/window_controller.h"
@ -109,7 +109,7 @@ void FastShareMessage(not_null<HistoryItem*> item) {
} else if (const auto bot = item->getMessageBot()) { } else if (const auto bot = item->getMessageBot()) {
if (const auto media = item->media()) { if (const auto media = item->media()) {
if (const auto game = media->game()) { if (const auto game = media->game()) {
const auto link = Messenger::Instance().createInternalLinkFull( const auto link = Core::App().createInternalLinkFull(
bot->username bot->username
+ qsl("?game=") + qsl("?game=")
+ game->shortName); + game->shortName);

View file

@ -52,7 +52,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "chat_helpers/bot_keyboard.h" #include "chat_helpers/bot_keyboard.h"
#include "chat_helpers/message_field.h" #include "chat_helpers/message_field.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "storage/localimageloader.h" #include "storage/localimageloader.h"
@ -62,7 +61,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "media/media_audio.h" #include "media/media_audio.h"
#include "media/media_audio_capture.h" #include "media/media_audio_capture.h"
#include "media/player/media_player_instance.h" #include "media/player/media_player_instance.h"
#include "messenger.h" #include "core/application.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "history/view/history_view_top_bar_widget.h" #include "history/view/history_view_top_bar_widget.h"
#include "observer_peer.h" #include "observer_peer.h"
@ -6145,7 +6144,7 @@ void HistoryWidget::updateTopBarSelection() {
_topBar->showSelected(selectedState); _topBar->showSelected(selectedState);
updateControlsVisibility(); updateControlsVisibility();
updateHistoryGeometry(); updateHistoryGeometry();
if (!Ui::isLayerShown() && !Messenger::Instance().locked()) { if (!Ui::isLayerShown() && !Core::App().locked()) {
if (_nonEmptySelection if (_nonEmptySelection
|| (_list && _list->wasSelectedText()) || (_list && _list->wasSelectedText())
|| _recording || _recording

View file

@ -29,7 +29,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/file_utilities.h" #include "core/file_utilities.h"
#include "window/window_peer_menu.h" #include "window/window_peer_menu.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "messenger.h" #include "core/application.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
@ -54,7 +54,7 @@ void SavePhotoToFile(not_null<PhotoData*> photo) {
} }
FileDialog::GetWritePath( FileDialog::GetWritePath(
Messenger::Instance().getFileDialogParent(), Core::App().getFileDialogParent(),
lang(lng_save_photo), lang(lng_save_photo),
qsl("JPEG Image (*.jpg);;") + FileDialog::AllFilesFilter(), qsl("JPEG Image (*.jpg);;") + FileDialog::AllFilesFilter(),
filedialogDefaultName(qsl("photo"), qsl(".jpg")), filedialogDefaultName(qsl("photo"), qsl(".jpg")),
@ -104,7 +104,7 @@ void OpenGif(FullMsgId itemId) {
if (const auto item = App::histItemById(itemId)) { if (const auto item = App::histItemById(itemId)) {
if (const auto media = item->media()) { if (const auto media = item->media()) {
if (const auto document = media->document()) { if (const auto document = media->document()) {
Messenger::Instance().showDocument(document, item); Core::App().showDocument(document, item);
} }
} }
} }

View file

@ -20,7 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "chat_helpers/message_field.h" #include "chat_helpers/message_field.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "messenger.h" #include "core/application.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "layout.h" #include "layout.h"
#include "window/window_controller.h" #include "window/window_controller.h"

View file

@ -38,7 +38,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "window/window_peer_menu.h" #include "window/window_peer_menu.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "auth_session.h" #include "auth_session.h"
#include "messenger.h" #include "core/application.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "styles/style_info.h" #include "styles/style_info.h"
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
@ -289,7 +289,7 @@ object_ptr<Ui::RpWidget> DetailsFiller::setupInfo() {
std::move(linkText), std::move(linkText),
QString()); QString());
link->setClickHandlerFilter([peer = _peer](auto&&...) { link->setClickHandlerFilter([peer = _peer](auto&&...) {
auto link = Messenger::Instance().createInternalLinkFull( auto link = Core::App().createInternalLinkFull(
peer->userName()); peer->userName());
if (!link.isEmpty()) { if (!link.isEmpty()) {
QApplication::clipboard()->setText(link); QApplication::clipboard()->setText(link);

View file

@ -23,7 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/special_buttons.h" #include "ui/special_buttons.h"
#include "window/window_controller.h" #include "window/window_controller.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "messenger.h" #include "core/application.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"

View file

@ -12,7 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include <rpl/then.h> #include <rpl/then.h>
#include <rpl/combine.h> #include <rpl/combine.h>
#include "observer_peer.h" #include "observer_peer.h"
#include "messenger.h" #include "core/application.h"
#include "auth_session.h" #include "auth_session.h"
#include "ui/wrap/slide_wrap.h" #include "ui/wrap/slide_wrap.h"
#include "data/data_peer_values.h" #include "data/data_peer_values.h"
@ -110,7 +110,7 @@ rpl::producer<QString> LinkValue(not_null<PeerData*> peer) {
) | rpl::map([](QString &&username) { ) | rpl::map([](QString &&username) {
return username.isEmpty() return username.isEmpty()
? QString() ? QString()
: Messenger::Instance().createInternalLinkFull(username); : Core::App().createInternalLinkFull(username);
}); });
} }

View file

@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "intro/introcode.h" #include "intro/introcode.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "intro/introsignup.h" #include "intro/introsignup.h"
#include "intro/intropwdcheck.h" #include "intro/intropwdcheck.h"
#include "core/update_checker.h" #include "core/update_checker.h"

View file

@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "intro/introphone.h" #include "intro/introphone.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "intro/introcode.h" #include "intro/introcode.h"
#include "styles/style_intro.h" #include "styles/style_intro.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
@ -18,7 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "base/qthelp_url.h" #include "base/qthelp_url.h"
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "messenger.h" #include "core/application.h"
namespace Intro { namespace Intro {
namespace { namespace {
@ -83,7 +82,7 @@ PhoneWidget::PhoneWidget(QWidget *parent, Widget::Data *data) : Step(parent, dat
} }
_changed = false; _changed = false;
Messenger::Instance().destroyStaleAuthorizationKeys(); Core::App().destroyStaleAuthorizationKeys();
} }
void PhoneWidget::resizeEvent(QResizeEvent *e) { void PhoneWidget::resizeEvent(QResizeEvent *e) {
@ -157,7 +156,7 @@ void PhoneWidget::submit() {
_checkRequest->start(1000); _checkRequest->start(1000);
_sentPhone = phone; _sentPhone = phone;
Messenger::Instance().mtp()->setUserPhone(_sentPhone); Core::App().mtp()->setUserPhone(_sentPhone);
//_sentRequest = MTP::send(MTPauth_CheckPhone(MTP_string(_sentPhone)), rpcDone(&PhoneWidget::phoneCheckDone), rpcFail(&PhoneWidget::phoneSubmitFail)); //_sentRequest = MTP::send(MTPauth_CheckPhone(MTP_string(_sentPhone)), rpcDone(&PhoneWidget::phoneCheckDone), rpcFail(&PhoneWidget::phoneSubmitFail));
_sentRequest = MTP::send( _sentRequest = MTP::send(
MTPauth_SendCode( MTPauth_SendCode(

View file

@ -13,7 +13,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/core_cloud_password.h" #include "core/core_cloud_password.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "intro/introsignup.h" #include "intro/introsignup.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
#include "ui/widgets/input_fields.h" #include "ui/widgets/input_fields.h"

View file

@ -13,7 +13,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/photo_crop_box.h" #include "boxes/photo_crop_box.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
#include "ui/widgets/input_fields.h" #include "ui/widgets/input_fields.h"
#include "ui/widgets/labels.h" #include "ui/widgets/labels.h"

View file

@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "intro/introstart.h" #include "intro/introstart.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "intro/introphone.h" #include "intro/introphone.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
#include "ui/widgets/labels.h" #include "ui/widgets/labels.h"

View file

@ -18,8 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwidget.h" #include "mainwidget.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h" #include "core/application.h"
#include "application.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "ui/text/text.h" #include "ui/text/text.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
@ -394,7 +393,7 @@ void Widget::getNearestDC() {
).arg(qs(nearest.vcountry) ).arg(qs(nearest.vcountry)
).arg(nearest.vnearest_dc.v ).arg(nearest.vnearest_dc.v
).arg(nearest.vthis_dc.v)); ).arg(nearest.vthis_dc.v));
Messenger::Instance().suggestMainDcId(nearest.vnearest_dc.v); Core::App().suggestMainDcId(nearest.vnearest_dc.v);
auto nearestCountry = qs(nearest.vcountry); auto nearestCountry = qs(nearest.vcountry);
if (getData()->country != nearestCountry) { if (getData()->country != nearestCountry) {
getData()->country = nearestCountry; getData()->country = nearestCountry;
@ -628,7 +627,7 @@ void Widget::Step::finish(const MTPUser &user, QImage &&photo) {
Local::writeLangPack(); Local::writeLangPack();
} }
Messenger::Instance().authSessionCreate(user); Core::App().authSessionCreate(user);
Local::writeMtpData(); Local::writeMtpData();
App::wnd()->setupMain(); App::wnd()->setupMain();

View file

@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_instance.h" #include "lang/lang_instance.h"
#include "mtproto/mtp_instance.h" #include "mtproto/mtp_instance.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "messenger.h" #include "core/application.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "auth_session.h" #include "auth_session.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
@ -514,7 +514,7 @@ void CloudManager::switchToLanguage(const Language &data) {
void CloudManager::performSwitchToCustom() { void CloudManager::performSwitchToCustom() {
auto filter = qsl("Language files (*.strings)"); auto filter = qsl("Language files (*.strings)");
auto title = qsl("Choose language .strings file"); auto title = qsl("Choose language .strings file");
FileDialog::GetOpenPath(Messenger::Instance().getFileDialogParent(), title, filter, [weak = base::make_weak(this)](const FileDialog::OpenResult &result) { FileDialog::GetOpenPath(Core::App().getFileDialogParent(), title, filter, [weak = base::make_weak(this)](const FileDialog::OpenResult &result) {
if (!weak || result.paths.isEmpty()) { if (!weak || result.paths.isEmpty()) {
return; return;
} }
@ -605,7 +605,7 @@ void CloudManager::changeIdAndReInitConnection(const Language &data) {
} }
CloudManager &CurrentCloudManager() { CloudManager &CurrentCloudManager() {
auto result = Messenger::Instance().langCloudManager(); auto result = Core::App().langCloudManager();
Assert(result != nullptr); Assert(result != nullptr);
return *result; return *result;
} }

View file

@ -7,7 +7,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/ */
#include "lang/lang_instance.h" #include "lang/lang_instance.h"
#include "messenger.h" #include "core/application.h"
#include "storage/serialize_common.h" #include "storage/serialize_common.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
@ -777,7 +777,7 @@ void Instance::resetValue(const QByteArray &key) {
} }
Instance &Current() { Instance &Current() {
return Messenger::Instance().langpack(); return Core::App().langpack();
} }
rpl::producer<QString> Viewer(LangKey key) { rpl::producer<QString> Viewer(LangKey key) {

View file

@ -10,7 +10,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_document.h" #include "data/data_document.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "application.h"
#include "storage/file_upload.h" #include "storage/file_upload.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "core/file_utilities.h" #include "core/file_utilities.h"

View file

@ -233,7 +233,7 @@ NEW LOGGING INSTANCE STARTED!!!\n\
LogsDataFields *LogsData = 0; LogsDataFields *LogsData = 0;
typedef QList<QPair<LogDataType, QString> > LogsInMemoryList; using LogsInMemoryList = QList<QPair<LogDataType, QString>>;
LogsInMemoryList *LogsInMemory = 0; LogsInMemoryList *LogsInMemory = 0;
LogsInMemoryList *DeletedLogsInMemory = SharedMemoryLocation<LogsInMemoryList, 0>(); LogsInMemoryList *DeletedLogsInMemory = SharedMemoryLocation<LogsInMemoryList, 0>();
@ -320,9 +320,9 @@ bool DebugEnabled() {
} }
void start(not_null<Core::Launcher*> launcher) { void start(not_null<Core::Launcher*> launcher) {
Assert(LogsData == 0); Assert(LogsData == nullptr);
if (!Sandbox::CheckPortableVersionDir()) { if (!launcher->checkPortableVersionFolder()) {
return; return;
} }
@ -394,12 +394,12 @@ void start(not_null<Core::Launcher*> launcher) {
QDir().mkpath(cWorkingDir() + qstr("tdata")); QDir().mkpath(cWorkingDir() + qstr("tdata"));
Sandbox::WorkingDirReady(); launcher->workingFolderReady();
CrashReports::StartCatching(); CrashReports::StartCatching(launcher);
if (!LogsData->openMain()) { if (!LogsData->openMain()) {
delete LogsData; delete LogsData;
LogsData = 0; LogsData = nullptr;
} }
LOG(("Launched version: %1, " LOG(("Launched version: %1, "

View file

@ -25,9 +25,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/special_buttons.h" #include "ui/special_buttons.h"
#include "ui/widgets/buttons.h" #include "ui/widgets/buttons.h"
#include "ui/widgets/shadow.h" #include "ui/widgets/shadow.h"
#include "window/section_memento.h"
#include "window/section_widget.h"
#include "window/window_connecting_widget.h"
#include "ui/toast/toast.h" #include "ui/toast/toast.h"
#include "ui/widgets/dropdown_menu.h" #include "ui/widgets/dropdown_menu.h"
#include "ui/image/image.h" #include "ui/image/image.h"
@ -36,6 +33,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/resize_area.h" #include "ui/resize_area.h"
#include "ui/text_options.h" #include "ui/text_options.h"
#include "ui/emoji_config.h" #include "ui/emoji_config.h"
#include "window/section_memento.h"
#include "window/section_widget.h"
#include "window/window_connecting_widget.h"
#include "chat_helpers/message_field.h" #include "chat_helpers/message_field.h"
#include "chat_helpers/stickers.h" #include "chat_helpers/stickers.h"
#include "info/info_memento.h" #include "info/info_memento.h"
@ -54,8 +54,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_cloud_manager.h" #include "lang/lang_cloud_manager.h"
#include "boxes/add_contact_box.h" #include "boxes/add_contact_box.h"
#include "storage/file_upload.h" #include "storage/file_upload.h"
#include "messenger.h"
#include "application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "inline_bots/inline_bot_layout_item.h" #include "inline_bots/inline_bot_layout_item.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
@ -84,6 +82,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/file_utilities.h" #include "core/file_utilities.h"
#include "core/update_checker.h" #include "core/update_checker.h"
#include "core/shortcuts.h" #include "core/shortcuts.h"
#include "core/application.h"
#include "calls/calls_instance.h" #include "calls/calls_instance.h"
#include "calls/calls_top_bar.h" #include "calls/calls_top_bar.h"
#include "export/export_settings.h" #include "export/export_settings.h"
@ -374,9 +373,6 @@ MainWidget::MainWidget(
, _failDifferenceTimer([=] { getDifferenceAfterFail(); }) , _failDifferenceTimer([=] { getDifferenceAfterFail(); })
, _cacheBackgroundTimer([=] { cacheBackground(); }) , _cacheBackgroundTimer([=] { cacheBackground(); })
, _viewsIncrementTimer([=] { viewsIncrement(); }) { , _viewsIncrementTimer([=] { viewsIncrement(); }) {
Messenger::Instance().mtp()->setUpdatesHandler(rpcDone(&MainWidget::updateReceived));
Messenger::Instance().mtp()->setGlobalFailHandler(rpcFail(&MainWidget::updateFail));
_controller->setDefaultFloatPlayerDelegate(floatPlayerDelegate()); _controller->setDefaultFloatPlayerDelegate(floatPlayerDelegate());
_controller->floatPlayerClosed( _controller->floatPlayerClosed(
) | rpl::start_with_next([=](FullMsgId itemId) { ) | rpl::start_with_next([=](FullMsgId itemId) {
@ -786,7 +782,7 @@ void MainWidget::clearHider(not_null<Window::HistoryHider*> instance) {
} }
void MainWidget::hiderLayer(base::unique_qptr<Window::HistoryHider> hider) { void MainWidget::hiderLayer(base::unique_qptr<Window::HistoryHider> hider) {
if (Messenger::Instance().locked()) { if (Core::App().locked()) {
return; return;
} }
@ -1044,7 +1040,7 @@ bool MainWidget::sendMessageFail(const RPCError &error) {
return true; return true;
} else if (error.type() == qstr("USER_BANNED_IN_CHANNEL")) { } else if (error.type() == qstr("USER_BANNED_IN_CHANNEL")) {
const auto link = textcmdLink( const auto link = textcmdLink(
Messenger::Instance().createInternalLinkFull(qsl("spambot")), Core::App().createInternalLinkFull(qsl("spambot")),
lang(lng_cant_more_info)); lang(lng_cant_more_info));
const auto text = lng_error_public_groups_denied(lt_more_info, link); const auto text = lng_error_public_groups_denied(lt_more_info, link);
Ui::show(Box<InformBox>(text)); Ui::show(Box<InformBox>(text));
@ -1838,7 +1834,7 @@ void MainWidget::ui_showPeerHistory(
auto animatedShow = [&] { auto animatedShow = [&] {
if (_a_show.animating() if (_a_show.animating()
|| Messenger::Instance().locked() || Core::App().locked()
|| (params.animated == anim::type::instant)) { || (params.animated == anim::type::instant)) {
return false; return false;
} }
@ -2147,7 +2143,7 @@ void MainWidget::showNewSection(
auto animatedShow = [&] { auto animatedShow = [&] {
if (_a_show.animating() if (_a_show.animating()
|| Messenger::Instance().locked() || Core::App().locked()
|| (params.animated == anim::type::instant) || (params.animated == anim::type::instant)
|| memento.instant()) { || memento.instant()) {
return false; return false;
@ -3039,11 +3035,6 @@ void MainWidget::feedMessageIds(const MTPVector<MTPUpdate> &updates) {
} }
} }
bool MainWidget::updateFail(const RPCError &e) {
crl::on_main(this, [] { Messenger::Instance().logOut(); });
return true;
}
void MainWidget::updSetState(int32 pts, int32 date, int32 qts, int32 seq) { void MainWidget::updSetState(int32 pts, int32 date, int32 qts, int32 seq) {
if (pts) { if (pts) {
_ptsWaiter.init(pts); _ptsWaiter.init(pts);
@ -3451,7 +3442,7 @@ void MainWidget::start() {
_history->start(); _history->start();
Messenger::Instance().checkStartUrl(); Core::App().checkStartUrl();
} }
bool MainWidget::started() { bool MainWidget::started() {
@ -3463,7 +3454,7 @@ void MainWidget::openPeerByName(
MsgId msgId, MsgId msgId,
const QString &startToken, const QString &startToken,
FullMsgId clickFromMessageId) { FullMsgId clickFromMessageId) {
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
if (const auto peer = session().data().peerByUsername(username)) { if (const auto peer = session().data().peerByUsername(username)) {
if (msgId == ShowAtGameShareMsgId) { if (msgId == ShowAtGameShareMsgId) {
@ -3753,9 +3744,9 @@ int32 MainWidget::dlgsWidth() const {
} }
MainWidget::~MainWidget() { MainWidget::~MainWidget() {
if (App::main() == this) _history->showHistory(0, 0); if (App::main() == this) {
_history->showHistory(0, 0);
Messenger::Instance().mtp()->clearGlobalHandlers(); }
} }
void MainWidget::updateOnline(bool gotOtherOffline) { void MainWidget::updateOnline(bool gotOtherOffline) {
@ -4398,11 +4389,11 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
case mtpc_updateDcOptions: { case mtpc_updateDcOptions: {
auto &d = update.c_updateDcOptions(); auto &d = update.c_updateDcOptions();
Messenger::Instance().dcOptions()->addFromList(d.vdc_options); Core::App().dcOptions()->addFromList(d.vdc_options);
} break; } break;
case mtpc_updateConfig: { case mtpc_updateConfig: {
Messenger::Instance().mtp()->requestConfig(); Core::App().mtp()->requestConfig();
} break; } break;
case mtpc_updateUserPhone: { case mtpc_updateUserPhone: {
@ -4463,7 +4454,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
TextUtilities::EntitiesFromMTP(d.ventities.v) TextUtilities::EntitiesFromMTP(d.ventities.v)
}; };
if (IsForceLogoutNotification(d)) { if (IsForceLogoutNotification(d)) {
Messenger::Instance().forceLogOut(text); Core::App().forceLogOut(text);
} else if (d.is_popup()) { } else if (d.is_popup()) {
Ui::show(Box<InformBox>(text)); Ui::show(Box<InformBox>(text));
} else { } else {

View file

@ -120,6 +120,7 @@ public:
void incrementSticker(DocumentData *sticker); void incrementSticker(DocumentData *sticker);
void activate(); void activate();
void updateReceived(const mtpPrime *from, const mtpPrime *end);
void createDialog(Dialogs::Key key); void createDialog(Dialogs::Key key);
void removeDialog(Dialogs::Key key); void removeDialog(Dialogs::Key key);
@ -415,9 +416,6 @@ private:
void deleteHistoryPart(DeleteHistoryRequest request, const MTPmessages_AffectedHistory &result); void deleteHistoryPart(DeleteHistoryRequest request, const MTPmessages_AffectedHistory &result);
void updateReceived(const mtpPrime *from, const mtpPrime *end);
bool updateFail(const RPCError &e);
void usernameResolveDone(QPair<MsgId, QString> msgIdAndStartToken, const MTPcontacts_ResolvedPeer &result); void usernameResolveDone(QPair<MsgId, QString> msgIdAndStartToken, const MTPcontacts_ResolvedPeer &result);
bool usernameResolveFail(QString name, const RPCError &error); bool usernameResolveFail(QString name, const RPCError &error);

View file

@ -22,9 +22,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_instance.h" #include "lang/lang_instance.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "core/shortcuts.h" #include "core/shortcuts.h"
#include "messenger.h" #include "core/sandbox.h"
#include "core/application.h"
#include "auth_session.h" #include "auth_session.h"
#include "application.h"
#include "intro/introwidget.h" #include "intro/introwidget.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
@ -66,12 +66,12 @@ void FeedLangTestingKey(int key) {
} // namespace } // namespace
MainWindow::MainWindow() { MainWindow::MainWindow() {
auto logo = Messenger::Instance().logo(); auto logo = Core::App().logo();
icon16 = logo.scaledToWidth(16, Qt::SmoothTransformation); icon16 = logo.scaledToWidth(16, Qt::SmoothTransformation);
icon32 = logo.scaledToWidth(32, Qt::SmoothTransformation); icon32 = logo.scaledToWidth(32, Qt::SmoothTransformation);
icon64 = logo.scaledToWidth(64, Qt::SmoothTransformation); icon64 = logo.scaledToWidth(64, Qt::SmoothTransformation);
auto logoNoMargin = Messenger::Instance().logoNoMargin(); auto logoNoMargin = Core::App().logoNoMargin();
iconbig16 = logoNoMargin.scaledToWidth(16, Qt::SmoothTransformation); iconbig16 = logoNoMargin.scaledToWidth(16, Qt::SmoothTransformation);
iconbig32 = logoNoMargin.scaledToWidth(32, Qt::SmoothTransformation); iconbig32 = logoNoMargin.scaledToWidth(32, Qt::SmoothTransformation);
iconbig64 = logoNoMargin.scaledToWidth(64, Qt::SmoothTransformation); iconbig64 = logoNoMargin.scaledToWidth(64, Qt::SmoothTransformation);
@ -80,7 +80,7 @@ MainWindow::MainWindow() {
setLocale(QLocale(QLocale::English, QLocale::UnitedStates)); setLocale(QLocale(QLocale::English, QLocale::UnitedStates));
subscribe(Messenger::Instance().authSessionChanged(), [this] { subscribe(Core::App().authSessionChanged(), [this] {
updateGlobalMenu(); updateGlobalMenu();
if (!AuthSession::Exists()) { if (!AuthSession::Exists()) {
_mediaPreview.destroy(); _mediaPreview.destroy();
@ -89,7 +89,7 @@ MainWindow::MainWindow() {
subscribe(Window::Theme::Background(), [this](const Window::Theme::BackgroundUpdate &data) { subscribe(Window::Theme::Background(), [this](const Window::Theme::BackgroundUpdate &data) {
themeUpdated(data); themeUpdated(data);
}); });
Messenger::Instance().lockChanges( Core::App().lockChanges(
) | rpl::start_with_next([=] { ) | rpl::start_with_next([=] {
updateGlobalMenu(); updateGlobalMenu();
}, lifetime()); }, lifetime());
@ -164,7 +164,7 @@ void MainWindow::setupPasscodeLock() {
_passcodeLock.create(bodyWidget()); _passcodeLock.create(bodyWidget());
updateControlsGeometry(); updateControlsGeometry();
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
Ui::hideSettingsAndLayer(anim::type::instant); Ui::hideSettingsAndLayer(anim::type::instant);
if (_main) { if (_main) {
_main->hide(); _main->hide();
@ -189,9 +189,9 @@ void MainWindow::clearPasscodeLock() {
_intro->showAnimated(bg, true); _intro->showAnimated(bg, true);
} else if (_main) { } else if (_main) {
_main->showAnimated(bg, true); _main->showAnimated(bg, true);
Messenger::Instance().checkStartUrl(); Core::App().checkStartUrl();
} else { } else {
Messenger::Instance().startMtp(); Core::App().startMtp();
if (AuthSession::Exists()) { if (AuthSession::Exists()) {
setupMain(); setupMain();
} else { } else {
@ -350,7 +350,7 @@ void MainWindow::ui_showBox(
destroyLayer(); destroyLayer();
} }
} }
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
} }
} }
@ -595,7 +595,7 @@ void MainWindow::onLogout() {
} }
const auto logout = [] { const auto logout = [] {
Messenger::Instance().logOut(); Core::App().logOut();
}; };
const auto callback = [=] { const auto callback = [=] {
if (AuthSession::Exists() && Auth().data().exportInProgress()) { if (AuthSession::Exists() && Auth().data().exportInProgress()) {
@ -680,7 +680,7 @@ bool MainWindow::skipTrayClick() const {
} }
void MainWindow::toggleDisplayNotifyFromTray() { void MainWindow::toggleDisplayNotifyFromTray() {
if (Messenger::Instance().locked()) { if (Core::App().locked()) {
if (!isActive()) showFromTray(); if (!isActive()) showFromTray();
Ui::show(Box<InformBox>(lang(lng_passcode_need_unblock))); Ui::show(Box<InformBox>(lang(lng_passcode_need_unblock)));
return; return;
@ -714,7 +714,7 @@ void MainWindow::toggleDisplayNotifyFromTray() {
} }
void MainWindow::closeEvent(QCloseEvent *e) { void MainWindow::closeEvent(QCloseEvent *e) {
if (Core::App().isSavingSession()) { if (Core::Sandbox::Instance().isSavingSession()) {
e->accept(); e->accept();
App::quit(); App::quit();
} else { } else {
@ -896,10 +896,10 @@ QImage MainWindow::iconWithCounter(int size, int count, style::color bg, style::
} }
void MainWindow::sendPaths() { void MainWindow::sendPaths() {
if (Messenger::Instance().locked()) { if (Core::App().locked()) {
return; return;
} }
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
Ui::hideSettingsAndLayer(anim::type::instant); Ui::hideSettingsAndLayer(anim::type::instant);
if (_main) { if (_main) {
_main->activate(); _main->activate();

View file

@ -14,7 +14,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "media/media_audio_loaders.h" #include "media/media_audio_loaders.h"
#include "media/media_audio_track.h" #include "media/media_audio_track.h"
#include "platform/platform_audio.h" #include "platform/platform_audio.h"
#include "messenger.h" #include "core/application.h"
#include "facades.h" #include "facades.h"
#include <AL/al.h> #include <AL/al.h>
@ -262,7 +262,7 @@ bool AttachToDevice() {
} }
crl::on_main([] { crl::on_main([] {
if (Messenger::InstancePointer()) { if (!App::quitting()) {
Current().reattachTracks(); Current().reattachTracks();
} }
}); });
@ -271,7 +271,7 @@ bool AttachToDevice() {
void ScheduleDetachFromDeviceSafe() { void ScheduleDetachFromDeviceSafe() {
crl::on_main([] { crl::on_main([] {
if (Messenger::InstancePointer()) { if (!App::quitting()) {
Current().scheduleDetachFromDevice(); Current().scheduleDetachFromDevice();
} }
}); });
@ -279,7 +279,7 @@ void ScheduleDetachFromDeviceSafe() {
void ScheduleDetachIfNotUsedSafe() { void ScheduleDetachIfNotUsedSafe() {
crl::on_main([] { crl::on_main([] {
if (Messenger::InstancePointer()) { if (!App::quitting()) {
Current().scheduleDetachIfNotUsed(); Current().scheduleDetachIfNotUsed();
} }
}); });
@ -287,7 +287,7 @@ void ScheduleDetachIfNotUsedSafe() {
void StopDetachIfNotUsedSafe() { void StopDetachIfNotUsedSafe() {
crl::on_main([] { crl::on_main([] {
if (Messenger::InstancePointer()) { if (!App::quitting()) {
Current().stopDetachIfNotUsed(); Current().stopDetachIfNotUsed();
} }
}); });

View file

@ -9,7 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "media/media_audio_ffmpeg_loader.h" #include "media/media_audio_ffmpeg_loader.h"
#include "media/media_audio.h" #include "media/media_audio.h"
#include "messenger.h" #include "core/application.h"
#include <AL/al.h> #include <AL/al.h>
#include <AL/alc.h> #include <AL/alc.h>
@ -339,7 +339,7 @@ void Instance::stopDetachIfNotUsed() {
} }
Instance &Current() { Instance &Current() {
return Messenger::Instance().audio(); return Core::App().audio();
} }
} // namespace Audio } // namespace Audio

View file

@ -18,7 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_file_origin.h" #include "data/data_file_origin.h"
#include "window/window_controller.h" #include "window/window_controller.h"
#include "core/shortcuts.h" #include "core/shortcuts.h"
#include "messenger.h" #include "core/application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "auth_session.h" #include "auth_session.h"
@ -74,7 +74,7 @@ Instance::Instance()
} }
}; };
subscribe( subscribe(
Messenger::Instance().authSessionChanged(), Core::App().authSessionChanged(),
handleAuthSessionChange); handleAuthSessionChange);
handleAuthSessionChange(); handleAuthSessionChange();

View file

@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "application.h" #include "core/application.h"
#include "core/file_utilities.h" #include "core/file_utilities.h"
#include "core/mime_type.h" #include "core/mime_type.h"
#include "ui/widgets/popup_menu.h" #include "ui/widgets/popup_menu.h"
@ -32,7 +32,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "window/window_peer_menu.h" #include "window/window_peer_menu.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "auth_session.h" #include "auth_session.h"
#include "messenger.h"
#include "layout.h" #include "layout.h"
#include "storage/file_download.h" #include "storage/file_download.h"
#include "calls/calls_instance.h" #include "calls/calls_instance.h"
@ -133,7 +132,7 @@ MediaView::MediaView()
_collage = nullptr; _collage = nullptr;
} }
}; };
subscribe(Messenger::Instance().authSessionChanged(), [handleAuthSessionChange] { subscribe(Core::App().authSessionChanged(), [handleAuthSessionChange] {
handleAuthSessionChange(); handleAuthSessionChange();
}); });
handleAuthSessionChange(); handleAuthSessionChange();
@ -184,7 +183,7 @@ void MediaView::moveToScreen() {
} }
return nullptr; return nullptr;
}; };
auto activeWindow = Messenger::Instance().getActiveWindow(); auto activeWindow = Core::App().getActiveWindow();
auto activeWindowScreen = widgetScreen(activeWindow); auto activeWindowScreen = widgetScreen(activeWindow);
auto myScreen = widgetScreen(this); auto myScreen = widgetScreen(this);
if (activeWindowScreen && myScreen && myScreen != activeWindowScreen) { if (activeWindowScreen && myScreen && myScreen != activeWindowScreen) {
@ -751,7 +750,7 @@ void MediaView::updateMixerVideoVolume() const {
} }
void MediaView::close() { void MediaView::close() {
Messenger::Instance().hideMediaView(); Core::App().hideMediaView();
} }
void MediaView::activateControls() { void MediaView::activateControls() {
@ -906,7 +905,7 @@ void MediaView::onSaveAs() {
})); }));
} }
activateWindow(); activateWindow();
Core::App().setActiveWindow(this); QApplication::setActiveWindow(this);
setFocus(); setFocus();
} }
@ -1777,7 +1776,7 @@ void MediaView::displayFinished() {
show(); show();
psShowOverAll(this); psShowOverAll(this);
activateWindow(); activateWindow();
Core::App().setActiveWindow(this); QApplication::setActiveWindow(this);
setFocus(); setFocus();
} }
} }

View file

@ -13,7 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/dc_options.h" #include "mtproto/dc_options.h"
#include "mtproto/connection_abstract.h" #include "mtproto/connection_abstract.h"
#include "zlib.h" #include "zlib.h"
#include "messenger.h" #include "core/application.h"
#include "core/launcher.h" #include "core/launcher.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "base/openssl_help.h" #include "base/openssl_help.h"
@ -820,10 +820,10 @@ void ConnectionPrivate::tryToSend() {
const auto langPackName = _connectionOptions->langPackName; const auto langPackName = _connectionOptions->langPackName;
const auto deviceModel = (_dcType == DcType::Cdn) const auto deviceModel = (_dcType == DcType::Cdn)
? "n/a" ? "n/a"
: Messenger::Instance().launcher()->deviceModel(); : Core::App().launcher()->deviceModel();
const auto systemVersion = (_dcType == DcType::Cdn) const auto systemVersion = (_dcType == DcType::Cdn)
? "n/a" ? "n/a"
: Messenger::Instance().launcher()->systemVersion(); : Core::App().launcher()->systemVersion();
#if defined OS_MAC_STORE || defined OS_WIN_STORE #if defined OS_MAC_STORE || defined OS_WIN_STORE
const auto appVersion = QString::fromLatin1(AppVersionStr) const auto appVersion = QString::fromLatin1(AppVersionStr)
+ " store"; + " store";
@ -1563,7 +1563,7 @@ void ConnectionPrivate::handleReceived() {
uint32 toAckSize = ackRequestData.size(); uint32 toAckSize = ackRequestData.size();
if (toAckSize) { if (toAckSize) {
DEBUG_LOG(("MTP Info: will send %1 acks, ids: %2").arg(toAckSize).arg(LogIdsVector(ackRequestData))); DEBUG_LOG(("MTP Info: will send %1 acks, ids: %2").arg(toAckSize).arg(LogIdsVector(ackRequestData)));
emit sendAnythingAsync(MTPAckSendWaiting); emit sendAnythingAsync(kAckSendWaiting);
} }
bool emitSignal = false; bool emitSignal = false;
@ -2321,10 +2321,10 @@ void ConnectionPrivate::requestsAcked(const QVector<MTPlong> &ids, bool byRespon
} }
uint32 ackedCount = wereAcked.size(); uint32 ackedCount = wereAcked.size();
if (ackedCount > MTPIdsBufferSize) { if (ackedCount > kIdsBufferSize) {
DEBUG_LOG(("Message Info: removing some old acked sent msgIds %1").arg(ackedCount - MTPIdsBufferSize)); DEBUG_LOG(("Message Info: removing some old acked sent msgIds %1").arg(ackedCount - kIdsBufferSize));
clearedBecauseTooOld.reserve(ackedCount - MTPIdsBufferSize); clearedBecauseTooOld.reserve(ackedCount - kIdsBufferSize);
while (ackedCount-- > MTPIdsBufferSize) { while (ackedCount-- > kIdsBufferSize) {
auto i = wereAcked.begin(); auto i = wereAcked.begin();
clearedBecauseTooOld.push_back(RPCCallbackClear( clearedBecauseTooOld.push_back(RPCCallbackClear(
i.value(), i.value(),

View file

@ -15,6 +15,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
namespace MTP { namespace MTP {
// How much time to wait for some more requests, when sending msg acks.
constexpr auto kAckSendWaiting = TimeMs(10000);
class Instance; class Instance;
bool IsPrimeAndGood(bytes::const_span primeBytes, int g); bool IsPrimeAndGood(bytes::const_span primeBytes, int g);

View file

@ -8,7 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/dedicated_file_loader.h" #include "mtproto/dedicated_file_loader.h"
#include "auth_session.h" #include "auth_session.h"
#include "messenger.h" #include "core/application.h"
namespace MTP { namespace MTP {
namespace { namespace {
@ -88,7 +88,7 @@ WeakInstance::WeakInstance(QPointer<MTP::Instance> instance)
_instance = nullptr; _instance = nullptr;
die(); die();
}); });
subscribe(Messenger::Instance().authSessionChanged(), [=] { subscribe(Core::App().authSessionChanged(), [=] {
if (!AuthSession::Exists()) { if (!AuthSession::Exists()) {
die(); die();
} }

View file

@ -8,7 +8,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/facade.h" #include "mtproto/facade.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "messenger.h" #include "core/application.h"
#include "core/sandbox.h"
namespace MTP { namespace MTP {
namespace internal { namespace internal {
@ -38,7 +39,9 @@ void unpause() {
} // namespace internal } // namespace internal
Instance *MainInstance() { Instance *MainInstance() {
return Messenger::Instance().mtp(); return Core::Sandbox::Instance().applicationLaunched()
? Core::App().mtp()
: nullptr;
} }
} // namespace MTP } // namespace MTP

View file

@ -152,7 +152,7 @@ inline DcId maindc() {
} }
inline int32 dcstate(ShiftedDcId shiftedDcId = 0) { inline int32 dcstate(ShiftedDcId shiftedDcId = 0) {
if (auto instance = MainInstance()) { if (const auto instance = MainInstance()) {
return instance->dcstate(shiftedDcId); return instance->dcstate(shiftedDcId);
} }
return DisconnectedState; return DisconnectedState;
@ -187,23 +187,33 @@ inline mtpRequestId send(
} }
inline void sendAnything(ShiftedDcId shiftedDcId = 0, TimeMs msCanWait = 0) { inline void sendAnything(ShiftedDcId shiftedDcId = 0, TimeMs msCanWait = 0) {
return MainInstance()->sendAnything(shiftedDcId, msCanWait); if (const auto instance = MainInstance()) {
instance->sendAnything(shiftedDcId, msCanWait);
}
} }
inline void cancel(mtpRequestId requestId) { inline void cancel(mtpRequestId requestId) {
return MainInstance()->cancel(requestId); if (const auto instance = MainInstance()) {
instance->cancel(requestId);
}
} }
inline void ping() { inline void ping() {
return MainInstance()->ping(); if (const auto instance = MainInstance()) {
instance->ping();
}
} }
inline void killSession(ShiftedDcId shiftedDcId) { inline void killSession(ShiftedDcId shiftedDcId) {
return MainInstance()->killSession(shiftedDcId); if (const auto instance = MainInstance()) {
instance->killSession(shiftedDcId);
}
} }
inline void stopSession(ShiftedDcId shiftedDcId) { inline void stopSession(ShiftedDcId shiftedDcId) {
return MainInstance()->stopSession(shiftedDcId); if (const auto instance = MainInstance()) {
instance->stopSession(shiftedDcId);
}
} }
inline int32 state(mtpRequestId requestId) { // < 0 means waiting for such count of ms inline int32 state(mtpRequestId requestId) { // < 0 means waiting for such count of ms

View file

@ -18,9 +18,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "calls/calls_instance.h" #include "calls/calls_instance.h"
#include "auth_session.h" #include "auth_session.h"
#include "application.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "messenger.h" #include "core/application.h"
#include "lang/lang_instance.h" #include "lang/lang_instance.h"
#include "lang/lang_cloud_manager.h" #include "lang/lang_cloud_manager.h"
#include "base/timer.h" #include "base/timer.h"
@ -413,7 +412,7 @@ void Instance::Private::setUserPhone(const QString &phone) {
void Instance::Private::badConfigurationError() { void Instance::Private::badConfigurationError() {
if (_mode == Mode::Normal) { if (_mode == Mode::Normal) {
Messenger::Instance().badMtprotoConfigurationError(); Core::App().badMtprotoConfigurationError();
} }
} }
@ -757,7 +756,7 @@ void Instance::Private::configLoadDone(const MTPConfig &result) {
Global::SetStickersRecentLimit(data.vstickers_recent_limit.v); Global::SetStickersRecentLimit(data.vstickers_recent_limit.v);
Global::SetStickersFavedLimit(data.vstickers_faved_limit.v); Global::SetStickersFavedLimit(data.vstickers_faved_limit.v);
Global::SetPinnedDialogsCountMax(data.vpinned_dialogs_count_max.v); Global::SetPinnedDialogsCountMax(data.vpinned_dialogs_count_max.v);
Messenger::Instance().setInternalLinkDomain(qs(data.vme_url_prefix)); Core::App().setInternalLinkDomain(qs(data.vme_url_prefix));
Global::SetChannelsReadMediaPeriod(data.vchannels_read_media_period.v); Global::SetChannelsReadMediaPeriod(data.vchannels_read_media_period.v);
Global::SetWebFileDcId(data.vwebfile_dc_id.v); Global::SetWebFileDcId(data.vwebfile_dc_id.v);
Global::SetTxtDomainString(qs(data.vdc_txt_domain_name)); Global::SetTxtDomainString(qs(data.vdc_txt_domain_name));

View file

@ -16,6 +16,20 @@ namespace MTP {
namespace internal { namespace internal {
namespace { namespace {
// How much time passed from send till we resend request or check its state.
constexpr auto kCheckResendTimeout = TimeMs(10000);
// How much time to wait for some more requests,
// when resending request or checking its state.
constexpr auto kCheckResendWaiting = TimeMs(1000);
// How much ints should message contain for us not to resend,
// but instead to check its state.
constexpr auto kResendThreshold = 1;
// Container lives 10 minutes in haveSent map.
constexpr auto kContainerLives = 600;
QString LogIds(const QVector<uint64> &ids) { QString LogIds(const QVector<uint64> &ids) {
if (!ids.size()) return "[]"; if (!ids.size()) return "[]";
auto idsStr = QString("[%1").arg(*ids.cbegin()); auto idsStr = QString("[%1").arg(*ids.cbegin());
@ -305,8 +319,8 @@ void Session::checkRequestsByTimer() {
for (auto i = haveSent.begin(), e = haveSent.end(); i != e; ++i) { for (auto i = haveSent.begin(), e = haveSent.end(); i != e; ++i) {
auto &req = i.value(); auto &req = i.value();
if (req->msDate > 0) { if (req->msDate > 0) {
if (req->msDate + MTPCheckResendTimeout < ms) { // need to resend or check state if (req->msDate + kCheckResendTimeout < ms) { // need to resend or check state
if (req.messageSize() < MTPResendThreshold) { // resend if (req.messageSize() < kResendThreshold) { // resend
resendingIds.reserve(haveSentCount); resendingIds.reserve(haveSentCount);
resendingIds.push_back(i.key()); resendingIds.push_back(i.key());
} else { } else {
@ -315,7 +329,7 @@ void Session::checkRequestsByTimer() {
stateRequestIds.push_back(i.key()); stateRequestIds.push_back(i.key());
} }
} }
} else if (unixtime() > (int32)(i.key() >> 32) + MTPContainerLives) { } else if (unixtime() > (int32)(i.key() >> 32) + kContainerLives) {
removingIds.reserve(haveSentCount); removingIds.reserve(haveSentCount);
removingIds.push_back(i.key()); removingIds.push_back(i.key());
} }
@ -330,12 +344,12 @@ void Session::checkRequestsByTimer() {
data.stateRequestMap().insert(stateRequestIds[i], true); data.stateRequestMap().insert(stateRequestIds[i], true);
} }
} }
sendAnything(MTPCheckResendWaiting); sendAnything(kCheckResendWaiting);
} }
if (!resendingIds.isEmpty()) { if (!resendingIds.isEmpty()) {
for (uint32 i = 0, l = resendingIds.size(); i < l; ++i) { for (uint32 i = 0, l = resendingIds.size(); i < l; ++i) {
DEBUG_LOG(("MTP Info: resending request %1").arg(resendingIds[i])); DEBUG_LOG(("MTP Info: resending request %1").arg(resendingIds[i]));
resend(resendingIds[i], MTPCheckResendWaiting); resend(resendingIds[i], kCheckResendWaiting);
} }
} }
if (!removingIds.isEmpty()) { if (!removingIds.isEmpty()) {

View file

@ -18,6 +18,9 @@ using AuthKeyPtr = std::shared_ptr<AuthKey>;
namespace internal { namespace internal {
// Received msgIds and wereAcked msgIds count stored.
constexpr auto kIdsBufferSize = 400;
class Dcenter; class Dcenter;
class Connection; class Connection;
@ -44,7 +47,7 @@ public:
bool registerMsgId(mtpMsgId msgId, bool needAck) { bool registerMsgId(mtpMsgId msgId, bool needAck) {
auto i = _idsNeedAck.constFind(msgId); auto i = _idsNeedAck.constFind(msgId);
if (i == _idsNeedAck.cend()) { if (i == _idsNeedAck.cend()) {
if (_idsNeedAck.size() < MTPIdsBufferSize || msgId > min()) { if (_idsNeedAck.size() < kIdsBufferSize || msgId > min()) {
_idsNeedAck.insert(msgId, needAck); _idsNeedAck.insert(msgId, needAck);
return true; return true;
} }
@ -66,7 +69,7 @@ public:
void shrink() { void shrink() {
auto size = _idsNeedAck.size(); auto size = _idsNeedAck.size();
while (size-- > MTPIdsBufferSize) { while (size-- > kIdsBufferSize) {
_idsNeedAck.erase(_idsNeedAck.begin()); _idsNeedAck.erase(_idsNeedAck.begin());
} }
} }

View file

@ -19,7 +19,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "application.h"
#include "storage/file_upload.h" #include "storage/file_upload.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "media/media_audio.h" #include "media/media_audio.h"

View file

@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include <private/qguiapplication_p.h> #include <private/qguiapplication_p.h>
#include "platform/linux/linux_libs.h" #include "platform/linux/linux_libs.h"
#include "platform/linux/linux_gdk_helper.h" #include "platform/linux/linux_gdk_helper.h"
#include "messenger.h" #include "core/application.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"

View file

@ -13,8 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "platform/platform_notifications_manager.h" #include "platform/platform_notifications_manager.h"
#include "history/history.h" #include "history/history.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h" #include "core/application.h"
#include "application.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
@ -71,14 +70,14 @@ gboolean _trayIconResized(GtkStatusIcon *status_icon, gint size, gpointer popup_
#endif // !TDESKTOP_DISABLE_GTK_INTEGRATION #endif // !TDESKTOP_DISABLE_GTK_INTEGRATION
QImage _trayIconImageGen() { QImage _trayIconImageGen() {
const auto counter = Messenger::Instance().unreadBadge(); const auto counter = Core::App().unreadBadge();
const auto muted = Messenger::Instance().unreadBadgeMuted(); const auto muted = Core::App().unreadBadgeMuted();
const auto counterSlice = (counter >= 1000) const auto counterSlice = (counter >= 1000)
? (1000 + (counter % 100)) ? (1000 + (counter % 100))
: counter; : counter;
if (_trayIconImage.isNull() || _trayIconImage.width() != _trayIconSize || muted != _trayIconMuted || counterSlice != _trayIconCount) { if (_trayIconImage.isNull() || _trayIconImage.width() != _trayIconSize || muted != _trayIconMuted || counterSlice != _trayIconCount) {
if (_trayIconImageBack.isNull() || _trayIconImageBack.width() != _trayIconSize) { if (_trayIconImageBack.isNull() || _trayIconImageBack.width() != _trayIconSize) {
_trayIconImageBack = Messenger::Instance().logo().scaled(_trayIconSize, _trayIconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); _trayIconImageBack = Core::App().logo().scaled(_trayIconSize, _trayIconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
_trayIconImageBack = _trayIconImageBack.convertToFormat(QImage::Format_ARGB32); _trayIconImageBack = _trayIconImageBack.convertToFormat(QImage::Format_ARGB32);
int w = _trayIconImageBack.width(), h = _trayIconImageBack.height(), perline = _trayIconImageBack.bytesPerLine(); int w = _trayIconImageBack.width(), h = _trayIconImageBack.height(), perline = _trayIconImageBack.bytesPerLine();
uchar *bytes = _trayIconImageBack.bits(); uchar *bytes = _trayIconImageBack.bits();
@ -114,8 +113,8 @@ QImage _trayIconImageGen() {
} }
QString _trayIconImageFile() { QString _trayIconImageFile() {
const auto counter = Messenger::Instance().unreadBadge(); const auto counter = Core::App().unreadBadge();
const auto muted = Messenger::Instance().unreadBadgeMuted(); const auto muted = Core::App().unreadBadgeMuted();
const auto counterSlice = (counter >= 1000) ? (1000 + (counter % 100)) : counter; const auto counterSlice = (counter >= 1000) ? (1000 + (counter % 100)) : counter;
QString name = cWorkingDir() + qsl("tdata/ticons/icon%1_%2_%3.png").arg(muted ? "mute" : "").arg(_trayIconSize).arg(counterSlice); QString name = cWorkingDir() + qsl("tdata/ticons/icon%1_%2_%3.png").arg(muted ? "mute" : "").arg(_trayIconSize).arg(counterSlice);
@ -335,7 +334,7 @@ void MainWindow::unreadCounterChangedHook() {
void MainWindow::updateIconCounters() { void MainWindow::updateIconCounters() {
updateWindowIcon(); updateWindowIcon();
const auto counter = Messenger::Instance().unreadBadge(); const auto counter = Core::App().unreadBadge();
#if !defined(TDESKTOP_DISABLE_GTK_INTEGRATION) && !defined(TDESKTOP_DISABLE_UNITY_INTEGRATION) #if !defined(TDESKTOP_DISABLE_GTK_INTEGRATION) && !defined(TDESKTOP_DISABLE_UNITY_INTEGRATION)
if (_psUnityLauncherEntry) { if (_psUnityLauncherEntry) {
@ -374,8 +373,8 @@ void MainWindow::updateIconCounters() {
QByteArray path = QFile::encodeName(iconFile.absoluteFilePath()); QByteArray path = QFile::encodeName(iconFile.absoluteFilePath());
icon = QIcon(path.constData()); icon = QIcon(path.constData());
} else { } else {
const auto counter = Messenger::Instance().unreadBadge(); const auto counter = Core::App().unreadBadge();
const auto muted = Messenger::Instance().unreadBadgeMuted(); const auto muted = Core::App().unreadBadgeMuted();
auto &bg = (muted ? st::trayCounterBgMute : st::trayCounterBg); auto &bg = (muted ? st::trayCounterBgMute : st::trayCounterBg);
auto &fg = st::trayCounterFg; auto &fg = st::trayCounterFg;

View file

@ -9,7 +9,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "platform/linux/linux_libs.h" #include "platform/linux/linux_libs.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "platform/linux/linux_desktop_environment.h" #include "platform/linux/linux_desktop_environment.h"
@ -91,11 +90,11 @@ void FallbackFontConfig() {
namespace Platform { namespace Platform {
bool IsApplicationActive() { bool IsApplicationActive() {
return static_cast<QApplication*>(QApplication::instance())->activeWindow() != nullptr; return QApplication::activeWindow() != nullptr;
} }
void SetApplicationIcon(const QIcon &icon) { void SetApplicationIcon(const QIcon &icon) {
qApp->setWindowIcon(icon); QApplication::setWindowIcon(icon);
} }
QString CurrentExecutablePath(int argc, char *argv[]) { QString CurrentExecutablePath(int argc, char *argv[]) {

View file

@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "styles/style_window.h" #include "styles/style_window.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "messenger.h" #include "core/application.h"
#include "auth_session.h" #include "auth_session.h"
#include "history/history.h" #include "history/history.h"
#include "history/history_widget.h" #include "history/history_widget.h"
@ -521,8 +521,8 @@ void MainWindow::unreadCounterChangedHook() {
} }
void MainWindow::updateIconCounters() { void MainWindow::updateIconCounters() {
const auto counter = Messenger::Instance().unreadBadge(); const auto counter = Core::App().unreadBadge();
const auto muted = Messenger::Instance().unreadBadgeMuted(); const auto muted = Core::App().unreadBadgeMuted();
const auto string = !counter const auto string = !counter
? QString() ? QString()
@ -699,7 +699,7 @@ void MainWindow::updateGlobalMenuHook() {
} }
App::wnd()->updateIsActive(0); App::wnd()->updateIsActive(0);
const auto logged = AuthSession::Exists(); const auto logged = AuthSession::Exists();
const auto locked = Messenger::Instance().locked(); const auto locked = Core::App().locked();
const auto inactive = !logged || locked; const auto inactive = !logged || locked;
const auto support = logged && Auth().supportMode(); const auto support = logged && Auth().supportMode();
_forceDisabled(psLogout, !logged && !locked); _forceDisabled(psLogout, !logged && !locked);

View file

@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "platform/mac/specific_mac.h" #include "platform/mac/specific_mac.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "application.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "history/history_widget.h" #include "history/history_widget.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"

View file

@ -9,15 +9,16 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "messenger.h" #include "core/application.h"
#include "core/sandbox.h"
#include "core/crash_reports.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "media/player/media_player_instance.h" #include "media/player/media_player_instance.h"
#include "media/media_audio.h" #include "media/media_audio.h"
#include "platform/mac/mac_utilities.h" #include "platform/mac/mac_utilities.h"
#include "styles/style_window.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "base/timer.h" #include "base/timer.h"
#include "core/crash_reports.h" #include "styles/style_window.h"
#include <Cocoa/Cocoa.h> #include <Cocoa/Cocoa.h>
#include <CoreFoundation/CFURL.h> #include <CoreFoundation/CFURL.h>
@ -141,9 +142,9 @@ ApplicationDelegate *_sharedDelegate = nil;
- (void) applicationDidBecomeActive:(NSNotification *)aNotification { - (void) applicationDidBecomeActive:(NSNotification *)aNotification {
ApplicationIsActive = true; ApplicationIsActive = true;
if (auto messenger = Messenger::InstancePointer()) { if (Core::Sandbox::Instance().applicationLaunched()) {
if (!_ignoreActivation) { if (!_ignoreActivation) {
messenger->handleAppActivated(); Core::App().handleAppActivated();
if (auto window = App::wnd()) { if (auto window = App::wnd()) {
if (window->isHidden()) { if (window->isHidden()) {
window->showFromTray(); window->showFromTray();
@ -158,8 +159,8 @@ ApplicationDelegate *_sharedDelegate = nil;
} }
- (void) receiveWakeNote:(NSNotification*)aNotification { - (void) receiveWakeNote:(NSNotification*)aNotification {
if (auto messenger = Messenger::InstancePointer()) { if (Core::Sandbox::Instance().applicationLaunched()) {
messenger->checkLocalTime(); Core::App().checkLocalTime();
} }
LOG(("Audio Info: -receiveWakeNote: received, scheduling detach from audio device")); LOG(("Audio Info: -receiveWakeNote: received, scheduling detach from audio device"));

View file

@ -11,7 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "platform/win/windows_dlls.h" #include "platform/win/windows_dlls.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "messenger.h" #include "core/application.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"
#include <Shlwapi.h> #include <Shlwapi.h>

View file

@ -12,8 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "platform/win/windows_dlls.h" #include "platform/win/windows_dlls.h"
#include "window/notifications_manager.h" #include "window/notifications_manager.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h" #include "core/application.h"
#include "application.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "ui/widgets/popup_menu.h" #include "ui/widgets/popup_menu.h"
@ -665,7 +664,7 @@ void MainWindow::psSetupTrayIcon() {
if (!trayIcon) { if (!trayIcon) {
trayIcon = new QSystemTrayIcon(this); trayIcon = new QSystemTrayIcon(this);
auto icon = QIcon(App::pixmapFromImageInPlace(Messenger::Instance().logoNoMargin())); auto icon = QIcon(App::pixmapFromImageInPlace(Core::App().logoNoMargin()));
trayIcon->setIcon(icon); trayIcon->setIcon(icon);
trayIcon->setToolTip(str_const_toString(AppName)); trayIcon->setToolTip(str_const_toString(AppName));
@ -727,8 +726,8 @@ void MainWindow::unreadCounterChangedHook() {
} }
void MainWindow::updateIconCounters() { void MainWindow::updateIconCounters() {
const auto counter = Messenger::Instance().unreadBadge(); const auto counter = Core::App().unreadBadge();
const auto muted = Messenger::Instance().unreadBadgeMuted(); const auto muted = Core::App().unreadBadgeMuted();
auto iconSizeSmall = QSize(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON)); auto iconSizeSmall = QSize(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
auto iconSizeBig = QSize(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON)); auto iconSizeBig = QSize(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
@ -800,7 +799,7 @@ void MainWindow::psFirstShow() {
if (cStartInTray() if (cStartInTray()
|| (cLaunchMode() == LaunchModeAutoStart || (cLaunchMode() == LaunchModeAutoStart
&& cStartMinimized() && cStartMinimized()
&& !Messenger::Instance().passcodeLocked())) { && !Core::App().passcodeLocked())) {
DEBUG_LOG(("Window Pos: First show, setting minimized after.")); DEBUG_LOG(("Window Pos: First show, setting minimized after."));
setWindowState(Qt::WindowMinimized); setWindowState(Qt::WindowMinimized);
if (Global::WorkMode().value() == dbiwmTrayOnly if (Global::WorkMode().value() == dbiwmTrayOnly

View file

@ -329,11 +329,11 @@ QString SystemCountry() {
} }
bool IsApplicationActive() { bool IsApplicationActive() {
return static_cast<QApplication*>(QApplication::instance())->activeWindow() != nullptr; return QApplication::activeWindow() != nullptr;
} }
void SetApplicationIcon(const QIcon &icon) { void SetApplicationIcon(const QIcon &icon) {
qApp->setWindowIcon(icon); QApplication::setWindowIcon(icon);
} }
QString CurrentExecutablePath(int argc, char *argv[]) { QString CurrentExecutablePath(int argc, char *argv[]) {

View file

@ -21,6 +21,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "core/update_checker.h" #include "core/update_checker.h"
#include "core/application.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "auth_session.h" #include "auth_session.h"
@ -174,7 +175,7 @@ void SetupUpdate(not_null<Ui::VerticalLayout*> container) {
return (toggled != cInstallBetaVersion()); return (toggled != cInstallBetaVersion());
}) | rpl::start_with_next([=](bool toggled) { }) | rpl::start_with_next([=](bool toggled) {
cSetInstallBetaVersion(toggled); cSetInstallBetaVersion(toggled);
Sandbox::WriteInstallBetaVersionsSetting(); Core::App().writeInstallBetaVersionsSetting();
Core::UpdateChecker checker; Core::UpdateChecker checker;
checker.stop(); checker.stop();

View file

@ -15,7 +15,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "lang/lang_cloud_manager.h" #include "lang/lang_cloud_manager.h"
#include "lang/lang_instance.h" #include "lang/lang_instance.h"
#include "messenger.h" #include "core/application.h"
#include "mtproto/mtp_instance.h" #include "mtproto/mtp_instance.h"
#include "mtproto/dc_options.h" #include "mtproto/dc_options.h"
#include "core/file_utilities.h" #include "core/file_utilities.h"
@ -34,7 +34,7 @@ auto GenerateCodes() {
: qsl("Do you want to enable DEBUG logs?\n\n" : qsl("Do you want to enable DEBUG logs?\n\n"
"All network events will be logged."); "All network events will be logged.");
Ui::show(Box<ConfirmBox>(text, [] { Ui::show(Box<ConfirmBox>(text, [] {
Messenger::Instance().switchDebugMode(); Core::App().switchDebugMode();
})); }));
}); });
codes.emplace(qsl("viewlogs"), [] { codes.emplace(qsl("viewlogs"), [] {
@ -43,7 +43,7 @@ auto GenerateCodes() {
codes.emplace(qsl("testmode"), [] { codes.emplace(qsl("testmode"), [] {
auto text = cTestMode() ? qsl("Do you want to disable TEST mode?") : qsl("Do you want to enable TEST mode?\n\nYou will be switched to test cloud."); auto text = cTestMode() ? qsl("Do you want to disable TEST mode?") : qsl("Do you want to enable TEST mode?\n\nYou will be switched to test cloud.");
Ui::show(Box<ConfirmBox>(text, [] { Ui::show(Box<ConfirmBox>(text, [] {
Messenger::Instance().switchTestMode(); Core::App().switchTestMode();
})); }));
}); });
if (!Core::UpdaterDisabled()) { if (!Core::UpdaterDisabled()) {
@ -71,7 +71,7 @@ auto GenerateCodes() {
codes.emplace(qsl("workmode"), [] { codes.emplace(qsl("workmode"), [] {
auto text = Global::DialogsModeEnabled() ? qsl("Disable work mode?") : qsl("Enable work mode?"); auto text = Global::DialogsModeEnabled() ? qsl("Disable work mode?") : qsl("Enable work mode?");
Ui::show(Box<ConfirmBox>(text, [] { Ui::show(Box<ConfirmBox>(text, [] {
Messenger::Instance().switchWorkMode(); Core::App().switchWorkMode();
})); }));
}); });
codes.emplace(qsl("moderate"), [] { codes.emplace(qsl("moderate"), [] {
@ -88,7 +88,7 @@ auto GenerateCodes() {
} }
}); });
codes.emplace(qsl("loadcolors"), [] { codes.emplace(qsl("loadcolors"), [] {
FileDialog::GetOpenPath(Messenger::Instance().getFileDialogParent(), "Open palette file", "Palette (*.tdesktop-palette)", [](const FileDialog::OpenResult &result) { FileDialog::GetOpenPath(Core::App().getFileDialogParent(), "Open palette file", "Palette (*.tdesktop-palette)", [](const FileDialog::OpenResult &result) {
if (!result.paths.isEmpty()) { if (!result.paths.isEmpty()) {
Window::Theme::Apply(result.paths.front()); Window::Theme::Apply(result.paths.front());
} }
@ -106,9 +106,9 @@ auto GenerateCodes() {
})); }));
}); });
codes.emplace(qsl("endpoints"), [] { codes.emplace(qsl("endpoints"), [] {
FileDialog::GetOpenPath(Messenger::Instance().getFileDialogParent(), "Open DC endpoints", "DC Endpoints (*.tdesktop-endpoints)", [](const FileDialog::OpenResult &result) { FileDialog::GetOpenPath(Core::App().getFileDialogParent(), "Open DC endpoints", "DC Endpoints (*.tdesktop-endpoints)", [](const FileDialog::OpenResult &result) {
if (!result.paths.isEmpty()) { if (!result.paths.isEmpty()) {
if (!Messenger::Instance().mtp()->dcOptions()->loadFromFile(result.paths.front())) { if (!Core::App().mtp()->dcOptions()->loadFromFile(result.paths.front())) {
Ui::show(Box<InformBox>("Could not load endpoints :( Errors in 'log.txt'.")); Ui::show(Box<InformBox>("Could not load endpoints :( Errors in 'log.txt'."));
} }
} }
@ -137,7 +137,7 @@ auto GenerateCodes() {
return; return;
} }
FileDialog::GetOpenPath(Messenger::Instance().getFileDialogParent(), "Open audio file", audioFilters, [key](const FileDialog::OpenResult &result) { FileDialog::GetOpenPath(Core::App().getFileDialogParent(), "Open audio file", audioFilters, [key](const FileDialog::OpenResult &result) {
if (AuthSession::Exists() && !result.paths.isEmpty()) { if (AuthSession::Exists() && !result.paths.isEmpty()) {
auto track = Media::Audio::Current().createTrack(); auto track = Media::Audio::Current().createTrack();
track->fillFromFile(result.paths.front()); track->fillFromFile(result.paths.front());

View file

@ -19,7 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "window/notifications_manager.h" #include "window/notifications_manager.h"
#include "platform/platform_notifications_manager.h" #include "platform/platform_notifications_manager.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h" #include "core/application.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "styles/style_settings.h" #include "styles/style_settings.h"
@ -239,7 +239,7 @@ void NotificationsCount::prepareNotificationSampleSmall() {
void NotificationsCount::prepareNotificationSampleUserpic() { void NotificationsCount::prepareNotificationSampleUserpic() {
if (_notificationSampleUserpic.isNull()) { if (_notificationSampleUserpic.isNull()) {
_notificationSampleUserpic = App::pixmapFromImageInPlace( _notificationSampleUserpic = App::pixmapFromImageInPlace(
Messenger::Instance().logoNoMargin().scaled( Core::App().logoNoMargin().scaled(
st::notifyPhotoSize * cIntRetinaFactor(), st::notifyPhotoSize * cIntRetinaFactor(),
st::notifyPhotoSize * cIntRetinaFactor(), st::notifyPhotoSize * cIntRetinaFactor(),
Qt::IgnoreAspectRatio, Qt::IgnoreAspectRatio,

View file

@ -463,8 +463,8 @@ void SetupCloudPassword(not_null<Ui::VerticalLayout*> container) {
} }
}; };
QObject::connect( QObject::connect(
qApp, static_cast<QGuiApplication*>(QCoreApplication::instance()),
&QApplication::applicationStateChanged, &QGuiApplication::applicationStateChanged,
label, label,
reloadOnActivation); reloadOnActivation);

View file

@ -11,9 +11,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_session.h" #include "data/data_session.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "messenger.h" #include "core/application.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "platform/platform_file_utilities.h" #include "platform/platform_file_utilities.h"
#include "mtproto/connection.h" // for MTP::kAckSendWaiting
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"
@ -21,8 +22,15 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "base/openssl_help.h" #include "base/openssl_help.h"
namespace Storage { namespace Storage {
namespace {
Downloader::Downloader() { // How much time without download causes additional session kill.
constexpr auto kKillSessionTimeout = TimeMs(5000);
} // namespace
Downloader::Downloader()
: _killDownloadSessionsTimer([=] { killDownloadSessions(); }) {
} }
void Downloader::clearPriorities() { void Downloader::clearPriorities() {
@ -38,9 +46,49 @@ void Downloader::requestedAmountIncrement(MTP::DcId dcId, int index, int amount)
} }
it->second[index] += amount; it->second[index] += amount;
if (it->second[index]) { if (it->second[index]) {
Messenger::Instance().killDownloadSessionsStop(dcId); killDownloadSessionsStop(dcId);
} else { } else {
Messenger::Instance().killDownloadSessionsStart(dcId); killDownloadSessionsStart(dcId);
}
}
void Downloader::killDownloadSessionsStart(MTP::DcId dcId) {
if (!_killDownloadSessionTimes.contains(dcId)) {
_killDownloadSessionTimes.emplace(
dcId,
getms() + MTP::kAckSendWaiting + kKillSessionTimeout);
}
if (!_killDownloadSessionsTimer.isActive()) {
_killDownloadSessionsTimer.callOnce(
MTP::kAckSendWaiting + kKillSessionTimeout + 5);
}
}
void Downloader::killDownloadSessionsStop(MTP::DcId dcId) {
_killDownloadSessionTimes.erase(dcId);
if (_killDownloadSessionTimes.empty()
&& _killDownloadSessionsTimer.isActive()) {
_killDownloadSessionsTimer.cancel();
}
}
void Downloader::killDownloadSessions() {
auto ms = getms(), left = MTP::kAckSendWaiting + kKillSessionTimeout;
for (auto i = _killDownloadSessionTimes.begin(); i != _killDownloadSessionTimes.end(); ) {
if (i->second <= ms) {
for (int j = 0; j < MTP::kDownloadSessionsCount; ++j) {
MTP::stopSession(MTP::downloadDcId(i->first, j));
}
i = _killDownloadSessionTimes.erase(i);
} else {
if (i->second - ms < left) {
left = i->second - ms;
}
++i;
}
}
if (!_killDownloadSessionTimes.empty()) {
_killDownloadSessionsTimer.callOnce(left);
} }
} }
@ -57,7 +105,9 @@ int Downloader::chooseDcIndexForRequest(MTP::DcId dcId) const {
return result; return result;
} }
Downloader::~Downloader() = default; Downloader::~Downloader() {
killDownloadSessions();
}
} // namespace Storage } // namespace Storage

View file

@ -8,8 +8,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#pragma once #pragma once
#include "base/observer.h" #include "base/observer.h"
#include "data/data_file_origin.h" #include "base/timer.h"
#include "base/binary_guard.h" #include "base/binary_guard.h"
#include "data/data_file_origin.h"
namespace Storage { namespace Storage {
namespace Cache { namespace Cache {
@ -42,12 +43,19 @@ public:
~Downloader(); ~Downloader();
private: private:
void killDownloadSessionsStart(MTP::DcId dcId);
void killDownloadSessionsStop(MTP::DcId dcId);
void killDownloadSessions();
base::Observable<void> _taskFinishedObservable; base::Observable<void> _taskFinishedObservable;
int _priority = 1; int _priority = 1;
using RequestedInDc = std::array<int64, MTP::kDownloadSessionsCount>; using RequestedInDc = std::array<int64, MTP::kDownloadSessionsCount>;
std::map<MTP::DcId, RequestedInDc> _requestedBytesAmount; std::map<MTP::DcId, RequestedInDc> _requestedBytesAmount;
base::flat_map<MTP::DcId, TimeMs> _killDownloadSessionTimes;
base::Timer _killDownloadSessionsTimer;
}; };
} // namespace Storage } // namespace Storage

View file

@ -9,6 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/localimageloader.h" #include "storage/localimageloader.h"
#include "storage/file_download.h" #include "storage/file_download.h"
#include "mtproto/connection.h" // for MTP::kAckSendWaiting
#include "data/data_document.h" #include "data/data_document.h"
#include "data/data_photo.h" #include "data/data_photo.h"
#include "data/data_session.h" #include "data/data_session.h"
@ -40,6 +41,9 @@ constexpr auto kDocumentUploadPartSize4 = 512 * 1024;
// One part each half second, if not uploaded faster. // One part each half second, if not uploaded faster.
constexpr auto kUploadRequestInterval = TimeMs(500); constexpr auto kUploadRequestInterval = TimeMs(500);
// How much time without upload causes additional session kill.
constexpr auto kKillSessionTimeout = TimeMs(5000);
} // namespace } // namespace
struct Uploader::File { struct Uploader::File {
@ -254,7 +258,8 @@ void Uploader::sendNext() {
bool stopping = stopSessionsTimer.isActive(); bool stopping = stopSessionsTimer.isActive();
if (queue.empty()) { if (queue.empty()) {
if (!stopping) { if (!stopping) {
stopSessionsTimer.start(MTPAckSendWaiting + MTPKillFileSessionTimeout); stopSessionsTimer.start(
MTP::kAckSendWaiting + kKillSessionTimeout);
} }
return; return;
} }

View file

@ -28,8 +28,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_cloud_manager.h" #include "lang/lang_cloud_manager.h"
#include "media/media_audio.h" #include "media/media_audio.h"
#include "mtproto/dc_options.h" #include "mtproto/dc_options.h"
#include "messenger.h" #include "core/application.h"
#include "application.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "auth_session.h" #include "auth_session.h"
#include "window/window_controller.h" #include "window/window_controller.h"
@ -48,6 +47,7 @@ constexpr auto kThemeFileSizeLimit = 5 * 1024 * 1024;
constexpr auto kFileLoaderQueueStopTimeout = TimeMs(5000); constexpr auto kFileLoaderQueueStopTimeout = TimeMs(5000);
constexpr auto kDefaultStickerInstallDate = TimeId(1); constexpr auto kDefaultStickerInstallDate = TimeId(1);
constexpr auto kProxyTypeShift = 1024; constexpr auto kProxyTypeShift = 1024;
constexpr auto kWriteMapTimeout = TimeMs(1000);
constexpr auto kSinglePeerTypeUser = qint32(1); constexpr auto kSinglePeerTypeUser = qint32(1);
constexpr auto kSinglePeerTypeChat = qint32(2); constexpr auto kSinglePeerTypeChat = qint32(2);
@ -881,7 +881,7 @@ struct ReadSettingsContext {
}; };
void applyReadContext(ReadSettingsContext &&context) { void applyReadContext(ReadSettingsContext &&context) {
Messenger::Instance().dcOptions()->addFromOther(std::move(context.dcOptions)); Core::App().dcOptions()->addFromOther(std::move(context.dcOptions));
if (context.legacyLanguageId != Lang::kLegacyLanguageNone) { if (context.legacyLanguageId != Lang::kLegacyLanguageNone) {
Lang::Current().fillFromLegacy(context.legacyLanguageId, context.legacyLanguageFile); Lang::Current().fillFromLegacy(context.legacyLanguageId, context.legacyLanguageFile);
writeLangPack(); writeLangPack();
@ -1011,8 +1011,8 @@ bool _readSetting(quint32 blockId, QDataStream &stream, int version, ReadSetting
if (!_checkStreamStatus(stream)) return false; if (!_checkStreamStatus(stream)) return false;
DEBUG_LOG(("MTP Info: user found, dc %1, uid %2").arg(dcId).arg(userId)); DEBUG_LOG(("MTP Info: user found, dc %1, uid %2").arg(dcId).arg(userId));
Messenger::Instance().setMtpMainDcId(dcId); Core::App().setMtpMainDcId(dcId);
Messenger::Instance().setAuthSessionUserId(userId); Core::App().setAuthSessionUserId(userId);
} break; } break;
case dbiKey: { case dbiKey: {
@ -1021,7 +1021,7 @@ bool _readSetting(quint32 blockId, QDataStream &stream, int version, ReadSetting
auto key = Serialize::read<MTP::AuthKey::Data>(stream); auto key = Serialize::read<MTP::AuthKey::Data>(stream);
if (!_checkStreamStatus(stream)) return false; if (!_checkStreamStatus(stream)) return false;
Messenger::Instance().setMtpKey(dcId, key); Core::App().setMtpKey(dcId, key);
} break; } break;
case dbiMtpAuthorization: { case dbiMtpAuthorization: {
@ -1029,7 +1029,7 @@ bool _readSetting(quint32 blockId, QDataStream &stream, int version, ReadSetting
stream >> serialized; stream >> serialized;
if (!_checkStreamStatus(stream)) return false; if (!_checkStreamStatus(stream)) return false;
Messenger::Instance().setMtpAuthorization(serialized); Core::App().setMtpAuthorization(serialized);
} break; } break;
case dbiAutoStart: { case dbiAutoStart: {
@ -2045,7 +2045,7 @@ void _writeUserSettings() {
} }
auto userDataInstance = StoredAuthSessionCache auto userDataInstance = StoredAuthSessionCache
? StoredAuthSessionCache.get() ? StoredAuthSessionCache.get()
: Messenger::Instance().getAuthSessionSettings(); : Core::App().getAuthSessionSettings();
auto userData = userDataInstance auto userData = userDataInstance
? userDataInstance->serialize() ? userDataInstance->serialize()
: QByteArray(); : QByteArray();
@ -2168,7 +2168,7 @@ void _writeMtpData() {
return; return;
} }
auto mtpAuthorizationSerialized = Messenger::Instance().serializeMtpAuthorization(); auto mtpAuthorizationSerialized = Core::App().serializeMtpAuthorization();
quint32 size = sizeof(quint32) + Serialize::bytearraySize(mtpAuthorizationSerialized); quint32 size = sizeof(quint32) + Serialize::bytearraySize(mtpAuthorizationSerialized);
@ -2402,7 +2402,7 @@ ReadMapState _readMap(const QByteArray &pass) {
_readMtpData(); _readMtpData();
DEBUG_LOG(("selfSerialized set: %1").arg(selfSerialized.size())); DEBUG_LOG(("selfSerialized set: %1").arg(selfSerialized.size()));
Messenger::Instance().setAuthSessionFromStorage( Core::App().setAuthSessionFromStorage(
std::move(StoredAuthSessionCache), std::move(StoredAuthSessionCache),
std::move(selfSerialized), std::move(selfSerialized),
_oldMapVersion); _oldMapVersion);
@ -2640,7 +2640,7 @@ void writeSettings() {
} }
settings.writeData(_settingsSalt); settings.writeData(_settingsSalt);
auto dcOptionsSerialized = Messenger::Instance().dcOptions()->serialize(); auto dcOptionsSerialized = Core::App().dcOptions()->serialize();
quint32 size = 12 * (sizeof(quint32) + sizeof(qint32)); quint32 size = 12 * (sizeof(quint32) + sizeof(qint32));
size += sizeof(quint32) + Serialize::bytearraySize(dcOptionsSerialized); size += sizeof(quint32) + Serialize::bytearraySize(dcOptionsSerialized);
@ -5045,7 +5045,7 @@ Manager::Manager() {
void Manager::writeMap(bool fast) { void Manager::writeMap(bool fast) {
if (!_mapWriteTimer.isActive() || fast) { if (!_mapWriteTimer.isActive() || fast) {
_mapWriteTimer.start(fast ? 1 : WriteMapTimeout); _mapWriteTimer.start(fast ? 1 : kWriteMapTimeout);
} else if (_mapWriteTimer.remainingTime() <= 0) { } else if (_mapWriteTimer.remainingTime() <= 0) {
mapWriteTimeout(); mapWriteTimeout();
} }
@ -5057,7 +5057,7 @@ void Manager::writingMap() {
void Manager::writeLocations(bool fast) { void Manager::writeLocations(bool fast) {
if (!_locationsWriteTimer.isActive() || fast) { if (!_locationsWriteTimer.isActive() || fast) {
_locationsWriteTimer.start(fast ? 1 : WriteMapTimeout); _locationsWriteTimer.start(fast ? 1 : kWriteMapTimeout);
} else if (_locationsWriteTimer.remainingTime() <= 0) { } else if (_locationsWriteTimer.remainingTime() <= 0) {
locationsWriteTimeout(); locationsWriteTimeout();
} }

View file

@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "window/window_controller.h" #include "window/window_controller.h"
#include "storage/storage_media_prepare.h" #include "storage/storage_media_prepare.h"
#include "storage/localimageloader.h" #include "storage/localimageloader.h"
#include "core/sandbox.h"
#include "auth_session.h" #include "auth_session.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "apiwrap.h" #include "apiwrap.h"
@ -137,7 +138,7 @@ QString FormatDateTime(TimeId value) {
} }
uint32 OccupationTag() { uint32 OccupationTag() {
return uint32(Sandbox::UserTag() & 0xFFFFFFFFU); return uint32(Core::Sandbox::Instance().installationTag() & 0xFFFFFFFF);
} }
QString NormalizeName(QString name) { QString NormalizeName(QString name) {
@ -280,7 +281,9 @@ Helper::Helper(not_null<AuthSession*> session)
}); });
}).fail([=](const RPCError &error) { }).fail([=](const RPCError &error) {
setSupportName( setSupportName(
qsl("[rand^") + QString::number(Sandbox::UserTag()) + ']'); qsl("[rand^")
+ QString::number(Core::Sandbox::Instance().installationTag())
+ ']');
}).send(); }).send();
} }

Some files were not shown because too many files have changed in this diff Show more