diff --git a/Telegram/SourceFiles/apiwrap.cpp b/Telegram/SourceFiles/apiwrap.cpp index 907b59aa3..588eab821 100644 --- a/Telegram/SourceFiles/apiwrap.cpp +++ b/Telegram/SourceFiles/apiwrap.cpp @@ -22,12 +22,11 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_user.h" #include "dialogs/dialogs_key.h" #include "core/core_cloud_password.h" +#include "core/application.h" #include "base/openssl_help.h" #include "observer_peer.h" #include "lang/lang_keys.h" -#include "application.h" #include "mainwindow.h" -#include "messenger.h" #include "mainwidget.h" #include "boxes/add_contact_box.h" #include "history/history.h" @@ -329,7 +328,7 @@ void ApiWrap::requestTermsUpdate() { const auto &data = result.c_help_termsOfServiceUpdate(); const auto &terms = data.vterms_of_service; const auto &fields = terms.c_help_termsOfService(); - Messenger::Instance().lockByTerms( + Core::App().lockByTerms( Window::TermsLock::FromMTP(fields)); requestNext(data); } break; @@ -478,7 +477,7 @@ void ApiWrap::sendMessageFail(const RPCError &error) { PeerFloodErrorText(PeerFloodType::Send))); } else if (error.type() == qstr("USER_BANNED_IN_CHANNEL")) { const auto link = textcmdLink( - Messenger::Instance().createInternalLinkFull(qsl("spambot")), + Core::App().createInternalLinkFull(qsl("spambot")), lang(lng_cant_more_info)); Ui::show(Box(lng_error_public_groups_denied( lt_more_info, @@ -2488,7 +2487,7 @@ void ApiWrap::checkQuitPreventFinished() { if (App::quitting()) { LOG(("ApiWrap doesn't prevent quit any more.")); } - Messenger::Instance().quitPreventFinished(); + Core::App().quitPreventFinished(); } } diff --git a/Telegram/SourceFiles/app.cpp b/Telegram/SourceFiles/app.cpp index b862dd4b0..073e46fc1 100644 --- a/Telegram/SourceFiles/app.cpp +++ b/Telegram/SourceFiles/app.cpp @@ -7,11 +7,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #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 "boxes/confirm_box.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 "core/crash_reports.h" #include "core/update_checker.h" +#include "core/sandbox.h" +#include "core/application.h" #include "window/themes/window_theme.h" #include "window/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/storage_facade.h" #include "storage/storage_shared_media.h" -#include "messenger.h" -#include "application.h" #include "mainwindow.h" #include "mainwidget.h" #include "apiwrap.h" #include "numbers.h" #include "observer_peer.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 #include @@ -117,8 +117,8 @@ namespace App { } MainWindow *wnd() { - if (auto instance = Messenger::InstancePointer()) { - return instance->getActiveWindow(); + if (Core::Sandbox::Instance().applicationLaunched()) { + return Core::App().getActiveWindow(); } return nullptr; } @@ -753,14 +753,14 @@ namespace App { setLaunchState(QuitRequested); if (auto window = App::wnd()) { - if (!Core::App().isSavingSession()) { + if (!Core::Sandbox::Instance().isSavingSession()) { window->hide(); } } if (auto mainwidget = App::main()) { mainwidget->saveDraftToCloud(); } - Messenger::QuitAttempt(); + Core::Application::QuitAttempt(); } bool quitting() { diff --git a/Telegram/SourceFiles/app.h b/Telegram/SourceFiles/app.h index 943b4c139..45ce3669e 100644 --- a/Telegram/SourceFiles/app.h +++ b/Telegram/SourceFiles/app.h @@ -11,7 +11,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL enum NewMessageType : char; enum class ImageRoundRadius; -class Messenger; class MainWindow; class MainWidget; class HistoryItem; diff --git a/Telegram/SourceFiles/auth_session.cpp b/Telegram/SourceFiles/auth_session.cpp index 8a05d1908..89723fa62 100644 --- a/Telegram/SourceFiles/auth_session.cpp +++ b/Telegram/SourceFiles/auth_session.cpp @@ -8,7 +8,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "auth_session.h" #include "apiwrap.h" -#include "messenger.h" +#include "core/application.h" +#include "core/sandbox.h" #include "core/changelogs.h" #include "storage/file_download.h" #include "storage/file_upload.h" @@ -372,7 +373,7 @@ rpl::producer AuthSessionSettings::thirdColumnWidthChanges() const { } AuthSession &Auth() { - auto result = Messenger::Instance().authSession(); + auto result = Core::App().authSession(); Assert(result != nullptr); return *result; } @@ -392,11 +393,11 @@ AuthSession::AuthSession(const MTPUser &user) _saveDataTimer.setCallback([=] { Local::writeUserSettings(); }); - Messenger::Instance().passcodeLockChanges( + Core::App().passcodeLockChanges( ) | rpl::start_with_next([=] { _shouldLockAt = 0; }, _lifetime); - Messenger::Instance().lockChanges( + Core::App().lockChanges( ) | rpl::start_with_next([=] { notifications().updateAll(); }, _lifetime); @@ -429,10 +430,8 @@ AuthSession::AuthSession(const MTPUser &user) } bool AuthSession::Exists() { - if (const auto messenger = Messenger::InstancePointer()) { - return (messenger->authSession() != nullptr); - } - return false; + return Core::Sandbox::Instance().applicationLaunched() + && (Core::App().authSession() != nullptr); } base::Observable &AuthSession::downloaderTaskFinished() { @@ -453,7 +452,7 @@ bool AuthSession::validateSelf(const MTPUser &user) { return false; } else if (user.c_user().vid.v != userId()) { LOG(("Auth Error: wrong self user received.")); - crl::on_main(this, [] { Messenger::Instance().logOut(); }); + crl::on_main(this, [] { Core::App().logOut(); }); return false; } return true; @@ -479,18 +478,18 @@ void AuthSession::saveSettingsDelayed(TimeMs delay) { void AuthSession::checkAutoLock() { if (!Global::LocalPasscode() - || Messenger::Instance().passcodeLocked()) { + || Core::App().passcodeLocked()) { return; } - Messenger::Instance().checkLocalTime(); + Core::App().checkLocalTime(); auto now = getms(true); auto shouldLockInMs = Global::AutoLock() * 1000LL; auto idleForMs = psIdleTime(); auto notPlayingVideoForMs = now - settings().lastTimeVideoPlayedAt(); auto checkTimeMs = qMin(idleForMs, notPlayingVideoForMs); if (checkTimeMs >= shouldLockInMs || (_shouldLockAt > 0 && now > _shouldLockAt + kAutoLockTimeoutLateMs)) { - Messenger::Instance().lockByPasscode(); + Core::App().lockByPasscode(); } else { _shouldLockAt = now + (shouldLockInMs - checkTimeMs); _autoLockTimer.callOnce(shouldLockInMs - checkTimeMs); diff --git a/Telegram/SourceFiles/auth_session.h b/Telegram/SourceFiles/auth_session.h index ec67993bd..19d7db7b3 100644 --- a/Telegram/SourceFiles/auth_session.h +++ b/Telegram/SourceFiles/auth_session.h @@ -267,7 +267,6 @@ private: }; -// One per Messenger. class AuthSession; AuthSession &Auth(); diff --git a/Telegram/SourceFiles/boxes/add_contact_box.cpp b/Telegram/SourceFiles/boxes/add_contact_box.cpp index c16e6a0c6..a7a150d53 100644 --- a/Telegram/SourceFiles/boxes/add_contact_box.cpp +++ b/Telegram/SourceFiles/boxes/add_contact_box.cpp @@ -10,7 +10,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "styles/style_boxes.h" #include "styles/style_dialogs.h" #include "lang/lang_keys.h" -#include "messenger.h" #include "mtproto/sender.h" #include "base/flat_set.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_participants_box.h" #include "core/file_utilities.h" +#include "core/application.h" #include "chat_helpers/emoji_suggestions_widget.h" #include "ui/widgets/checkbox.h" #include "ui/widgets/buttons.h" @@ -66,7 +66,7 @@ style::InputField CreateBioFieldStyle() { QString PeerFloodErrorText(PeerFloodType type) { auto link = textcmdLink( - Messenger::Instance().createInternalLinkFull(qsl("spambot")), + Core::App().createInternalLinkFull(qsl("spambot")), lang(lng_cant_more_info)); if (type == PeerFloodType::InviteGroup) { return lng_cant_invite_not_contact(lt_more_info, link); @@ -1209,7 +1209,7 @@ RevokePublicLinkBox::Inner::Inner(QWidget *parent, Fn revokeCallback) : Ui::NameTextOptions()); row.status.setText( st::defaultTextStyle, - Messenger::Instance().createInternalLink( + Core::App().createInternalLink( textcmdLink(1, peer->userName())), Ui::DialogTextOptions()); _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); 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 = 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); _weakRevokeConfirmBox = Ui::show(Box(text, confirmText, crl::guard(this, [this, pressed]() { if (_revokeRequestId) return; diff --git a/Telegram/SourceFiles/boxes/background_box.cpp b/Telegram/SourceFiles/boxes/background_box.cpp index 49545f090..069783434 100644 --- a/Telegram/SourceFiles/boxes/background_box.cpp +++ b/Telegram/SourceFiles/boxes/background_box.cpp @@ -19,10 +19,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "history/view/history_view_message.h" #include "auth_session.h" #include "apiwrap.h" -#include "messenger.h" #include "data/data_session.h" #include "data/data_user.h" #include "data/data_document.h" +#include "core/application.h" #include "boxes/confirm_box.h" #include "styles/style_overview.h" #include "styles/style_history.h" @@ -347,7 +347,7 @@ void BackgroundPreviewBox::share() { Expects(!_paper.slug.isEmpty()); QApplication::clipboard()->setText( - Messenger::Instance().createInternalLinkFull("bg/" + _paper.slug)); + Core::App().createInternalLinkFull("bg/" + _paper.slug)); Ui::Toast::Show(lang(lng_background_link_copied)); } diff --git a/Telegram/SourceFiles/boxes/confirm_box.cpp b/Telegram/SourceFiles/boxes/confirm_box.cpp index 27be54380..0db838bd1 100644 --- a/Telegram/SourceFiles/boxes/confirm_box.cpp +++ b/Telegram/SourceFiles/boxes/confirm_box.cpp @@ -12,7 +12,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwidget.h" #include "mainwindow.h" #include "apiwrap.h" -#include "application.h" #include "history/history.h" #include "history/history_item.h" #include "ui/widgets/checkbox.h" diff --git a/Telegram/SourceFiles/boxes/connection_box.cpp b/Telegram/SourceFiles/boxes/connection_box.cpp index 548c81941..2052108e6 100644 --- a/Telegram/SourceFiles/boxes/connection_box.cpp +++ b/Telegram/SourceFiles/boxes/connection_box.cpp @@ -11,7 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_keys.h" #include "storage/localstorage.h" #include "base/qthelp_url.h" -#include "messenger.h" +#include "core/application.h" #include "ui/widgets/checkbox.h" #include "ui/widgets/buttons.h" #include "ui/widgets/input_fields.h" @@ -975,7 +975,7 @@ void ProxiesBoxController::ShowApplyConfirmation( if (ranges::find(proxies, proxy) == end(proxies)) { proxies.push_back(proxy); } - Messenger::Instance().setCurrentProxy( + Core::App().setCurrentProxy( proxy, ProxyData::Settings::Enabled); Local::writeSettings(); @@ -998,7 +998,7 @@ void ProxiesBoxController::refreshChecker(Item &item) { const auto type = (item.data.type == Type::Http) ? Variants::Http : Variants::Tcp; - const auto mtproto = Messenger::Instance().mtp(); + const auto mtproto = Core::App().mtp(); const auto dcId = mtproto->mainDcId(); item.state = ItemState::Checking; @@ -1140,7 +1140,7 @@ void ProxiesBoxController::applyItem(int id) { auto j = findByProxy(Global::SelectedProxy()); - Messenger::Instance().setCurrentProxy( + Core::App().setCurrentProxy( item->data, ProxyData::Settings::Enabled); saveDelayed(); @@ -1163,7 +1163,7 @@ void ProxiesBoxController::setDeleted(int id, bool deleted) { _lastSelectedProxy = base::take(Global::RefSelectedProxy()); if (Global::ProxySettings() == ProxyData::Settings::Enabled) { _lastSelectedProxyUsed = true; - Messenger::Instance().setCurrentProxy( + Core::App().setCurrentProxy( ProxyData(), ProxyData::Settings::System); saveDelayed(); @@ -1188,7 +1188,7 @@ void ProxiesBoxController::setDeleted(int id, bool deleted) { Assert(Global::ProxySettings() != ProxyData::Settings::Enabled); if (base::take(_lastSelectedProxyUsed)) { - Messenger::Instance().setCurrentProxy( + Core::App().setCurrentProxy( base::take(_lastSelectedProxy), ProxyData::Settings::Enabled); } else { @@ -1293,9 +1293,7 @@ bool ProxiesBoxController::setProxySettings(ProxyData::Settings value) { } } } - Messenger::Instance().setCurrentProxy( - Global::SelectedProxy(), - value); + Core::App().setCurrentProxy(Global::SelectedProxy(), value); saveDelayed(); return true; } diff --git a/Telegram/SourceFiles/boxes/language_box.cpp b/Telegram/SourceFiles/boxes/language_box.cpp index cd720952e..72cfcbc6a 100644 --- a/Telegram/SourceFiles/boxes/language_box.cpp +++ b/Telegram/SourceFiles/boxes/language_box.cpp @@ -24,7 +24,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/confirm_box.h" #include "mainwidget.h" #include "mainwindow.h" -#include "messenger.h" +#include "core/application.h" #include "lang/lang_instance.h" #include "lang/lang_cloud_manager.h" #include "styles/style_boxes.h" @@ -1132,7 +1132,7 @@ not_null LanguageBox::createMultiSelect() { base::binary_guard LanguageBox::Show() { auto result = base::binary_guard(); - const auto manager = Messenger::Instance().langCloudManager(); + const auto manager = Core::App().langCloudManager(); if (manager->languageList().empty()) { auto guard = std::make_shared(); std::tie(result, *guard) = base::make_binary_guard(); diff --git a/Telegram/SourceFiles/boxes/peers/edit_peer_info_box.cpp b/Telegram/SourceFiles/boxes/peers/edit_peer_info_box.cpp index a65620006..28b8802a9 100644 --- a/Telegram/SourceFiles/boxes/peers/edit_peer_info_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/edit_peer_info_box.cpp @@ -31,7 +31,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mtproto/sender.h" #include "lang/lang_keys.h" #include "mainwidget.h" -#include "messenger.h" +#include "core/application.h" #include "apiwrap.h" #include "auth_session.h" #include "observer_peer.h" diff --git a/Telegram/SourceFiles/boxes/share_box.cpp b/Telegram/SourceFiles/boxes/share_box.cpp index af1665af3..c0a640e96 100644 --- a/Telegram/SourceFiles/boxes/share_box.cpp +++ b/Telegram/SourceFiles/boxes/share_box.cpp @@ -33,7 +33,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_user.h" #include "data/data_session.h" #include "auth_session.h" -#include "messenger.h" +#include "core/application.h" #include "styles/style_boxes.h" #include "styles/style_history.h" diff --git a/Telegram/SourceFiles/boxes/sticker_set_box.cpp b/Telegram/SourceFiles/boxes/sticker_set_box.cpp index b86a039e2..efb8e1e5b 100644 --- a/Telegram/SourceFiles/boxes/sticker_set_box.cpp +++ b/Telegram/SourceFiles/boxes/sticker_set_box.cpp @@ -10,22 +10,21 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_document.h" #include "data/data_session.h" #include "lang/lang_keys.h" -#include "mainwidget.h" -#include "mainwindow.h" #include "chat_helpers/stickers.h" #include "boxes/confirm_box.h" -#include "apiwrap.h" -#include "application.h" +#include "core/application.h" #include "storage/localstorage.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/scroll_area.h" #include "ui/image/image.h" #include "ui/emoji_config.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 { @@ -142,7 +141,7 @@ void StickerSetBox::addStickers() { } 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); Ui::show(Box(lang(lng_stickers_copied))); } diff --git a/Telegram/SourceFiles/boxes/stickers_box.cpp b/Telegram/SourceFiles/boxes/stickers_box.cpp index e2c978a7e..366c5eb28 100644 --- a/Telegram/SourceFiles/boxes/stickers_box.cpp +++ b/Telegram/SourceFiles/boxes/stickers_box.cpp @@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_document.h" #include "data/data_session.h" #include "data/data_channel.h" +#include "core/application.h" #include "lang/lang_keys.h" #include "mainwidget.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/image/image.h" #include "auth_session.h" -#include "messenger.h" namespace { @@ -623,7 +623,7 @@ StickersBox::Inner::Inner(QWidget *parent, not_null megagroup) : T , _megagroupSetField(this, st::groupStickersField, [] { return qsl("stickerset"); }, QString(), true) , _megagroupDivider(this) , _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); _megagroupSetAddressChangedTimer.setCallback([this] { handleMegagroupSetAddressChange(); }); connect( diff --git a/Telegram/SourceFiles/boxes/username_box.cpp b/Telegram/SourceFiles/boxes/username_box.cpp index b82333482..19354ccf0 100644 --- a/Telegram/SourceFiles/boxes/username_box.cpp +++ b/Telegram/SourceFiles/boxes/username_box.cpp @@ -13,7 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/widgets/buttons.h" #include "ui/widgets/input_fields.h" #include "ui/toast/toast.h" -#include "messenger.h" +#include "core/application.h" #include "auth_session.h" #include "data/data_session.h" #include "data/data_user.h" @@ -88,7 +88,7 @@ void UsernameBox::paintEvent(QPaintEvent *e) { if (_link->isHidden()) { p.drawTextLeft(st::usernamePadding.left(), linky, width(), lang(lng_username_link_willbe)); 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 { p.drawTextLeft(st::usernamePadding.left(), linky, width(), lang(lng_username_link)); } @@ -166,7 +166,7 @@ void UsernameBox::changed() { } void UsernameBox::linkClick() { - QApplication::clipboard()->setText(Messenger::Instance().createInternalLinkFull(getName())); + QApplication::clipboard()->setText(Core::App().createInternalLinkFull(getName())); Ui::Toast::Show(lang(lng_username_copied)); } @@ -247,7 +247,7 @@ QString UsernameBox::getName() const { void UsernameBox::updateLinkText() { 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 (!_link->isHidden()) { _link->hide(); diff --git a/Telegram/SourceFiles/calls/calls_instance.cpp b/Telegram/SourceFiles/calls/calls_instance.cpp index 8e022d67a..e1f6525c8 100644 --- a/Telegram/SourceFiles/calls/calls_instance.cpp +++ b/Telegram/SourceFiles/calls/calls_instance.cpp @@ -8,7 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "calls/calls_instance.h" #include "mtproto/connection.h" -#include "messenger.h" +#include "core/application.h" #include "auth_session.h" #include "apiwrap.h" #include "lang/lang_keys.h" @@ -101,7 +101,7 @@ void Instance::destroyCall(not_null call) { if (App::quitting()) { LOG(("Calls::Instance doesn't prevent quit any more.")); } - Messenger::Instance().quitPreventFinished(); + Core::App().quitPreventFinished(); } } diff --git a/Telegram/SourceFiles/calls/calls_panel.cpp b/Telegram/SourceFiles/calls/calls_panel.cpp index 8fb88355f..a247e1d0d 100644 --- a/Telegram/SourceFiles/calls/calls_panel.cpp +++ b/Telegram/SourceFiles/calls/calls_panel.cpp @@ -21,7 +21,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/wrap/fade_wrap.h" #include "ui/empty_userpic.h" #include "ui/emoji_config.h" -#include "messenger.h" +#include "core/application.h" #include "mainwindow.h" #include "lang/lang_keys.h" #include "auth_session.h" @@ -582,7 +582,7 @@ bool Panel::isGoodUserPhoto(PhotoData *photo) { } void Panel::initGeometry() { - auto center = Messenger::Instance().getPointForCallPanelCenter(); + auto center = Core::App().getPointForCallPanelCenter(); _useTransparency = Platform::TranslucentWindowsSupported(center); setAttribute(Qt::WA_OpaquePaintEvent, !_useTransparency); _padding = _useTransparency ? st::callShadow.extend : style::margins(st::lineWidth, st::lineWidth, st::lineWidth, st::lineWidth); diff --git a/Telegram/SourceFiles/chat_helpers/emoji_sets_manager.cpp b/Telegram/SourceFiles/chat_helpers/emoji_sets_manager.cpp index 1b703be20..36969e55c 100644 --- a/Telegram/SourceFiles/chat_helpers/emoji_sets_manager.cpp +++ b/Telegram/SourceFiles/chat_helpers/emoji_sets_manager.cpp @@ -17,7 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_keys.h" #include "base/zlib_help.h" #include "layout.h" -#include "messenger.h" +#include "core/application.h" #include "mainwidget.h" #include "styles/style_boxes.h" #include "styles/style_chat_helpers.h" @@ -245,7 +245,7 @@ Loader::Loader(QObject *parent, int id) , _id(id) , _size(GetDownloadSize(_id)) , _state(Loading{ 0, _size }) -, _mtproto(Messenger::Instance().mtp()) { +, _mtproto(Core::App().mtp()) { const auto ready = [=](std::unique_ptr loader) { if (loader) { setImplementation(std::move(loader)); diff --git a/Telegram/SourceFiles/chat_helpers/tabbed_panel.cpp b/Telegram/SourceFiles/chat_helpers/tabbed_panel.cpp index 2f9c8c412..681a00423 100644 --- a/Telegram/SourceFiles/chat_helpers/tabbed_panel.cpp +++ b/Telegram/SourceFiles/chat_helpers/tabbed_panel.cpp @@ -12,7 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "chat_helpers/tabbed_selector.h" #include "window/window_controller.h" #include "mainwindow.h" -#include "messenger.h" +#include "core/application.h" #include "styles/style_chat_helpers.h" namespace ChatHelpers { @@ -192,7 +192,7 @@ void TabbedPanel::moveByBottom() { } void TabbedPanel::enterEventHook(QEvent *e) { - Messenger::Instance().registerLeaveSubscription(this); + Core::App().registerLeaveSubscription(this); showAnimated(); } @@ -204,7 +204,7 @@ bool TabbedPanel::preventAutoHide() const { } void TabbedPanel::leaveEventHook(QEvent *e) { - Messenger::Instance().unregisterLeaveSubscription(this); + Core::App().unregisterLeaveSubscription(this); if (preventAutoHide()) { return; } diff --git a/Telegram/SourceFiles/config.h b/Telegram/SourceFiles/config.h index d2ee93657..498040e02 100644 --- a/Telegram/SourceFiles/config.h +++ b/Telegram/SourceFiles/config.h @@ -17,15 +17,6 @@ constexpr str_const AppId = "{53F49750-6209-4FBF-9CA8-7A333C87D1ED}"; // used in constexpr str_const AppFile = "Telegram"; 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, MaxPhoneCodeLength = 4, // max length of country phone code @@ -71,8 +62,6 @@ enum { MaxMessageSize = 4096, - WriteMapTimeout = 1000, - SetOnlineAfterActivity = 30, // user with hidden last seen stays online for such amount of seconds in the interface ServiceUserId = 777000, diff --git a/Telegram/SourceFiles/messenger.cpp b/Telegram/SourceFiles/core/application.cpp similarity index 79% rename from Telegram/SourceFiles/messenger.cpp rename to Telegram/SourceFiles/core/application.cpp index fb847268d..2c598ad15 100644 --- a/Telegram/SourceFiles/messenger.cpp +++ b/Telegram/SourceFiles/core/application.cpp @@ -5,7 +5,7 @@ the official desktop application for the Telegram messaging service. For license and copyright information please follow this link: https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ -#include "messenger.h" +#include "core/application.h" #include "data/data_photo.h" #include "data/data_document.h" @@ -14,13 +14,14 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "base/timer.h" #include "core/update_checker.h" #include "core/shortcuts.h" +#include "core/sandbox.h" #include "core/local_url_handlers.h" +#include "core/launcher.h" #include "storage/localstorage.h" #include "platform/platform_specific.h" #include "mainwindow.h" #include "dialogs/dialogs_entry.h" #include "history/history.h" -#include "application.h" #include "auth_session.h" #include "apiwrap.h" #include "calls/calls_instance.h" @@ -54,19 +55,14 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/confirm_box.h" #include "boxes/share_box.h" +namespace Core { namespace { constexpr auto kQuitPreventTimeoutMs = 1500; -Messenger *SingleInstance = nullptr; - } // namespace -Messenger *Messenger::InstancePointer() { - return SingleInstance; -} - -struct Messenger::Private { +struct Application::Private { UserId authSessionUserId = 0; QByteArray authSessionUserSerialized; int32 authSessionUserStreamVersion = 0; @@ -76,10 +72,9 @@ struct Messenger::Private { base::Timer quitTimer; }; -Messenger::Messenger(not_null launcher) +Application::Application(not_null launcher) : QObject() , _launcher(launcher) -, _killDownloadSessionsTimer([=] { killDownloadSessions(); }) , _private(std::make_unique()) , _databases(std::make_unique()) , _langpack(std::make_unique()) @@ -88,15 +83,14 @@ Messenger::Messenger(not_null launcher) , _logoNoMargin(Window::LoadLogoNoMargin()) { Expects(!_logo.isNull()); Expects(!_logoNoMargin.isNull()); - Expects(SingleInstance == nullptr); - - SingleInstance = this; +} +void Application::run() { Fonts::Start(); ThirdParty::start(); Global::start(); - Core::App().refreshGlobalProxy(); // Depends on Global::started(). + refreshGlobalProxy(); // Depends on Global::started(). startLocalStorage(); @@ -111,7 +105,7 @@ Messenger::Messenger(not_null launcher) } _translator = std::make_unique(); - qApp->installTranslator(_translator.get()); + QCoreApplication::instance()->installTranslator(_translator.get()); style::startManager(); anim::startManager(); @@ -121,7 +115,8 @@ Messenger::Messenger(not_null launcher) DEBUG_LOG(("Application Info: inited...")); - QApplication::instance()->installNativeEventFilter(psNativeEventFilter()); + QCoreApplication::instance()->installNativeEventFilter( + psNativeEventFilter()); cChangeTimeFormat(QLocale::system().timeFormat(QLocale::ShortFormat)); @@ -137,12 +132,12 @@ Messenger::Messenger(not_null launcher) _mediaView = std::make_unique(); _window->setGeometry(currentGeometry); - qApp->installEventFilter(this); + QCoreApplication::instance()->installEventFilter(this); connect( - qApp, - SIGNAL(applicationStateChanged(Qt::ApplicationState)), + static_cast(QCoreApplication::instance()), + &QGuiApplication::applicationStateChanged, this, - SLOT(onAppStateChanged(Qt::ApplicationState))); + &Application::stateChanged); DEBUG_LOG(("Application Info: window created...")); @@ -179,7 +174,7 @@ Messenger::Messenger(not_null launcher) } } -bool Messenger::hideMediaView() { +bool Application::hideMediaView() { if (_mediaView && !_mediaView->isHidden()) { _mediaView->hide(); if (auto activeWindow = getActiveWindow()) { @@ -190,7 +185,7 @@ bool Messenger::hideMediaView() { return false; } -void Messenger::showPhoto(not_null link) { +void Application::showPhoto(not_null link) { const auto item = App::histItemById(link->context()); const auto peer = link->peer(); return (!item && peer) @@ -198,13 +193,13 @@ void Messenger::showPhoto(not_null link) { : showPhoto(link->photo(), item); } -void Messenger::showPhoto(not_null photo, HistoryItem *item) { +void Application::showPhoto(not_null photo, HistoryItem *item) { _mediaView->showPhoto(photo, item); _mediaView->activateWindow(); _mediaView->setFocus(); } -void Messenger::showPhoto( +void Application::showPhoto( not_null photo, not_null peer) { _mediaView->showPhoto(photo, peer); @@ -212,7 +207,7 @@ void Messenger::showPhoto( _mediaView->setFocus(); } -void Messenger::showDocument(not_null document, HistoryItem *item) { +void Application::showDocument(not_null document, HistoryItem *item) { if (cUseExternalVideoPlayer() && document->isVideoFile()) { QDesktopServices::openUrl(QUrl("file:///" + document->location(false).fname)); } else { @@ -222,7 +217,7 @@ void Messenger::showDocument(not_null document, HistoryItem *item } } -PeerData *Messenger::ui_getPeerForMouseAction() { +PeerData *Application::ui_getPeerForMouseAction() { if (_mediaView && !_mediaView->isHidden()) { return _mediaView->ui_getPeerForMouseAction(); } else if (auto main = App::main()) { @@ -231,7 +226,7 @@ PeerData *Messenger::ui_getPeerForMouseAction() { return nullptr; } -bool Messenger::eventFilter(QObject *object, QEvent *e) { +bool Application::eventFilter(QObject *object, QEvent *e) { switch (e->type()) { case QEvent::KeyPress: case QEvent::MouseButtonPress: @@ -255,14 +250,16 @@ bool Messenger::eventFilter(QObject *object, QEvent *e) { } break; case QEvent::ApplicationActivate: { - if (object == qApp) { + if (object == QCoreApplication::instance()) { psUserActionDone(); } } break; case QEvent::FileOpen: { - if (object == qApp) { - auto url = QString::fromUtf8(static_cast(e)->url().toEncoded().trimmed()); + if (object == QCoreApplication::instance()) { + const auto event = static_cast(e); + const auto url = QString::fromUtf8( + event->url().toEncoded().trimmed()); if (url.startsWith(qstr("tg://"), Qt::CaseInsensitive)) { cSetStartUrl(url.mid(0, 8192)); checkStartUrl(); @@ -277,7 +274,7 @@ bool Messenger::eventFilter(QObject *object, QEvent *e) { return QObject::eventFilter(object, e); } -void Messenger::setCurrentProxy( +void Application::setCurrentProxy( const ProxyData &proxy, ProxyData::Settings settings) { const auto key = [&](const ProxyData &proxy) { @@ -292,7 +289,7 @@ void Messenger::setCurrentProxy( : ProxyData())); Global::SetSelectedProxy(proxy); Global::SetProxySettings(settings); - Core::App().refreshGlobalProxy(); + refreshGlobalProxy(); if (_mtproto) { _mtproto->restart(); if (previousKey != key(proxy)) { @@ -305,7 +302,7 @@ void Messenger::setCurrentProxy( Global::RefConnectionTypeChanged().notify(); } -void Messenger::badMtprotoConfigurationError() { +void Application::badMtprotoConfigurationError() { if (Global::ProxySettings() == ProxyData::Settings::Enabled && !_badProxyDisableBox) { const auto disableCallback = [=] { @@ -319,19 +316,19 @@ void Messenger::badMtprotoConfigurationError() { } } -void Messenger::setMtpMainDcId(MTP::DcId mainDcId) { +void Application::setMtpMainDcId(MTP::DcId mainDcId) { Expects(!_mtproto); _private->mtpConfig.mainDcId = mainDcId; } -void Messenger::setMtpKey(MTP::DcId dcId, const MTP::AuthKey::Data &keyData) { +void Application::setMtpKey(MTP::DcId dcId, const MTP::AuthKey::Data &keyData) { Expects(!_mtproto); _private->mtpConfig.keys.push_back(std::make_shared(MTP::AuthKey::Type::ReadFromFile, dcId, keyData)); } -QByteArray Messenger::serializeMtpAuthorization() const { +QByteArray Application::serializeMtpAuthorization() const { auto serialize = [this](auto mainDcId, auto &keys, auto &keysToDestroy) { auto keysSize = [](auto &list) { return sizeof(qint32) + list.size() * (sizeof(qint32) + MTP::AuthKey::Data().size()); @@ -371,13 +368,13 @@ QByteArray Messenger::serializeMtpAuthorization() const { return serialize(_private->mtpConfig.mainDcId, keys, keysToDestroy); } -void Messenger::setAuthSessionUserId(UserId userId) { +void Application::setAuthSessionUserId(UserId userId) { Expects(!authSession()); _private->authSessionUserId = userId; } -void Messenger::setAuthSessionFromStorage( +void Application::setAuthSessionFromStorage( std::unique_ptr data, QByteArray &&selfSerialized, int32 selfStreamVersion) { @@ -391,7 +388,7 @@ void Messenger::setAuthSessionFromStorage( _private->authSessionUserStreamVersion = selfStreamVersion; } -AuthSessionSettings *Messenger::getAuthSessionSettings() { +AuthSessionSettings *Application::getAuthSessionSettings() { if (_private->authSessionUserId) { return _private->storedAuthSession ? _private->storedAuthSession.get() @@ -402,7 +399,7 @@ AuthSessionSettings *Messenger::getAuthSessionSettings() { return nullptr; } -void Messenger::setMtpAuthorization(const QByteArray &serialized) { +void Application::setMtpAuthorization(const QByteArray &serialized) { Expects(!_mtproto); QDataStream stream(serialized); @@ -440,7 +437,7 @@ void Messenger::setMtpAuthorization(const QByteArray &serialized) { LOG(("MTP Info: read keys, current: %1, to destroy: %2").arg(_private->mtpConfig.keys.size()).arg(_private->mtpKeysToDestroy.size())); } -void Messenger::startMtp() { +void Application::startMtp() { Expects(!_mtproto); _mtproto = std::make_unique( @@ -504,8 +501,8 @@ void Messenger::startMtp() { _langCloudManager = std::make_unique( langpack(), mtp()); - if (!Core::UpdaterDisabled()) { - Core::UpdateChecker().setMtproto(mtp()); + if (!UpdaterDisabled()) { + UpdateChecker().setMtproto(mtp()); } if (_authSession) { @@ -517,7 +514,7 @@ void Messenger::startMtp() { } } -void Messenger::destroyMtpKeys(MTP::AuthKeysList &&keys) { +void Application::destroyMtpKeys(MTP::AuthKeysList &&keys) { if (keys.empty()) { return; } @@ -536,7 +533,7 @@ void Messenger::destroyMtpKeys(MTP::AuthKeysList &&keys) { [=] { allKeysDestroyed(); }); } -void Messenger::allKeysDestroyed() { +void Application::allKeysDestroyed() { LOG(("MTP Info: all keys scheduled for destroy are destroyed.")); crl::on_main(this, [=] { _mtprotoForKeysDestroy = nullptr; @@ -544,7 +541,7 @@ void Messenger::allKeysDestroyed() { }); } -void Messenger::suggestMainDcId(MTP::DcId mainDcId) { +void Application::suggestMainDcId(MTP::DcId mainDcId) { Assert(_mtproto != nullptr); _mtproto->suggestMainDcId(mainDcId); @@ -553,7 +550,7 @@ void Messenger::suggestMainDcId(MTP::DcId mainDcId) { } } -void Messenger::destroyStaleAuthorizationKeys() { +void Application::destroyStaleAuthorizationKeys() { Assert(_mtproto != nullptr); for (const auto &key : _mtproto->getKeysForWrite()) { @@ -568,13 +565,13 @@ void Messenger::destroyStaleAuthorizationKeys() { } } -void Messenger::resetAuthorizationKeys() { - _mtproto.reset(); +void Application::resetAuthorizationKeys() { + _mtproto = nullptr; startMtp(); Local::writeMtpData(); } -void Messenger::startLocalStorage() { +void Application::startLocalStorage() { _dcOptions = std::make_unique(); _dcOptions->constructFromBuiltIn(); Local::start(); @@ -608,24 +605,7 @@ void Messenger::startLocalStorage() { }); } -void Messenger::killDownloadSessionsStart(MTP::DcId dcId) { - if (!_killDownloadSessionTimes.contains(dcId)) { - _killDownloadSessionTimes.emplace(dcId, getms() + MTPAckSendWaiting + MTPKillFileSessionTimeout); - } - if (!_killDownloadSessionsTimer.isActive()) { - _killDownloadSessionsTimer.callOnce(MTPAckSendWaiting + MTPKillFileSessionTimeout + 5); - } -} - -void Messenger::killDownloadSessionsStop(MTP::DcId dcId) { - _killDownloadSessionTimes.erase(dcId); - if (_killDownloadSessionTimes.empty() - && _killDownloadSessionsTimer.isActive()) { - _killDownloadSessionsTimer.cancel(); - } -} - -void Messenger::forceLogOut(const TextWithEntities &explanation) { +void Application::forceLogOut(const TextWithEntities &explanation) { const auto box = Ui::show(Box( explanation, lang(lng_passcode_logout))); @@ -641,12 +621,12 @@ void Messenger::forceLogOut(const TextWithEntities &explanation) { }); } -void Messenger::checkLocalTime() { +void Application::checkLocalTime() { const auto updated = checkms(); if (App::main()) App::main()->checkLastUpdate(updated); } -void Messenger::onAppStateChanged(Qt::ApplicationState state) { +void Application::stateChanged(Qt::ApplicationState state) { if (state == Qt::ApplicationActive) { handleAppActivated(); } else { @@ -654,73 +634,53 @@ void Messenger::onAppStateChanged(Qt::ApplicationState state) { } } -void Messenger::handleAppActivated() { +void Application::handleAppActivated() { checkLocalTime(); if (_window) { _window->updateIsActive(Global::OnlineFocusTimeout()); } } -void Messenger::handleAppDeactivated() { +void Application::handleAppDeactivated() { if (_window) { _window->updateIsActive(Global::OfflineBlurTimeout()); } Ui::Tooltip::Hide(); } -void Messenger::call_handleUnreadCounterUpdate() { +void Application::call_handleUnreadCounterUpdate() { Global::RefUnreadCounterUpdate().notify(true); } -void Messenger::call_handleDelayedPeerUpdates() { +void Application::call_handleDelayedPeerUpdates() { Notify::peerUpdatedSendDelayed(); } -void Messenger::call_handleObservables() { +void Application::call_handleObservables() { base::HandleObservables(); } -void Messenger::killDownloadSessions() { - auto ms = getms(), left = static_cast(MTPAckSendWaiting) + MTPKillFileSessionTimeout; - 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); - } -} - -void Messenger::switchDebugMode() { +void Application::switchDebugMode() { if (Logs::DebugEnabled()) { Logs::SetDebugEnabled(false); - Sandbox::WriteDebugModeSetting(); + _launcher->writeDebugModeSetting(); App::restart(); } else { Logs::SetDebugEnabled(true); - Sandbox::WriteDebugModeSetting(); + _launcher->writeDebugModeSetting(); DEBUG_LOG(("Debug logs started.")); Ui::hideLayer(); } } -void Messenger::switchWorkMode() { +void Application::switchWorkMode() { Global::SetDialogsModeEnabled(!Global::DialogsModeEnabled()); Global::SetDialogsMode(Dialogs::Mode::All); Local::writeUserSettings(); App::restart(); } -void Messenger::switchTestMode() { +void Application::switchTestMode() { if (cTestMode()) { QFile(cWorkingDir() + qsl("tdata/withtestmode")).remove(); cSetTestMode(false); @@ -735,33 +695,50 @@ void Messenger::switchTestMode() { App::restart(); } -void Messenger::authSessionCreate(const MTPUser &user) { +void Application::writeInstallBetaVersionsSetting() { + _launcher->writeInstallBetaVersionsSetting(); +} + +void Application::authSessionCreate(const MTPUser &user) { Expects(_mtproto != nullptr); _authSession = std::make_unique(user); + _mtproto->setUpdatesHandler(::rpcDone([]( + const mtpPrime *from, + const mtpPrime *end) { + if (const auto main = App::main()) { + main->updateReceived(from, end); + } + })); + _mtproto->setGlobalFailHandler(::rpcFail([=](const RPCError &error) { + crl::on_main(_authSession.get(), [=] { logOut(); }); + return true; + })); authSessionChanged().notify(true); } -void Messenger::authSessionDestroy() { - unlockTerms(); - - _authSession = nullptr; +void Application::authSessionDestroy() { _private->storedAuthSession.reset(); _private->authSessionUserId = 0; _private->authSessionUserSerialized = {}; - authSessionChanged().notify(true); - Notify::unreadCounterUpdated(); + if (_authSession) { + unlockTerms(); + _mtproto->clearGlobalHandlers(); + _authSession = nullptr; + authSessionChanged().notify(true); + Notify::unreadCounterUpdated(); + } } -int Messenger::unreadBadge() const { +int Application::unreadBadge() const { return _authSession ? _authSession->data().unreadBadge() : 0; } -bool Messenger::unreadBadgeMuted() const { +bool Application::unreadBadgeMuted() const { return _authSession ? _authSession->data().unreadBadgeMuted() : false; } -void Messenger::setInternalLinkDomain(const QString &domain) const { +void Application::setInternalLinkDomain(const QString &domain) const { // This domain should start with 'http[s]://' and end with '/'. // Like 'https://telegram.me/' or 'https://t.me/'. auto validate = [](const auto &domain) { @@ -781,7 +758,7 @@ void Messenger::setInternalLinkDomain(const QString &domain) const { } } -QString Messenger::createInternalLink(const QString &query) const { +QString Application::createInternalLink(const QString &query) const { auto result = createInternalLinkFull(query); auto prefixes = { qstr("https://"), @@ -796,11 +773,11 @@ QString Messenger::createInternalLink(const QString &query) const { return result; } -QString Messenger::createInternalLinkFull(const QString &query) const { +QString Application::createInternalLinkFull(const QString &query) const { return Global::InternalLinksDomain() + query; } -void Messenger::checkStartUrl() { +void Application::checkStartUrl() { if (!cStartUrl().isEmpty() && !locked()) { auto url = cStartUrl(); cSetStartUrl(QString()); @@ -810,7 +787,7 @@ void Messenger::checkStartUrl() { } } -bool Messenger::openLocalUrl(const QString &url, QVariant context) { +bool Application::openLocalUrl(const QString &url, QVariant context) { auto urlTrimmed = url.trimmed(); if (urlTrimmed.size() > 8192) urlTrimmed = urlTrimmed.mid(0, 8192); @@ -822,7 +799,7 @@ bool Messenger::openLocalUrl(const QString &url, QVariant context) { using namespace qthelp; const auto options = RegExOption::CaseInsensitive; - for (const auto &[expression, handler] : Core::LocalUrlHandlers()) { + for (const auto &[expression, handler] : LocalUrlHandlers()) { const auto match = regex_match(expression, command, options); if (match) { return handler(match, context); @@ -831,74 +808,74 @@ bool Messenger::openLocalUrl(const QString &url, QVariant context) { return false; } -void Messenger::lockByPasscode() { +void Application::lockByPasscode() { _passcodeLock = true; _window->setupPasscodeLock(); } -void Messenger::unlockPasscode() { +void Application::unlockPasscode() { clearPasscodeLock(); _window->clearPasscodeLock(); } -void Messenger::clearPasscodeLock() { +void Application::clearPasscodeLock() { cSetPasscodeBadTries(0); _passcodeLock = false; } -bool Messenger::passcodeLocked() const { +bool Application::passcodeLocked() const { return _passcodeLock.current(); } -rpl::producer Messenger::passcodeLockChanges() const { +rpl::producer Application::passcodeLockChanges() const { return _passcodeLock.changes(); } -rpl::producer Messenger::passcodeLockValue() const { +rpl::producer Application::passcodeLockValue() const { return _passcodeLock.value(); } -void Messenger::lockByTerms(const Window::TermsLock &data) { +void Application::lockByTerms(const Window::TermsLock &data) { if (!_termsLock || *_termsLock != data) { _termsLock = std::make_unique(data); _termsLockChanges.fire(true); } } -void Messenger::unlockTerms() { +void Application::unlockTerms() { if (_termsLock) { _termsLock = nullptr; _termsLockChanges.fire(false); } } -std::optional Messenger::termsLocked() const { +std::optional Application::termsLocked() const { return _termsLock ? base::make_optional(*_termsLock) : std::nullopt; } -rpl::producer Messenger::termsLockChanges() const { +rpl::producer Application::termsLockChanges() const { return _termsLockChanges.events(); } -rpl::producer Messenger::termsLockValue() const { +rpl::producer Application::termsLockValue() const { return rpl::single( _termsLock != nullptr ) | rpl::then(termsLockChanges()); } -void Messenger::termsDeleteNow() { +void Application::termsDeleteNow() { MTP::send(MTPaccount_DeleteAccount(MTP_string("Decline ToS update"))); } -bool Messenger::locked() const { +bool Application::locked() const { return passcodeLocked() || termsLocked(); } -rpl::producer Messenger::lockChanges() const { +rpl::producer Application::lockChanges() const { return lockValue() | rpl::skip(1); } -rpl::producer Messenger::lockValue() const { +rpl::producer Application::lockValue() const { using namespace rpl::mappers; return rpl::combine( passcodeLockValue(), @@ -906,9 +883,216 @@ rpl::producer Messenger::lockValue() const { _1 || _2); } -Messenger::~Messenger() { - Expects(SingleInstance == this); +MainWindow *Application::getActiveWindow() const { + return _window.get(); +} +bool Application::closeActiveWindow() { + if (hideMediaView()) { + return true; + } + if (auto activeWindow = getActiveWindow()) { + if (!activeWindow->hideNoQuit()) { + activeWindow->close(); + } + return true; + } + return false; +} + +bool Application::minimizeActiveWindow() { + hideMediaView(); + if (auto activeWindow = getActiveWindow()) { + if (Global::WorkMode().value() == dbiwmTrayOnly) { + activeWindow->minimizeToTray(); + } else { + activeWindow->setWindowState(Qt::WindowMinimized); + } + return true; + } + return false; +} + +QWidget *Application::getFileDialogParent() { + return (_mediaView && _mediaView->isVisible()) ? (QWidget*)_mediaView.get() : (QWidget*)getActiveWindow(); +} + +void Application::checkMediaViewActivation() { + if (_mediaView && !_mediaView->isHidden()) { + _mediaView->activateWindow(); + QApplication::setActiveWindow(_mediaView.get()); + _mediaView->setFocus(); + } +} + +void Application::logOut() { + if (_mtproto) { + _mtproto->logout(::rpcDone([=] { + loggedOut(); + }), ::rpcFail([=] { + loggedOut(); + return true; + })); + } else { + // We log out because we've forgotten passcode. + // So we just start mtproto from scratch. + startMtp(); + loggedOut(); + } +} + +void Application::loggedOut() { + if (Global::LocalPasscode()) { + Global::SetLocalPasscode(false); + Global::RefLocalPasscodeChanged().notify(); + } + clearPasscodeLock(); + Media::Player::mixer()->stopAndClear(); + Global::SetVoiceMsgPlaybackDoubled(false); + Media::Player::mixer()->setVoicePlaybackDoubled(false); + if (const auto window = getActiveWindow()) { + window->tempDirDelete(Local::ClearManagerAll); + window->setupIntro(); + } + if (const auto session = authSession()) { + session->data().clearLocalStorage(); + authSessionDestroy(); + } + if (_mediaView) { + hideMediaView(); + _mediaView->clearData(); + } + Local::reset(); + + cSetOtherOnline(0); + Images::ClearRemote(); +} + +QPoint Application::getPointForCallPanelCenter() const { + if (auto activeWindow = getActiveWindow()) { + Assert(activeWindow->windowHandle() != nullptr); + if (activeWindow->isActive()) { + return activeWindow->geometry().center(); + } + return activeWindow->windowHandle()->screen()->geometry().center(); + } + return QApplication::desktop()->screenGeometry().center(); +} + +// macOS Qt bug workaround, sometimes no leaveEvent() gets to the nested widgets. +void Application::registerLeaveSubscription(QWidget *widget) { +#ifdef Q_OS_MAC + if (auto topLevel = widget->window()) { + if (topLevel == _window.get()) { + auto weak = make_weak(widget); + auto subscription = _window->leaveEvents( + ) | rpl::start_with_next([weak] { + if (const auto window = weak.data()) { + QEvent ev(QEvent::Leave); + QGuiApplication::sendEvent(window, &ev); + } + }); + _leaveSubscriptions.emplace_back(weak, std::move(subscription)); + } + } +#endif // Q_OS_MAC +} + +void Application::unregisterLeaveSubscription(QWidget *widget) { +#ifdef Q_OS_MAC + _leaveSubscriptions = std::move( + _leaveSubscriptions + ) | ranges::action::remove_if([&](const LeaveSubscription &subscription) { + auto pointer = subscription.pointer.data(); + return !pointer || (pointer == widget); + }); +#endif // Q_OS_MAC +} + +void Application::postponeCall(FnMut &&callable) { + Sandbox::Instance().postponeCall(std::move(callable)); +} + +void Application::refreshGlobalProxy() { + Sandbox::Instance().refreshGlobalProxy(); +} + +void Application::activateWindowDelayed(not_null widget) { + Sandbox::Instance().activateWindowDelayed(widget); +} + +void Application::pauseDelayedWindowActivations() { + Sandbox::Instance().pauseDelayedWindowActivations(); +} + +void Application::resumeDelayedWindowActivations() { + Sandbox::Instance().resumeDelayedWindowActivations(); +} + +void Application::preventWindowActivation() { + pauseDelayedWindowActivations(); + postponeCall([=] { + resumeDelayedWindowActivations(); + }); +} + +void Application::QuitAttempt() { + auto prevents = false; + if (AuthSession::Exists() && !Sandbox::Instance().isSavingSession()) { + if (Auth().api().isQuitPrevent()) { + prevents = true; + } + if (Auth().calls().isQuitPrevent()) { + prevents = true; + } + } + if (prevents) { + App().quitDelayed(); + } else { + QApplication::quit(); + } +} + +void Application::quitPreventFinished() { + if (App::quitting()) { + QuitAttempt(); + } +} + +void Application::quitDelayed() { + if (!_private->quitTimer.isActive()) { + _private->quitTimer.setCallback([] { QApplication::quit(); }); + _private->quitTimer.callOnce(kQuitPreventTimeoutMs); + } +} + +void Application::startShortcuts() { + Shortcuts::Start(); + + Shortcuts::Requests( + ) | rpl::start_with_next([=](not_null request) { + using Command = Shortcuts::Command; + request->check(Command::Quit) && request->handle([] { + App::quit(); + return true; + }); + request->check(Command::Lock) && request->handle([=] { + if (!passcodeLocked() && Global::LocalPasscode()) { + lockByPasscode(); + return true; + } + return false; + }); + request->check(Command::Minimize) && request->handle([=] { + return minimizeActiveWindow(); + }); + request->check(Command::Close) && request->handle([=] { + return closeActiveWindow(); + }); + }, _lifetime); +} + +Application::~Application() { _window.reset(); _mediaView.reset(); @@ -939,188 +1123,10 @@ Messenger::~Messenger() { Local::finish(); Global::finish(); ThirdParty::finish(); - - SingleInstance = nullptr; } -MainWindow *Messenger::getActiveWindow() const { - return _window.get(); +Application &App() { + return Sandbox::Instance().application(); } -bool Messenger::closeActiveWindow() { - if (hideMediaView()) { - return true; - } - if (auto activeWindow = getActiveWindow()) { - if (!activeWindow->hideNoQuit()) { - activeWindow->close(); - } - return true; - } - return false; -} - -bool Messenger::minimizeActiveWindow() { - hideMediaView(); - if (auto activeWindow = getActiveWindow()) { - if (Global::WorkMode().value() == dbiwmTrayOnly) { - activeWindow->minimizeToTray(); - } else { - activeWindow->setWindowState(Qt::WindowMinimized); - } - return true; - } - return false; -} - -QWidget *Messenger::getFileDialogParent() { - return (_mediaView && _mediaView->isVisible()) ? (QWidget*)_mediaView.get() : (QWidget*)getActiveWindow(); -} - -void Messenger::checkMediaViewActivation() { - if (_mediaView && !_mediaView->isHidden()) { - _mediaView->activateWindow(); - Core::App().setActiveWindow(_mediaView.get()); - _mediaView->setFocus(); - } -} - -void Messenger::logOut() { - if (_mtproto) { - _mtproto->logout(::rpcDone([=] { - loggedOut(); - }), ::rpcFail([=] { - loggedOut(); - return true; - })); - } else { - // We log out because we've forgotten passcode. - // So we just start mtproto from scratch. - startMtp(); - loggedOut(); - } -} - -void Messenger::loggedOut() { - if (Global::LocalPasscode()) { - Global::SetLocalPasscode(false); - Global::RefLocalPasscodeChanged().notify(); - } - clearPasscodeLock(); - Media::Player::mixer()->stopAndClear(); - Global::SetVoiceMsgPlaybackDoubled(false); - Media::Player::mixer()->setVoicePlaybackDoubled(false); - if (const auto window = getActiveWindow()) { - window->tempDirDelete(Local::ClearManagerAll); - window->setupIntro(); - } - if (const auto session = authSession()) { - session->data().clearLocalStorage(); - authSessionDestroy(); - } - if (_mediaView) { - hideMediaView(); - _mediaView->clearData(); - } - Local::reset(); - - cSetOtherOnline(0); - Images::ClearRemote(); -} - -QPoint Messenger::getPointForCallPanelCenter() const { - if (auto activeWindow = getActiveWindow()) { - Assert(activeWindow->windowHandle() != nullptr); - if (activeWindow->isActive()) { - return activeWindow->geometry().center(); - } - return activeWindow->windowHandle()->screen()->geometry().center(); - } - return QApplication::desktop()->screenGeometry().center(); -} - -// macOS Qt bug workaround, sometimes no leaveEvent() gets to the nested widgets. -void Messenger::registerLeaveSubscription(QWidget *widget) { -#ifdef Q_OS_MAC - if (auto topLevel = widget->window()) { - if (topLevel == _window.get()) { - auto weak = make_weak(widget); - auto subscription = _window->leaveEvents( - ) | rpl::start_with_next([weak] { - if (const auto window = weak.data()) { - QEvent ev(QEvent::Leave); - QGuiApplication::sendEvent(window, &ev); - } - }); - _leaveSubscriptions.emplace_back(weak, std::move(subscription)); - } - } -#endif // Q_OS_MAC -} - -void Messenger::unregisterLeaveSubscription(QWidget *widget) { -#ifdef Q_OS_MAC - _leaveSubscriptions = std::move( - _leaveSubscriptions - ) | ranges::action::remove_if([&](const LeaveSubscription &subscription) { - auto pointer = subscription.pointer.data(); - return !pointer || (pointer == widget); - }); -#endif // Q_OS_MAC -} - -void Messenger::QuitAttempt() { - auto prevents = false; - if (AuthSession::Exists() && !Core::App().isSavingSession()) { - if (Auth().api().isQuitPrevent()) { - prevents = true; - } - if (Auth().calls().isQuitPrevent()) { - prevents = true; - } - } - if (prevents) { - Instance().quitDelayed(); - } else { - QApplication::quit(); - } -} - -void Messenger::quitPreventFinished() { - if (App::quitting()) { - QuitAttempt(); - } -} - -void Messenger::quitDelayed() { - if (!_private->quitTimer.isActive()) { - _private->quitTimer.setCallback([] { QApplication::quit(); }); - _private->quitTimer.callOnce(kQuitPreventTimeoutMs); - } -} - -void Messenger::startShortcuts() { - Shortcuts::Start(); - - Shortcuts::Requests( - ) | rpl::start_with_next([=](not_null request) { - using Command = Shortcuts::Command; - request->check(Command::Quit) && request->handle([] { - App::quit(); - return true; - }); - request->check(Command::Lock) && request->handle([=] { - if (!passcodeLocked() && Global::LocalPasscode()) { - lockByPasscode(); - return true; - } - return false; - }); - request->check(Command::Minimize) && request->handle([=] { - return minimizeActiveWindow(); - }); - request->check(Command::Close) && request->handle([=] { - return closeActiveWindow(); - }); - }, _lifetime); -} +} // namespace Core diff --git a/Telegram/SourceFiles/messenger.h b/Telegram/SourceFiles/core/application.h similarity index 88% rename from Telegram/SourceFiles/messenger.h rename to Telegram/SourceFiles/core/application.h index 29fbd9820..2e45b7f66 100644 --- a/Telegram/SourceFiles/messenger.h +++ b/Telegram/SourceFiles/core/application.h @@ -23,11 +23,6 @@ namespace Storage { class Databases; } // namespace Storage -namespace Core { -class Launcher; -struct LocalUrlHandler; -} // namespace Core - namespace Window { struct TermsLock; } // namespace Window @@ -56,21 +51,27 @@ class Translator; class CloudManager; } // namespace Lang -class Messenger final : public QObject, public RPCSender, private base::Subscriber { - Q_OBJECT +namespace Core { +class Launcher; +struct LocalUrlHandler; + +class Application final + : public QObject + , public RPCSender + , private base::Subscriber { public: - Messenger(not_null launcher); + Application(not_null launcher); - Messenger(const Messenger &other) = delete; - Messenger &operator=(const Messenger &other) = delete; + Application(const Application &other) = delete; + Application &operator=(const Application &other) = delete; - ~Messenger(); - - not_null launcher() const { + not_null launcher() const { return _launcher; } + void run(); + // Windows interface. MainWindow *getActiveWindow() const; bool closeActiveWindow(); @@ -97,13 +98,6 @@ public: return _logoNoMargin; } - static Messenger *InstancePointer(); - static Messenger &Instance() { - auto result = InstancePointer(); - Assert(result != nullptr); - return *result; - } - // MTProto components. MTP::DcOptions *dcOptions() { return _dcOptions.get(); @@ -169,9 +163,6 @@ public: void checkStartUrl(); bool openLocalUrl(const QString &url, QVariant context); - void killDownloadSessionsStart(MTP::DcId dcId); - void killDownloadSessionsStop(MTP::DcId dcId); - void forceLogOut(const TextWithEntities &explanation); void checkLocalTime(); void lockByPasscode(); @@ -194,6 +185,14 @@ public: void registerLeaveSubscription(QWidget *widget); void unregisterLeaveSubscription(QWidget *widget); + // Sandbox interface. + void postponeCall(FnMut &&callable); + void refreshGlobalProxy(); + void activateWindowDelayed(not_null widget); + void pauseDelayedWindowActivations(); + void resumeDelayedWindowActivations(); + void preventWindowActivation(); + void quitPreventFinished(); void handleAppActivated(); @@ -202,6 +201,7 @@ public: void switchDebugMode(); void switchWorkMode(); void switchTestMode(); + void writeInstallBetaVersionsSetting(); void call_handleUnreadCounterUpdate(); void call_handleDelayedPeerUpdates(); @@ -211,13 +211,11 @@ public: _callDelayedTimer.call(duration, std::move(lambda)); } + ~Application(); + protected: bool eventFilter(QObject *object, QEvent *event) override; -public slots: - void killDownloadSessions(); - void onAppStateChanged(Qt::ApplicationState state); - private: void destroyMtpKeys(MTP::AuthKeysList &&keys); void allKeysDestroyed(); @@ -225,6 +223,8 @@ private: void startLocalStorage(); void startShortcuts(); + void stateChanged(Qt::ApplicationState state); + friend void App::quit(); static void QuitAttempt(); void quitDelayed(); @@ -234,12 +234,7 @@ private: void clearPasscodeLock(); void loggedOut(); - void fillLocalUrlHandlers(); - - not_null _launcher; - - base::flat_map _killDownloadSessionTimes; - base::Timer _killDownloadSessionsTimer; + not_null _launcher; // Some fields are just moved from the declaration. struct Private; @@ -286,3 +281,7 @@ private: rpl::lifetime _lifetime; }; + +Application &App(); + +} // namespace Core diff --git a/Telegram/SourceFiles/core/click_handler_types.cpp b/Telegram/SourceFiles/core/click_handler_types.cpp index 847b37f78..a0ed5aca1 100644 --- a/Telegram/SourceFiles/core/click_handler_types.cpp +++ b/Telegram/SourceFiles/core/click_handler_types.cpp @@ -8,10 +8,11 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/click_handler_types.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 "auth_session.h" -#include "application.h" #include "platform/platform_specific.h" #include "history/view/history_view_element.h" #include "history/history_item.h" @@ -20,7 +21,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "base/qthelp_url.h" #include "storage/localstorage.h" #include "ui/widgets/tooltip.h" -#include "core/file_utilities.h" #include "data/data_user.h" #include "data/data_session.h" @@ -117,7 +117,7 @@ QString UrlClickHandler::url() const { void UrlClickHandler::Open(QString url, QVariant context) { url = tryConvertUrlToLocal(url); - if (InternalPassportLink(url)) { + if (Core::InternalPassportLink(url)) { return; } @@ -125,7 +125,7 @@ void UrlClickHandler::Open(QString url, QVariant context) { if (isEmail(url)) { File::OpenEmailLink(url); } else if (url.startsWith(qstr("tg://"), Qt::CaseInsensitive)) { - Messenger::Instance().openLocalUrl(url, context); + Core::App().openLocalUrl(url, context); } else if (!url.isEmpty()) { QDesktopServices::openUrl(url); } @@ -153,7 +153,7 @@ TextWithEntities UrlClickHandler::getExpandedLinkTextWithEntities(ExpandLinksMod void HiddenUrlClickHandler::Open(QString url, QVariant context) { url = tryConvertUrlToLocal(url); - if (InternalPassportLink(url)) { + if (Core::InternalPassportLink(url)) { return; } @@ -165,7 +165,7 @@ void HiddenUrlClickHandler::Open(QString url, QVariant context) { } else { const auto parsedUrl = QUrl::fromUserInput(url); if (UrlRequiresConfirmation(url)) { - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); const auto displayUrl = parsedUrl.isValid() ? parsedUrl.toDisplayString() : url; @@ -183,7 +183,7 @@ void HiddenUrlClickHandler::Open(QString url, QVariant context) { void BotGameUrlClickHandler::onClick(ClickContext context) const { const auto url = tryConvertUrlToLocal(this->url()); - if (InternalPassportLink(url)) { + if (Core::InternalPassportLink(url)) { return; } diff --git a/Telegram/SourceFiles/core/crash_report_window.cpp b/Telegram/SourceFiles/core/crash_report_window.cpp index dfb09ea63..c7be12315 100644 --- a/Telegram/SourceFiles/core/crash_report_window.cpp +++ b/Telegram/SourceFiles/core/crash_report_window.cpp @@ -8,11 +8,18 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/crash_report_window.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 "platform/platform_specific.h" -#include "application.h" #include "base/zlib_help.h" -#include "core/update_checker.h" + +namespace { + +constexpr auto kDefaultProxyPort = 80; + +} // namespace PreLaunchWindow *PreLaunchWindowInstance = nullptr; @@ -198,8 +205,12 @@ LastCrashedWindow::UpdaterData::UpdaterData(QWidget *buttonParent) , skip(buttonParent, false) { } -LastCrashedWindow::LastCrashedWindow() -: _port(80) +LastCrashedWindow::LastCrashedWindow( + not_null launcher, + const QByteArray &crashdump, + Fn launch) +: _dumpraw(crashdump) +, _port(kDefaultProxyPort) , _label(this) , _pleaseSendReport(this) , _yourReportName(this) @@ -213,18 +224,15 @@ LastCrashedWindow::LastCrashedWindow() , _saveReport(this) , _getApp(this) , _includeUsername(this) -, _reportText(QString::fromUtf8(Sandbox::LastCrashDump())) +, _reportText(QString::fromUtf8(crashdump)) , _reportShown(false) , _reportSaved(false) -, _sendingState(Sandbox::LastCrashDump().isEmpty() ? SendingNoReport : SendingUpdateCheck) +, _sendingState(crashdump.isEmpty() ? SendingNoReport : SendingUpdateCheck) , _updating(this) -, _sendingProgress(0) -, _sendingTotal(0) -, _checkReply(0) -, _sendReply(0) , _updaterData(Core::UpdaterDisabled() ? nullptr - : std::make_unique(this)) { + : std::make_unique(this)) +, _launch(std::move(launch)) { excludeReportUsername(); 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.")); - _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.setTextInteractionFlags(Qt::TextSelectableByMouse); @@ -386,9 +394,11 @@ void LastCrashedWindow::onSaveReport() { } QByteArray LastCrashedWindow::getCrashReportRaw() const { - QByteArray result(Sandbox::LastCrashDump()); + auto result = _dumpraw; 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; } @@ -775,7 +785,7 @@ void LastCrashedWindow::updateControls() { } void LastCrashedWindow::onNetworkSettings() { - const auto &proxy = Sandbox::PreLaunchProxy(); + const auto &proxy = Core::Sandbox::Instance().sandboxProxy(); const auto box = new NetworkSettingsWindow( this, proxy.host, @@ -797,7 +807,7 @@ void LastCrashedWindow::onNetworkSettingsSaved( QString password) { Expects(host.isEmpty() || port != 0); - auto &proxy = Sandbox::RefPreLaunchProxy(); + auto proxy = ProxyData(); proxy.type = host.isEmpty() ? ProxyData::Type::None : ProxyData::Type::Http; @@ -805,9 +815,11 @@ void LastCrashedWindow::onNetworkSettingsSaved( proxy.port = port; proxy.user = username; proxy.password = password; + _proxyChanges.fire(std::move(proxy)); + proxyUpdated(); +} - Core::App().refreshGlobalProxy(); - +void LastCrashedWindow::proxyUpdated() { if (_updaterData && ((_updaterData->state == UpdatingCheck) || (_updaterData->state == UpdatingFail @@ -824,6 +836,10 @@ void LastCrashedWindow::onNetworkSettingsSaved( activate(); } +rpl::producer LastCrashedWindow::proxyChanges() const { + return _proxyChanges.events(); +} + void LastCrashedWindow::setUpdatingState(UpdatingState state, bool force) { Expects(_updaterData != nullptr); @@ -932,8 +948,8 @@ void LastCrashedWindow::onUpdateFailed() { void LastCrashedWindow::onContinue() { if (CrashReports::Restart() == CrashReports::CantOpen) { new NotStartedWindow(); - } else if (!Global::started()) { - Sandbox::launch(); + } else { + _launch(); } close(); } diff --git a/Telegram/SourceFiles/core/crash_report_window.h b/Telegram/SourceFiles/core/crash_report_window.h index 1a99ba2b9..80b584e2d 100644 --- a/Telegram/SourceFiles/core/crash_report_window.h +++ b/Telegram/SourceFiles/core/crash_report_window.h @@ -7,6 +7,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #pragma once +namespace Core { +class Launcher; +} // namespace Core + class PreLaunchWindow : public QWidget { public: PreLaunchWindow(QString title = QString()); @@ -62,8 +66,8 @@ public: NotStartedWindow(); protected: - void closeEvent(QCloseEvent *e); - void resizeEvent(QResizeEvent *e); + void closeEvent(QCloseEvent *e) override; + void resizeEvent(QResizeEvent *e) override; private: void updateControls(); @@ -78,7 +82,16 @@ class LastCrashedWindow : public PreLaunchWindow { Q_OBJECT public: - LastCrashedWindow(); + LastCrashedWindow( + not_null launcher, + const QByteArray &crashdump, + Fn launch); + + rpl::producer proxyChanges() const; + + rpl::lifetime &lifetime() { + return _lifetime; + } public slots: void onViewReport(); @@ -105,10 +118,11 @@ public slots: void onUpdateFailed(); protected: - void closeEvent(QCloseEvent *e); - void resizeEvent(QResizeEvent *e); + void closeEvent(QCloseEvent *e) override; + void resizeEvent(QResizeEvent *e) override; private: + void proxyUpdated(); QString minidumpFileName(); void updateControls(); @@ -117,6 +131,8 @@ private: QString getReportField(const QLatin1String &name, const QLatin1String &prefix); void addReportFieldPart(const QLatin1String &name, const QLatin1String &prefix, QHttpMultiPart *multipart); + QByteArray _dumpraw; + QString _host, _username, _password; quint32 _port; @@ -146,10 +162,12 @@ private: SendingState _sendingState; PreLaunchLabel _updating; - qint64 _sendingProgress, _sendingTotal; + qint64 _sendingProgress = 0; + qint64 _sendingTotal = 0; QNetworkAccessManager _sendManager; - QNetworkReply *_checkReply, *_sendReply; + QNetworkReply *_checkReply = nullptr; + QNetworkReply *_sendReply = nullptr; enum UpdatingState { UpdatingNone, @@ -171,6 +189,8 @@ private: void setUpdatingState(UpdatingState state, bool force = false); void setDownloadProgress(qint64 ready, qint64 total); + Fn _launch; + rpl::event_stream _proxyChanges; rpl::lifetime _lifetime; }; diff --git a/Telegram/SourceFiles/core/crash_reports.cpp b/Telegram/SourceFiles/core/crash_reports.cpp index a5c2f01c1..633820be9 100644 --- a/Telegram/SourceFiles/core/crash_reports.cpp +++ b/Telegram/SourceFiles/core/crash_reports.cpp @@ -8,6 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/crash_reports.h" #include "platform/platform_specific.h" +#include "core/launcher.h" #include #include @@ -319,14 +320,14 @@ bool DumpCallback(const google_breakpad::MinidumpDescriptor &md, void *context, } // namespace -void StartCatching() { +void StartCatching(not_null launcher) { #ifndef TDESKTOP_DISABLE_CRASH_REPORTS ProcessAnnotations["Binary"] = cExeName().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["Launched"] = QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss").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"); QDir().mkpath(dumpspath); @@ -393,7 +394,7 @@ void FinishCatching() { #endif // !TDESKTOP_DISABLE_CRASH_REPORTS } -Status Start() { +StartResult Start() { #ifndef TDESKTOP_DISABLE_CRASH_REPORTS ReportPath = cWorkingDir() + qsl("tdata/working"); @@ -413,11 +414,11 @@ Status Start() { } 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 LastCrashed; + return lastdump; } #endif // !TDESKTOP_DISABLE_CRASH_REPORTS diff --git a/Telegram/SourceFiles/core/crash_reports.h b/Telegram/SourceFiles/core/crash_reports.h index dfb7e43ef..aadc0180b 100644 --- a/Telegram/SourceFiles/core/crash_reports.h +++ b/Telegram/SourceFiles/core/crash_reports.h @@ -7,6 +7,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #pragma once +namespace Core { +class Launcher; +} // namespace Core + namespace CrashReports { #ifndef TDESKTOP_DISABLE_CRASH_REPORTS @@ -26,10 +30,11 @@ const dump &operator<<(const dump &stream, double num); enum Status { CantOpen, - LastCrashed, Started }; -Status Start(); +// Open status or crash report dump. +using StartResult = base::variant; +StartResult Start(); Status Restart(); // can be only CantOpen or Started void Finish(); @@ -46,7 +51,7 @@ inline void ClearAnnotationRef(const std::string &key) { SetAnnotationRef(key, nullptr); } -void StartCatching(); +void StartCatching(not_null launcher); void FinishCatching(); } // namespace CrashReports diff --git a/Telegram/SourceFiles/core/file_utilities.cpp b/Telegram/SourceFiles/core/file_utilities.cpp index 9df8e7774..2a58a5309 100644 --- a/Telegram/SourceFiles/core/file_utilities.cpp +++ b/Telegram/SourceFiles/core/file_utilities.cpp @@ -9,17 +9,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/localstorage.h" #include "platform/platform_file_utilities.h" -#include "messenger.h" -#include "application.h" +#include "core/application.h" #include "mainwindow.h" -void PreventWindowActivation() { - Core::App().pauseDelayedWindowActivations(); - Core::App().postponeCall([] { - Core::App().resumeDelayedWindowActivations(); - }); -} - bool filedialogGetSaveFile( QPointer parent, QString &file, @@ -28,7 +20,7 @@ bool filedialogGetSaveFile( const QString &initialPath) { QStringList files; QByteArray remoteContent; - PreventWindowActivation(); + Core::App().preventWindowActivation(); bool result = Platform::FileDialog::Get( parent, files, @@ -47,7 +39,7 @@ bool filedialogGetSaveFile( const QString &filter, const QString &initialPath) { return filedialogGetSaveFile( - Messenger::Instance().getFileDialogParent(), + Core::App().getFileDialogParent(), file, caption, filter, @@ -121,7 +113,7 @@ namespace File { void OpenEmailLink(const QString &email) { crl::on_main([=] { - PreventWindowActivation(); + Core::App().preventWindowActivation(); Platform::File::UnsafeOpenEmailLink(email); }); } @@ -129,7 +121,7 @@ void OpenEmailLink(const QString &email) { void OpenWith(const QString &filepath, QPoint menuPosition) { InvokeQueued(QApplication::instance(), [=] { if (!Platform::File::UnsafeShowOpenWithDropdown(filepath, menuPosition)) { - PreventWindowActivation(); + Core::App().preventWindowActivation(); if (!Platform::File::UnsafeShowOpenWith(filepath)) { Platform::File::UnsafeLaunch(filepath); } @@ -139,14 +131,14 @@ void OpenWith(const QString &filepath, QPoint menuPosition) { void Launch(const QString &filepath) { crl::on_main([=] { - PreventWindowActivation(); + Core::App().preventWindowActivation(); Platform::File::UnsafeLaunch(filepath); }); } void ShowInFolder(const QString &filepath) { crl::on_main([=] { - PreventWindowActivation(); + Core::App().preventWindowActivation(); Platform::File::UnsafeShowInFolder(filepath); }); } @@ -186,7 +178,7 @@ void GetOpenPath( InvokeQueued(QApplication::instance(), [=] { auto files = QStringList(); auto remoteContent = QByteArray(); - PreventWindowActivation(); + Core::App().preventWindowActivation(); const auto success = Platform::FileDialog::Get( parent, files, @@ -220,7 +212,7 @@ void GetOpenPaths( InvokeQueued(QApplication::instance(), [=] { auto files = QStringList(); auto remoteContent = QByteArray(); - PreventWindowActivation(); + Core::App().preventWindowActivation(); const auto success = Platform::FileDialog::Get( parent, files, @@ -269,7 +261,7 @@ void GetFolder( InvokeQueued(QApplication::instance(), [=] { auto files = QStringList(); auto remoteContent = QByteArray(); - PreventWindowActivation(); + Core::App().preventWindowActivation(); const auto success = Platform::FileDialog::Get( parent, files, @@ -320,7 +312,7 @@ bool GetDefault( } QString file; 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(); if (!path.isEmpty() && path != cDialogLastPath()) { cSetDialogLastPath(path); @@ -328,11 +320,11 @@ bool GetDefault( } return !files.isEmpty(); } 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) { - file = QFileDialog::getSaveFileName(Messenger::Instance().getFileDialogParent(), caption, startFile, filter); + file = QFileDialog::getSaveFileName(Core::App().getFileDialogParent(), caption, startFile, filter); } else { - file = QFileDialog::getOpenFileName(Messenger::Instance().getFileDialogParent(), caption, startFile, filter); + file = QFileDialog::getOpenFileName(Core::App().getFileDialogParent(), caption, startFile, filter); } if (file.isEmpty()) { files = QStringList(); diff --git a/Telegram/SourceFiles/core/launcher.cpp b/Telegram/SourceFiles/core/launcher.cpp index 83f869e36..129407523 100644 --- a/Telegram/SourceFiles/core/launcher.cpp +++ b/Telegram/SourceFiles/core/launcher.cpp @@ -12,10 +12,179 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/crash_reports.h" #include "core/main_queue_processor.h" #include "core/update_checker.h" +#include "core/sandbox.h" #include "base/concurrent_timer.h" -#include "application.h" 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(&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(&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::Create(int argc, char *argv[]) { return std::make_unique(argc, argv); @@ -37,10 +206,10 @@ void Launcher::init() { prepareSettings(); - QCoreApplication::setApplicationName(qsl("TelegramDesktop")); + QApplication::setApplicationName(qsl("TelegramDesktop")); #ifndef OS_MAC_OLD - QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true); + QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true); #endif // OS_MAC_OLD initHook(); @@ -55,21 +224,21 @@ int Launcher::exec() { return psCleanup(); } - // both are finished in Application::closeApplication + // both are finished in Sandbox::closeApplication 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(); DEBUG_LOG(("Telegram finished, result: %1").arg(result)); 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)) { psDeleteDir(cWorkingDir() + qsl("tupdates/temp")); } } else if (cRestarting()) { - DEBUG_LOG(("Application Info: executing Telegram, because of restart...")); + DEBUG_LOG(("Sandbox Info: executing Telegram because of restart.")); launchUpdater(UpdaterLaunch::JustRelaunch); } @@ -80,6 +249,27 @@ int Launcher::exec() { 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 { Expects(argc >= 0); @@ -170,6 +360,10 @@ QString Launcher::systemVersion() const { return _systemVersion; } +uint64 Launcher::installationTag() const { + return InstallationTag; +} + void Launcher::processArguments() { enum class KeyFormat { NoValues, @@ -243,10 +437,10 @@ void Launcher::processArguments() { } int Launcher::executeApplication() { - Application application(this, _argc, _argv); + Sandbox sandbox(this, _argc, _argv); MainQueueProcessor processor; base::ConcurrentTimerEnvironment environment; - return application.execute(); + return sandbox.start(); } } // namespace Core diff --git a/Telegram/SourceFiles/core/launcher.h b/Telegram/SourceFiles/core/launcher.h index df1b4836f..53f865aa1 100644 --- a/Telegram/SourceFiles/core/launcher.h +++ b/Telegram/SourceFiles/core/launcher.h @@ -27,6 +27,12 @@ public: // Thread safe. QString deviceModel() const; QString systemVersion() const; + uint64 installationTag() const; + + bool checkPortableVersionFolder(); + void workingFolderReady(); + void writeDebugModeSetting(); + void writeInstallBetaVersionsSetting(); virtual ~Launcher() = default; diff --git a/Telegram/SourceFiles/core/local_url_handlers.cpp b/Telegram/SourceFiles/core/local_url_handlers.cpp index 7916f05ea..719d4db66 100644 --- a/Telegram/SourceFiles/core/local_url_handlers.cpp +++ b/Telegram/SourceFiles/core/local_url_handlers.cpp @@ -23,7 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_session.h" #include "mainwindow.h" #include "mainwidget.h" -#include "messenger.h" +#include "core/application.h" #include "auth_session.h" #include "apiwrap.h" @@ -38,7 +38,7 @@ bool JoinGroupByHash(const Match &match, const QVariant &context) { } const auto hash = match->captured(1); Auth().api().checkChatInvite(hash, [=](const MTPChatInvite &result) { - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); result.match([=](const MTPDchatInvite &data) { Ui::show(Box(data, [=] { Auth().api().importChatInvite(hash); @@ -54,7 +54,7 @@ bool JoinGroupByHash(const Match &match, const QVariant &context) { if (error.code() != 400) { return; } - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); Ui::show(Box(lang(lng_group_invite_bad_link))); }); return true; @@ -64,7 +64,7 @@ bool ShowStickerSet(const Match &match, const QVariant &context) { if (!AuthSession::Exists()) { return false; } - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); Ui::show(Box( MTP_inputStickerSetShortName(MTP_string(match->captured(1))))); return true; @@ -310,4 +310,36 @@ const std::vector &LocalUrlHandlers() { 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 diff --git a/Telegram/SourceFiles/core/local_url_handlers.h b/Telegram/SourceFiles/core/local_url_handlers.h index c1084e522..e4f266fec 100644 --- a/Telegram/SourceFiles/core/local_url_handlers.h +++ b/Telegram/SourceFiles/core/local_url_handlers.h @@ -22,4 +22,8 @@ struct LocalUrlHandler { const std::vector &LocalUrlHandlers(); +bool InternalPassportLink(const QString &url); + +bool StartUrlRequiresActivate(const QString &url); + } // namespace Core diff --git a/Telegram/SourceFiles/core/main_queue_processor.cpp b/Telegram/SourceFiles/core/main_queue_processor.cpp index f316070eb..013733cf1 100644 --- a/Telegram/SourceFiles/core/main_queue_processor.cpp +++ b/Telegram/SourceFiles/core/main_queue_processor.cpp @@ -7,7 +7,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "core/main_queue_processor.h" -#include "application.h" +#include "core/sandbox.h" namespace Core { namespace { @@ -54,12 +54,12 @@ MainQueueProcessor::MainQueueProcessor() { if (ProcessorInstance) { const auto event = new ProcessorEvent(callable, argument); - QCoreApplication::postEvent(ProcessorInstance, event); + QApplication::postEvent(ProcessorInstance, event); } }); crl::wrap_main_queue([](void (*callable)(void*), void *argument) { - App().registerEnterFromEventLoop(); - const auto wrap = App().createEventNestingLevel(); + Sandbox::Instance().registerEnterFromEventLoop(); + const auto wrap = Sandbox::Instance().createEventNestingLevel(); callable(argument); }); diff --git a/Telegram/SourceFiles/application.cpp b/Telegram/SourceFiles/core/sandbox.cpp similarity index 64% rename from Telegram/SourceFiles/application.cpp rename to Telegram/SourceFiles/core/sandbox.cpp index 417e0b9b7..4f9ef1326 100644 --- a/Telegram/SourceFiles/application.cpp +++ b/Telegram/SourceFiles/core/sandbox.cpp @@ -5,7 +5,7 @@ the official desktop application for the Telegram messaging service. For license and copyright information please follow this link: https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ -#include "application.h" +#include "core/sandbox.h" #include "platform/platform_specific.h" #include "mainwidget.h" @@ -13,7 +13,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/localstorage.h" #include "window/notifications_manager.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/concurrent_timer.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/crash_report_window.h" +namespace Core { namespace { constexpr auto kEmptyPidForCommandResponse = 0ULL; +using ErrorSignal = void(QLocalSocket::*)(QLocalSocket::LocalSocketError); +const auto QLocalSocket_error = ErrorSignal(&QLocalSocket::error); + QChar _toHex(ushort v) { v = v & 0x000F; return QChar::fromLatin1((v >= 10) ? ('a' + (v - 10)) : ('0' + v)); @@ -65,48 +71,16 @@ QString _escapeFrom7bit(const QString &str) { } // namespace -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; +Sandbox::Sandbox( + not_null launcher, + int &argc, + char **argv) + : QApplication(argc, argv) + , _mainThreadId(QThread::currentThreadId()) + , _launcher(launcher) { } -bool StartUrlRequiresActivate(const QString &url) { - return Messenger::Instance().locked() - ? true - : !InternalPassportLink(url); -} - -Application::Application( - not_null launcher, - int &argc, - char **argv) -: QApplication(argc, argv) -, _mainThreadId(QThread::currentThreadId()) -, _launcher(launcher) { -} - -int Application::execute() { +int Sandbox::start() { if (!Core::UpdaterDisabled()) { _updateChecker = std::make_unique(); } @@ -120,37 +94,96 @@ int Application::execute() { _localServerName = psServerPrefix() + h; #endif // OS_MAC_STORE - connect(&_localSocket, SIGNAL(connected()), this, SLOT(socketConnected())); - connect(&_localSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); - connect(&_localSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError))); - connect(&_localSocket, SIGNAL(bytesWritten(qint64)), this, SLOT(socketWritten(qint64))); - connect(&_localSocket, SIGNAL(readyRead()), this, SLOT(socketReading())); - connect(&_localServer, SIGNAL(newConnection()), this, SLOT(newInstanceConnected())); + connect( + &_localSocket, + &QLocalSocket::connected, + [=] { socketConnected(); }); + connect( + &_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())); - connect(this, SIGNAL(aboutToQuit()), this, SLOT(closeApplication())); + crl::on_main(this, [=] { checkForQuit(); }); + connect( + this, + &QCoreApplication::aboutToQuit, + [=] { closeApplication(); }); if (cManyInstance()) { LOG(("Many instance allowed, starting...")); singleInstanceChecked(); } else { - LOG(("Connecting local socket to %1...").arg(_localServerName)); + LOG(("Connecting local socket to %1...").arg(_localServerName)); _localSocket.connectToServer(_localServerName); } 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) { App::quit(); } return QApplication::event(e); } -void Application::socketConnected() { +void Sandbox::socketConnected() { LOG(("Socket connected, this is not the first application instance, sending show command...")); _secondInstance = true; @@ -165,11 +198,11 @@ void Application::socketConnected() { 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()); } -void Application::socketWritten(qint64/* bytes*/) { +void Sandbox::socketWritten(qint64/* bytes*/) { if (_localSocket.state() != QLocalSocket::ConnectedState) { LOG(("Socket is not connected %1").arg(_localSocket.state())); return; @@ -180,7 +213,7 @@ void Application::socketWritten(qint64/* bytes*/) { LOG(("Show command written, waiting response...")); } -void Application::socketReading() { +void Sandbox::socketReading() { if (_localSocket.state() != QLocalSocket::ConnectedState) { LOG(("Socket is not connected %1").arg(_localSocket.state())); 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 (_secondInstance) { @@ -211,7 +244,7 @@ void Application::socketError(QLocalSocket::LocalSocketError e) { } _localSocket.close(); -// Local server does not work in WinRT build. + // Local server does not work in WinRT build. #ifndef Q_OS_WINRT psCheckLocalSocket(_localServerName); @@ -225,61 +258,78 @@ void Application::socketError(QLocalSocket::LocalSocketError e) { && !cNoStartUpdate() && Core::checkReadyUpdate()) { 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(); } singleInstanceChecked(); } -void Application::singleInstanceChecked() { +void Sandbox::singleInstanceChecked() { if (cManyInstance()) { Logs::multipleInstances(); } - Sandbox::start(); refreshGlobalProxy(); - if (!Logs::started() || (!cManyInstance() && !Logs::instanceChecked())) { new NotStartedWindow(); - } else { - const auto status = CrashReports::Start(); + return; + } + const auto result = CrashReports::Start(); + result.match([&](CrashReports::Status status) { if (status == CrashReports::CantOpen) { 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 { - 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) { - 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(); } } -void Application::newInstanceConnected() { - DEBUG_LOG(("Application Info: new local socket connected")); - for (QLocalSocket *client = _localServer.nextPendingConnection(); client; client = _localServer.nextPendingConnection()) { +void Sandbox::newInstanceConnected() { + DEBUG_LOG(("Sandbox Info: new local socket connected")); + for (auto client = _localServer.nextPendingConnection(); client; client = _localServer.nextPendingConnection()) { _localClients.push_back(LocalClient(client, QByteArray())); - connect(client, SIGNAL(readyRead()), this, SLOT(readClients())); - connect(client, SIGNAL(disconnected()), this, SLOT(removeClients())); + connect( + client, + &QLocalSocket::readyRead, + [=] { readClients(); }); + connect( + client, + &QLocalSocket::disconnected, + [=] { removeClients(); }); } } -void Application::readClients() { - // This method can be called before Messenger is constructed. +void Sandbox::readClients() { + // This method can be called before Application is constructed. QString startUrl; QStringList toSend; 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) { QStringRef cmd(&cmds, from, to - from); if (cmd.startsWith(qsl("CMD:"))) { - Sandbox::execExternal(cmds.mid(from + 4, to - from - 4)); - const auto response = qsl("RES:%1;").arg(QCoreApplication::applicationPid()).toLatin1(); + execExternal(cmds.mid(from + 4, to - from - 4)); + const auto response = qsl("RES:%1;").arg(QApplication::applicationPid()).toLatin1(); i->first->write(response.data(), response.size()); } else if (cmd.startsWith(qsl("SEND:"))) { if (cSendPaths().isEmpty()) { @@ -304,15 +354,15 @@ void Application::readClients() { activateRequired = StartUrlRequiresActivate(startUrl); } if (activateRequired) { - Sandbox::execExternal("show"); + execExternal("show"); } const auto responsePid = activateRequired - ? QCoreApplication::applicationPid() + ? QApplication::applicationPid() : kEmptyPidForCommandResponse; const auto response = qsl("RES:%1;").arg(responsePid).toLatin1(); i->first->write(response.data(), response.size()); } 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; } @@ -334,16 +384,17 @@ void Application::readClients() { if (!startUrl.isEmpty()) { cSetStartUrl(startUrl); } - if (auto messenger = Messenger::InstancePointer()) { - messenger->checkStartUrl(); + if (_application) { + _application->checkStartUrl(); } } -void Application::removeClients() { - DEBUG_LOG(("Application Info: remove clients slot called, clients %1").arg(_localClients.size())); - for (LocalClients::iterator i = _localClients.begin(), e = _localClients.end(); i != e;) { +void Sandbox::removeClients() { + DEBUG_LOG(("Sandbox Info: remove clients slot called, clients %1" + ).arg(_localClients.size())); + for (auto i = _localClients.begin(), e = _localClients.end(); i != e;) { if (i->first->state() != QLocalSocket::ConnectedState) { - DEBUG_LOG(("Application Info: removing client")); + DEBUG_LOG(("Sandbox Info: removing client")); i = _localClients.erase(i); e = _localClients.end(); } else { @@ -352,34 +403,33 @@ void Application::removeClients() { } } -void Application::startApplication() { +void Sandbox::checkForQuit() { if (App::quitting()) { quit(); } } -void Application::createMessenger() { +void Sandbox::runApplication() { Expects(!App::quitting()); - _messengerInstance = std::make_unique(_launcher); + _application = std::make_unique(_launcher); // 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 - // our filter after the Messenger constructor installs his. + // our filter after the Application constructor installs his. installNativeEventFilter(this); + + _application->run(); } -void Application::refreshGlobalProxy() { +void Sandbox::refreshGlobalProxy() { #ifndef TDESKTOP_DISABLE_NETWORK_PROXY - const auto proxy = [&] { - if (Global::started()) { - return (Global::ProxySettings() == ProxyData::Settings::Enabled) - ? Global::SelectedProxy() - : ProxyData(); - } - return Sandbox::PreLaunchProxy(); - }(); + const auto proxy = !Global::started() + ? _sandboxProxy + : (Global::ProxySettings() == ProxyData::Settings::Enabled) + ? Global::SelectedProxy() + : ProxyData(); if (proxy.type == ProxyData::Type::Socks5 || proxy.type == ProxyData::Type::Http) { QNetworkProxy::setApplicationProxy( @@ -393,7 +443,11 @@ void Application::refreshGlobalProxy() { #endif // TDESKTOP_DISABLE_NETWORK_PROXY } -void Application::postponeCall(FnMut &&callable) { +uint64 Sandbox::installationTag() const { + return _launcher->installationTag(); +} + +void Sandbox::postponeCall(FnMut &&callable) { Expects(callable != nullptr); Expects(_eventNestingLevel >= _loopNestingLevel); @@ -413,14 +467,14 @@ void Application::postponeCall(FnMut &&callable) { _postponedCalls.push_back({ _loopNestingLevel, std::move(callable) - }); + }); } -void Application::incrementEventNestingLevel() { +void Sandbox::incrementEventNestingLevel() { ++_eventNestingLevel; } -void Application::decrementEventNestingLevel() { +void Sandbox::decrementEventNestingLevel() { if (_eventNestingLevel == _loopNestingLevel) { _loopNestingLevel = _previousLoopNestingLevels.back(); _previousLoopNestingLevels.pop_back(); @@ -430,14 +484,14 @@ void Application::decrementEventNestingLevel() { _eventNestingLevel = processTillLevel; } -void Application::registerEnterFromEventLoop() { +void Sandbox::registerEnterFromEventLoop() { if (_eventNestingLevel > _loopNestingLevel) { _previousLoopNestingLevels.push_back(_loopNestingLevel); _loopNestingLevel = _eventNestingLevel; } } -bool Application::notify(QObject *receiver, QEvent *e) { +bool Sandbox::notify(QObject *receiver, QEvent *e) { if (QThread::currentThreadId() != _mainThreadId) { return QApplication::notify(receiver, e); } @@ -446,7 +500,7 @@ bool Application::notify(QObject *receiver, QEvent *e) { return QApplication::notify(receiver, e); } -void Application::processPostponedCalls(int level) { +void Sandbox::processPostponedCalls(int level) { while (!_postponedCalls.empty()) { auto &last = _postponedCalls.back(); if (last.loopNestingLevel != level) { @@ -458,15 +512,15 @@ void Application::processPostponedCalls(int level) { } } -bool Application::nativeEventFilter( - const QByteArray &eventType, - void *message, - long *result) { +bool Sandbox::nativeEventFilter( + const QByteArray &eventType, + void *message, + long *result) { registerEnterFromEventLoop(); return false; } -void Application::activateWindowDelayed(not_null widget) { +void Sandbox::activateWindowDelayed(not_null widget) { if (_delayedActivationsPaused) { return; } else if (std::exchange(_windowForDelayedActivation, widget.get())) { @@ -481,27 +535,30 @@ void Application::activateWindowDelayed(not_null widget) { }); } -void Application::pauseDelayedWindowActivations() { +void Sandbox::pauseDelayedWindowActivations() { _windowForDelayedActivation = nullptr; _delayedActivationsPaused = true; } -void Application::resumeDelayedWindowActivations() { +void Sandbox::resumeDelayedWindowActivations() { _delayedActivationsPaused = false; } -void Application::closeApplication() { - if (App::launchState() == App::QuitProcessed) return; +ProxyData Sandbox::sandboxProxy() const { + return _sandboxProxy; +} + +void Sandbox::closeApplication() { + if (App::launchState() == App::QuitProcessed) { + return; + } App::setLaunchState(App::QuitProcessed); - _messengerInstance.reset(); - - Sandbox::finish(); + _application = nullptr; _localServer.close(); - for (LocalClients::iterator i = _localClients.begin(), e = _localClients.end(); i != e; ++i) { - disconnect(i->first, SIGNAL(disconnected()), this, SLOT(removeClients())); - i->first->close(); + for (const auto &localClient : base::take(_localClients)) { + localClient.first->close(); } _localClients.clear(); @@ -510,10 +567,8 @@ void Application::closeApplication() { _updateChecker = nullptr; } -namespace Sandbox { - -void execExternal(const QString &cmd) { - DEBUG_LOG(("Application Info: executing external command '%1'").arg(cmd)); +void Sandbox::execExternal(const QString &cmd) { + DEBUG_LOG(("Sandbox Info: executing external command '%1'").arg(cmd)); if (cmd == "show") { if (App::wnd()) { App::wnd()->activate(); @@ -523,38 +578,4 @@ void execExternal(const QString &cmd) { } } -void launch() { - 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 +} // namespace Core diff --git a/Telegram/SourceFiles/application.h b/Telegram/SourceFiles/core/sandbox.h similarity index 66% rename from Telegram/SourceFiles/application.h rename to Telegram/SourceFiles/core/sandbox.h index 3e82601f4..89bc7d9e5 100644 --- a/Telegram/SourceFiles/application.h +++ b/Telegram/SourceFiles/core/sandbox.h @@ -8,23 +8,24 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #pragma once namespace Core { + class Launcher; class UpdateChecker; -} // namespace Core - -bool InternalPassportLink(const QString &url); -bool StartUrlRequiresActivate(const QString &url); - -class Application : public QApplication, private QAbstractNativeEventFilter { - Q_OBJECT +class Application; +class Sandbox final + : public QApplication + , private QAbstractNativeEventFilter { public: - Application(not_null launcher, int &argc, char **argv); + Sandbox(not_null launcher, int &argc, char **argv); - int execute(); + Sandbox(const Sandbox &other) = delete; + Sandbox &operator=(const Sandbox &other) = delete; + + int start(); - void createMessenger(); void refreshGlobalProxy(); + uint64 installationTag() const; void postponeCall(FnMut &&callable); bool notify(QObject *receiver, QEvent *e) override; @@ -38,22 +39,24 @@ public: void pauseDelayedWindowActivations(); void resumeDelayedWindowActivations(); - ~Application(); + ProxyData sandboxProxy() const; -// Single instance application -public slots: - void socketConnected(); - void socketError(QLocalSocket::LocalSocketError e); - void socketDisconnected(); - void socketWritten(qint64 bytes); - void socketReading(); - void newInstanceConnected(); + static Sandbox &Instance() { + Expects(QApplication::instance() != nullptr); - void readClients(); - void removeClients(); + return *static_cast(QApplication::instance()); + } - void startApplication(); // will be done in exec() - void closeApplication(); // will be done in aboutToQuit() + bool applicationLaunched() const { + return _application != nullptr; + } + Application &application() const { + Expects(_application != nullptr); + + return *_application; + } + + ~Sandbox(); protected: bool event(QEvent *e) override; @@ -67,6 +70,8 @@ private: FnMut callable; }; + void closeApplication(); // will be done in aboutToQuit() + void checkForQuit(); // will be done in exec() void incrementEventNestingLevel(); void decrementEventNestingLevel(); bool nativeEventFilter( @@ -74,6 +79,21 @@ private: void *message, long *result) override; 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; int _eventNestingLevel = 0; @@ -84,8 +104,8 @@ private: QPointer _windowForDelayedActivation; bool _delayedActivationsPaused = false; - not_null _launcher; - std::unique_ptr _messengerInstance; + not_null _launcher; + std::unique_ptr _application; QString _localServerName, _localSocketReadData; QLocalServer _localServer; @@ -93,26 +113,11 @@ private: LocalClients _localClients; bool _secondInstance = false; - void singleInstanceChecked(); + std::unique_ptr _updateChecker; -private: - std::unique_ptr _updateChecker; + QByteArray _lastCrashDump; + ProxyData _sandboxProxy; }; -namespace Core { - -inline Application &App() { - Expects(QCoreApplication::instance() != nullptr); - - return *static_cast(QCoreApplication::instance()); -} - } // namespace Core - -namespace Sandbox { - -void execExternal(const QString &cmd); -void launch(); - -} // namespace Sandbox diff --git a/Telegram/SourceFiles/core/shortcuts.cpp b/Telegram/SourceFiles/core/shortcuts.cpp index 697579f60..0a00d82b8 100644 --- a/Telegram/SourceFiles/core/shortcuts.cpp +++ b/Telegram/SourceFiles/core/shortcuts.cpp @@ -9,7 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwindow.h" #include "mainwidget.h" -#include "messenger.h" +#include "core/application.h" #include "media/player/media_player_instance.h" #include "platform/platform_specific.h" #include "base/parse_helper.h" @@ -371,7 +371,7 @@ void Manager::set(const QString &keys, Command command) { } auto shortcut = base::make_unique_q( result, - Messenger::Instance().getActiveWindow(), + Core::App().getActiveWindow(), nullptr, nullptr, Qt::ApplicationShortcut); diff --git a/Telegram/SourceFiles/core/update_checker.cpp b/Telegram/SourceFiles/core/update_checker.cpp index 34b6f5ae1..078f974f9 100644 --- a/Telegram/SourceFiles/core/update_checker.cpp +++ b/Telegram/SourceFiles/core/update_checker.cpp @@ -7,12 +7,12 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "core/update_checker.h" -#include "application.h" #include "platform/platform_specific.h" #include "base/timer.h" #include "base/bytes.h" #include "storage/localstorage.h" -#include "messenger.h" +#include "core/application.h" +#include "core/sandbox.h" #include "mainwindow.h" #include "core/click_handler_types.h" #include "info/info_memento.h" @@ -1187,7 +1187,7 @@ void Updater::stop() { } void Updater::start(bool forceWait) { - if (!Sandbox::started() || cExeName().isEmpty()) { + if (cExeName().isEmpty()) { return; } @@ -1382,8 +1382,8 @@ Updater::~Updater() { UpdateChecker::UpdateChecker() : _updater(GetUpdaterInstance()) { - if (const auto messenger = Messenger::InstancePointer()) { - if (const auto mtproto = messenger->mtp()) { + if (Sandbox::Instance().applicationLaunched()) { + if (const auto mtproto = Core::App().mtp()) { _updater->setMtproto(mtproto); } } diff --git a/Telegram/SourceFiles/data/data_document.cpp b/Telegram/SourceFiles/data/data_document.cpp index c0c442f2e..867ff2f63 100644 --- a/Telegram/SourceFiles/data/data_document.cpp +++ b/Telegram/SourceFiles/data/data_document.cpp @@ -27,7 +27,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/image/image_source.h" #include "auth_session.h" #include "mainwindow.h" -#include "messenger.h" +#include "core/application.h" namespace { @@ -299,7 +299,7 @@ void DocumentOpenClickHandler::Open( auto &location = data->location(true); if (data->isTheme()) { if (!location.isEmpty() && location.accessEnable()) { - Messenger::Instance().showDocument(data, context); + Core::App().showDocument(data, context); location.accessDisable(); return; } @@ -335,9 +335,9 @@ void DocumentOpenClickHandler::Open( } } else if (playVideo) { if (!data->data().isEmpty()) { - Messenger::Instance().showDocument(data, context); + Core::App().showDocument(data, context); } else if (location.accessEnable()) { - Messenger::Instance().showDocument(data, context); + Core::App().showDocument(data, context); location.accessDisable(); } else { const auto filepath = location.name(); @@ -357,14 +357,14 @@ void DocumentOpenClickHandler::Open( if (action == ActionOnLoadPlayInline && context) { data->session()->data().requestAnimationPlayInline(context); } else { - Messenger::Instance().showDocument(data, context); + Core::App().showDocument(data, context); } } else if (location.accessEnable()) { if (playAnimation || QImageReader(location.name()).canRead()) { if (playAnimation && action == ActionOnLoadPlayInline && context) { data->session()->data().requestAnimationPlayInline(context); } else { - Messenger::Instance().showDocument(data, context); + Core::App().showDocument(data, context); } } else { LaunchWithWarning(location.name(), context); @@ -720,7 +720,7 @@ void DocumentData::performActionOnLoad() { && item; if (auto applyTheme = isTheme()) { if (!loc.isEmpty() && loc.accessEnable()) { - Messenger::Instance().showDocument(this, item); + Core::App().showDocument(this, item); loc.accessDisable(); return; } @@ -760,7 +760,7 @@ void DocumentData::performActionOnLoad() { if (_actionOnLoad == ActionOnLoadPlayInline && item) { _session->data().requestAnimationPlayInline(item); } else { - Messenger::Instance().showDocument(this, item); + Core::App().showDocument(this, item); } } } else { @@ -776,7 +776,7 @@ void DocumentData::performActionOnLoad() { _session->data().markMediaRead(this); } else if (loc.accessEnable()) { if (showImage && QImageReader(loc.name()).canRead()) { - Messenger::Instance().showDocument(this, item); + Core::App().showDocument(this, item); } else { LaunchWithWarning(already, item); } diff --git a/Telegram/SourceFiles/data/data_peer.cpp b/Telegram/SourceFiles/data/data_peer.cpp index 329e948e1..1462ed3b5 100644 --- a/Telegram/SourceFiles/data/data_peer.cpp +++ b/Telegram/SourceFiles/data/data_peer.cpp @@ -20,7 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "apiwrap.h" #include "boxes/confirm_box.h" #include "auth_session.h" -#include "messenger.h" +#include "core/application.h" #include "mainwindow.h" #include "window/window_controller.h" #include "ui/image/image.h" @@ -315,7 +315,7 @@ void PeerData::clearUserpic() { const auto loc = StorageImageLocation(); const auto photo = [&] { if (id == peerFromUser(ServiceUserId)) { - auto image = Messenger::Instance().logoNoMargin().scaledToWidth( + auto image = Core::App().logoNoMargin().scaledToWidth( kUserpicSize, Qt::SmoothTransformation); return _userpic diff --git a/Telegram/SourceFiles/data/data_photo.cpp b/Telegram/SourceFiles/data/data_photo.cpp index 505044977..749f47cc5 100644 --- a/Telegram/SourceFiles/data/data_photo.cpp +++ b/Telegram/SourceFiles/data/data_photo.cpp @@ -13,7 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/image/image_source.h" #include "mainwidget.h" #include "auth_session.h" -#include "messenger.h" +#include "core/application.h" PhotoData::PhotoData(const PhotoId &id) : id(id) { @@ -167,7 +167,7 @@ void PhotoData::collectLocalData(PhotoData *local) { } void PhotoOpenClickHandler::onClickImpl() const { - Messenger::Instance().showPhoto(this); + Core::App().showPhoto(this); } void PhotoSaveClickHandler::onClickImpl() const { diff --git a/Telegram/SourceFiles/data/data_session.cpp b/Telegram/SourceFiles/data/data_session.cpp index 112e5188a..17a5f1cfb 100644 --- a/Telegram/SourceFiles/data/data_session.cpp +++ b/Telegram/SourceFiles/data/data_session.cpp @@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "observer_peer.h" #include "auth_session.h" #include "apiwrap.h" -#include "messenger.h" +#include "core/application.h" #include "core/crash_reports.h" // for CrashReports::SetAnnotation #include "ui/image/image.h" #include "export/export_controller.h" @@ -145,7 +145,7 @@ MTPPhotoSize FindDocumentThumb(const MTPDdocument &data) { Session::Session(not_null session) : _session(session) -, _cache(Messenger::Instance().databases().get( +, _cache(Core::App().databases().get( Local::cachePath(), Local::cacheSettings())) , _selfDestructTimer([=] { checkSelfDestructItems(); }) diff --git a/Telegram/SourceFiles/dialogs/dialogs_widget.cpp b/Telegram/SourceFiles/dialogs/dialogs_widget.cpp index 99a5cb3eb..a46aca9fb 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_widget.cpp +++ b/Telegram/SourceFiles/dialogs/dialogs_widget.cpp @@ -18,13 +18,12 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/wrap/fade_wrap.h" #include "ui/effects/radial_animation.h" #include "lang/lang_keys.h" -#include "application.h" #include "mainwindow.h" #include "mainwidget.h" #include "core/update_checker.h" #include "auth_session.h" #include "apiwrap.h" -#include "messenger.h" +#include "core/application.h" #include "boxes/peer_list_box.h" #include "boxes/peers/edit_participants_box.h" #include "window/window_controller.h" @@ -207,7 +206,7 @@ DialogsWidget::DialogsWidget(QWidget *parent, not_null cont subscribe(Global::RefLocalPasscodeChanged(), [this] { updateLockUnlockVisibility(); }); _lockUnlock->setClickedCallback([this] { _lockUnlock->setIconOverride(&st::dialogsUnlockIcon, &st::dialogsUnlockIconOver); - Messenger::Instance().lockByPasscode(); + Core::App().lockByPasscode(); _lockUnlock->setIconOverride(nullptr); }); _mainMenuToggle->setClickedCallback([this] { showMainMenu(); }); diff --git a/Telegram/SourceFiles/facades.cpp b/Telegram/SourceFiles/facades.cpp index b37afec81..631cd09eb 100644 --- a/Telegram/SourceFiles/facades.cpp +++ b/Telegram/SourceFiles/facades.cpp @@ -9,6 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "info/info_memento.h" #include "core/click_handler_types.h" +#include "core/application.h" #include "media/media_clip_reader.h" #include "window/window_controller.h" #include "history/history_item_components.h" @@ -18,7 +19,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwindow.h" #include "mainwidget.h" #include "apiwrap.h" -#include "messenger.h" #include "auth_session.h" #include "boxes/confirm_box.h" #include "window/layer_widget.h" @@ -34,7 +34,7 @@ namespace App { namespace internal { void CallDelayed(int duration, FnMut &&lambda) { - Messenger::Instance().callDelayed(duration, std::move(lambda)); + Core::App().callDelayed(duration, std::move(lambda)); } } // namespace internal @@ -153,7 +153,7 @@ void activateBotCommand( void searchByHashtag(const QString &tag, PeerData *inPeer) { if (const auto m = App::main()) { Ui::hideSettingsAndLayer(); - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); if (inPeer && (!inPeer->isChannel() || inPeer->isMegagroup())) { inPeer = nullptr; } @@ -271,7 +271,7 @@ void showPeerHistory(const PeerData *peer, MsgId msgId) { } PeerData *getPeerForMouseAction() { - return Messenger::Instance().ui_getPeerForMouseAction(); + return Core::App().ui_getPeerForMouseAction(); } bool skipPaintEvent(QWidget *widget, QPaintEvent *event) { @@ -346,220 +346,13 @@ void Set##Name(const Type &Name) { \ Namespace##Data->Name = Name; \ } -namespace Sandbox { -namespace internal { - -struct Data { - QByteArray LastCrashDump; - ProxyData PreLaunchProxy; -}; - -} // namespace internal -} // namespace Sandbox - -std::unique_ptr 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(&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(&SandboxUserTag), sizeof(uint64)); - usertag.close(); - } - } -} - -void WorkingDirReady() { - srand((int32)time(NULL)); - - ComputeTestMode(); - ComputeDebugMode(); - ComputeInstallBetaVersions(); - ComputeUserTag(); -} - -void start() { - SandboxData = std::make_unique(); -} - -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 internal { struct Data { - SingleQueuedInvokation HandleUnreadCounterUpdate = { [] { Messenger::Instance().call_handleUnreadCounterUpdate(); } }; - SingleQueuedInvokation HandleDelayedPeerUpdates = { [] { Messenger::Instance().call_handleDelayedPeerUpdates(); } }; - SingleQueuedInvokation HandleObservables = { [] { Messenger::Instance().call_handleObservables(); } }; + SingleQueuedInvokation HandleUnreadCounterUpdate = { [] { Core::App().call_handleUnreadCounterUpdate(); } }; + SingleQueuedInvokation HandleDelayedPeerUpdates = { [] { Core::App().call_handleDelayedPeerUpdates(); } }; + SingleQueuedInvokation HandleObservables = { [] { Core::App().call_handleObservables(); } }; Adaptive::WindowLayout AdaptiveWindowLayout = Adaptive::WindowLayout::Normal; Adaptive::ChatLayout AdaptiveChatLayout = Adaptive::ChatLayout::Normal; diff --git a/Telegram/SourceFiles/facades.h b/Telegram/SourceFiles/facades.h index 821d61be9..1aa9cdc32 100644 --- a/Telegram/SourceFiles/facades.h +++ b/Telegram/SourceFiles/facades.h @@ -175,24 +175,6 @@ inline bool IsTopCorner(ScreenCorner corner) { #define DeclareVar(Type, Name) DeclareRefVar(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 { enum class WindowLayout { diff --git a/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp b/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp index 92c97990e..a96db3652 100644 --- a/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp +++ b/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp @@ -23,7 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/sticker_set_box.h" #include "mainwindow.h" #include "mainwidget.h" -#include "messenger.h" +#include "core/application.h" #include "apiwrap.h" #include "layout.h" #include "window/window_controller.h" @@ -1125,7 +1125,7 @@ void InnerWidget::openContextGif(FullMsgId itemId) { if (const auto item = App::histItemById(itemId)) { if (auto media = item->media()) { if (auto document = media->document()) { - Messenger::Instance().showDocument(document, item); + Core::App().showDocument(document, item); } } } diff --git a/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp b/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp index 658be3dfb..0fabe9135 100644 --- a/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp +++ b/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp @@ -17,7 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_session.h" #include "lang/lang_keys.h" #include "boxes/sticker_set_box.h" -#include "messenger.h" +#include "core/application.h" #include "auth_session.h" namespace AdminLog { @@ -434,10 +434,10 @@ void GenerateItems( auto bodyFlags = Flag::f_entities | Flag::f_from_id; auto bodyReplyTo = 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); 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); } addPart(body); diff --git a/Telegram/SourceFiles/history/history.cpp b/Telegram/SourceFiles/history/history.cpp index c830e2bb2..8d425b013 100644 --- a/Telegram/SourceFiles/history/history.cpp +++ b/Telegram/SourceFiles/history/history.cpp @@ -21,7 +21,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_keys.h" #include "apiwrap.h" #include "mainwidget.h" -#include "application.h" #include "mainwindow.h" #include "storage/localstorage.h" #include "observer_peer.h" diff --git a/Telegram/SourceFiles/history/history_inner_widget.cpp b/Telegram/SourceFiles/history/history_inner_widget.cpp index 01aea3b82..224d2aab5 100644 --- a/Telegram/SourceFiles/history/history_inner_widget.cpp +++ b/Telegram/SourceFiles/history/history_inner_widget.cpp @@ -37,7 +37,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwidget.h" #include "layout.h" #include "auth_session.h" -#include "messenger.h" +#include "core/application.h" #include "apiwrap.h" #include "lang/lang_keys.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 media = item->media()) { if (const auto document = media->document()) { - Messenger::Instance().showDocument(document, item); + Core::App().showDocument(document, item); } } } diff --git a/Telegram/SourceFiles/history/history_item.cpp b/Telegram/SourceFiles/history/history_item.cpp index e82b6dac3..60f1b4d96 100644 --- a/Telegram/SourceFiles/history/history_item.cpp +++ b/Telegram/SourceFiles/history/history_item.cpp @@ -27,7 +27,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "auth_session.h" #include "apiwrap.h" #include "media/media_audio.h" -#include "messenger.h" +#include "core/application.h" #include "mainwindow.h" #include "window/window_controller.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(); } diff --git a/Telegram/SourceFiles/history/history_message.cpp b/Telegram/SourceFiles/history/history_message.cpp index 1620bb131..7e205db21 100644 --- a/Telegram/SourceFiles/history/history_message.cpp +++ b/Telegram/SourceFiles/history/history_message.cpp @@ -21,7 +21,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/confirm_box.h" #include "ui/toast/toast.h" #include "ui/text_options.h" -#include "messenger.h" +#include "core/application.h" #include "layout.h" #include "window/notifications_manager.h" #include "window/window_controller.h" @@ -109,7 +109,7 @@ void FastShareMessage(not_null item) { } else if (const auto bot = item->getMessageBot()) { if (const auto media = item->media()) { if (const auto game = media->game()) { - const auto link = Messenger::Instance().createInternalLinkFull( + const auto link = Core::App().createInternalLinkFull( bot->username + qsl("?game=") + game->shortName); diff --git a/Telegram/SourceFiles/history/history_widget.cpp b/Telegram/SourceFiles/history/history_widget.cpp index 671f34754..1b1940dc0 100644 --- a/Telegram/SourceFiles/history/history_widget.cpp +++ b/Telegram/SourceFiles/history/history_widget.cpp @@ -52,7 +52,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "chat_helpers/bot_keyboard.h" #include "chat_helpers/message_field.h" #include "lang/lang_keys.h" -#include "application.h" #include "mainwidget.h" #include "mainwindow.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_capture.h" #include "media/player/media_player_instance.h" -#include "messenger.h" +#include "core/application.h" #include "apiwrap.h" #include "history/view/history_view_top_bar_widget.h" #include "observer_peer.h" @@ -6145,7 +6144,7 @@ void HistoryWidget::updateTopBarSelection() { _topBar->showSelected(selectedState); updateControlsVisibility(); updateHistoryGeometry(); - if (!Ui::isLayerShown() && !Messenger::Instance().locked()) { + if (!Ui::isLayerShown() && !Core::App().locked()) { if (_nonEmptySelection || (_list && _list->wasSelectedText()) || _recording diff --git a/Telegram/SourceFiles/history/view/history_view_context_menu.cpp b/Telegram/SourceFiles/history/view/history_view_context_menu.cpp index 417e195d4..1c3a57c00 100644 --- a/Telegram/SourceFiles/history/view/history_view_context_menu.cpp +++ b/Telegram/SourceFiles/history/view/history_view_context_menu.cpp @@ -29,7 +29,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/file_utilities.h" #include "window/window_peer_menu.h" #include "lang/lang_keys.h" -#include "messenger.h" +#include "core/application.h" #include "mainwidget.h" #include "auth_session.h" #include "apiwrap.h" @@ -54,7 +54,7 @@ void SavePhotoToFile(not_null photo) { } FileDialog::GetWritePath( - Messenger::Instance().getFileDialogParent(), + Core::App().getFileDialogParent(), lang(lng_save_photo), qsl("JPEG Image (*.jpg);;") + FileDialog::AllFilesFilter(), filedialogDefaultName(qsl("photo"), qsl(".jpg")), @@ -104,7 +104,7 @@ void OpenGif(FullMsgId itemId) { if (const auto item = App::histItemById(itemId)) { if (const auto media = item->media()) { if (const auto document = media->document()) { - Messenger::Instance().showDocument(document, item); + Core::App().showDocument(document, item); } } } diff --git a/Telegram/SourceFiles/history/view/history_view_list_widget.cpp b/Telegram/SourceFiles/history/view/history_view_list_widget.cpp index fcc962072..b9f57ff3b 100644 --- a/Telegram/SourceFiles/history/view/history_view_list_widget.cpp +++ b/Telegram/SourceFiles/history/view/history_view_list_widget.cpp @@ -20,7 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "chat_helpers/message_field.h" #include "mainwindow.h" #include "mainwidget.h" -#include "messenger.h" +#include "core/application.h" #include "apiwrap.h" #include "layout.h" #include "window/window_controller.h" diff --git a/Telegram/SourceFiles/info/profile/info_profile_actions.cpp b/Telegram/SourceFiles/info/profile/info_profile_actions.cpp index ed27dfbf1..74adea552 100644 --- a/Telegram/SourceFiles/info/profile/info_profile_actions.cpp +++ b/Telegram/SourceFiles/info/profile/info_profile_actions.cpp @@ -38,7 +38,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/window_peer_menu.h" #include "mainwidget.h" #include "auth_session.h" -#include "messenger.h" +#include "core/application.h" #include "apiwrap.h" #include "styles/style_info.h" #include "styles/style_boxes.h" @@ -289,7 +289,7 @@ object_ptr DetailsFiller::setupInfo() { std::move(linkText), QString()); link->setClickHandlerFilter([peer = _peer](auto&&...) { - auto link = Messenger::Instance().createInternalLinkFull( + auto link = Core::App().createInternalLinkFull( peer->userName()); if (!link.isEmpty()) { QApplication::clipboard()->setText(link); diff --git a/Telegram/SourceFiles/info/profile/info_profile_cover.cpp b/Telegram/SourceFiles/info/profile/info_profile_cover.cpp index 6526dd49b..14175d840 100644 --- a/Telegram/SourceFiles/info/profile/info_profile_cover.cpp +++ b/Telegram/SourceFiles/info/profile/info_profile_cover.cpp @@ -23,7 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/special_buttons.h" #include "window/window_controller.h" #include "observer_peer.h" -#include "messenger.h" +#include "core/application.h" #include "auth_session.h" #include "apiwrap.h" diff --git a/Telegram/SourceFiles/info/profile/info_profile_values.cpp b/Telegram/SourceFiles/info/profile/info_profile_values.cpp index 0d628298b..9164aa965 100644 --- a/Telegram/SourceFiles/info/profile/info_profile_values.cpp +++ b/Telegram/SourceFiles/info/profile/info_profile_values.cpp @@ -12,7 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include #include #include "observer_peer.h" -#include "messenger.h" +#include "core/application.h" #include "auth_session.h" #include "ui/wrap/slide_wrap.h" #include "data/data_peer_values.h" @@ -110,7 +110,7 @@ rpl::producer LinkValue(not_null peer) { ) | rpl::map([](QString &&username) { return username.isEmpty() ? QString() - : Messenger::Instance().createInternalLinkFull(username); + : Core::App().createInternalLinkFull(username); }); } diff --git a/Telegram/SourceFiles/intro/introcode.cpp b/Telegram/SourceFiles/intro/introcode.cpp index e8c63f0d0..f1bda9383 100644 --- a/Telegram/SourceFiles/intro/introcode.cpp +++ b/Telegram/SourceFiles/intro/introcode.cpp @@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "intro/introcode.h" #include "lang/lang_keys.h" -#include "application.h" #include "intro/introsignup.h" #include "intro/intropwdcheck.h" #include "core/update_checker.h" diff --git a/Telegram/SourceFiles/intro/introphone.cpp b/Telegram/SourceFiles/intro/introphone.cpp index 67b2714b9..2f64118e8 100644 --- a/Telegram/SourceFiles/intro/introphone.cpp +++ b/Telegram/SourceFiles/intro/introphone.cpp @@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "intro/introphone.h" #include "lang/lang_keys.h" -#include "application.h" #include "intro/introcode.h" #include "styles/style_intro.h" #include "ui/widgets/buttons.h" @@ -18,7 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/confirm_box.h" #include "base/qthelp_url.h" #include "platform/platform_specific.h" -#include "messenger.h" +#include "core/application.h" namespace Intro { namespace { @@ -83,7 +82,7 @@ PhoneWidget::PhoneWidget(QWidget *parent, Widget::Data *data) : Step(parent, dat } _changed = false; - Messenger::Instance().destroyStaleAuthorizationKeys(); + Core::App().destroyStaleAuthorizationKeys(); } void PhoneWidget::resizeEvent(QResizeEvent *e) { @@ -157,7 +156,7 @@ void PhoneWidget::submit() { _checkRequest->start(1000); _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_SendCode( diff --git a/Telegram/SourceFiles/intro/intropwdcheck.cpp b/Telegram/SourceFiles/intro/intropwdcheck.cpp index 2ce5011a9..c10f69cc3 100644 --- a/Telegram/SourceFiles/intro/intropwdcheck.cpp +++ b/Telegram/SourceFiles/intro/intropwdcheck.cpp @@ -13,7 +13,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/core_cloud_password.h" #include "boxes/confirm_box.h" #include "lang/lang_keys.h" -#include "application.h" #include "intro/introsignup.h" #include "ui/widgets/buttons.h" #include "ui/widgets/input_fields.h" diff --git a/Telegram/SourceFiles/intro/introsignup.cpp b/Telegram/SourceFiles/intro/introsignup.cpp index 0b5ba9849..f214da5ba 100644 --- a/Telegram/SourceFiles/intro/introsignup.cpp +++ b/Telegram/SourceFiles/intro/introsignup.cpp @@ -13,7 +13,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/photo_crop_box.h" #include "boxes/confirm_box.h" #include "lang/lang_keys.h" -#include "application.h" #include "ui/widgets/buttons.h" #include "ui/widgets/input_fields.h" #include "ui/widgets/labels.h" diff --git a/Telegram/SourceFiles/intro/introstart.cpp b/Telegram/SourceFiles/intro/introstart.cpp index 3d90ca697..9de68067c 100644 --- a/Telegram/SourceFiles/intro/introstart.cpp +++ b/Telegram/SourceFiles/intro/introstart.cpp @@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "intro/introstart.h" #include "lang/lang_keys.h" -#include "application.h" #include "intro/introphone.h" #include "ui/widgets/buttons.h" #include "ui/widgets/labels.h" diff --git a/Telegram/SourceFiles/intro/introwidget.cpp b/Telegram/SourceFiles/intro/introwidget.cpp index 5176ff276..62e88b323 100644 --- a/Telegram/SourceFiles/intro/introwidget.cpp +++ b/Telegram/SourceFiles/intro/introwidget.cpp @@ -18,8 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwidget.h" #include "apiwrap.h" #include "mainwindow.h" -#include "messenger.h" -#include "application.h" +#include "core/application.h" #include "boxes/confirm_box.h" #include "ui/text/text.h" #include "ui/widgets/buttons.h" @@ -394,7 +393,7 @@ void Widget::getNearestDC() { ).arg(qs(nearest.vcountry) ).arg(nearest.vnearest_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); if (getData()->country != nearestCountry) { getData()->country = nearestCountry; @@ -628,7 +627,7 @@ void Widget::Step::finish(const MTPUser &user, QImage &&photo) { Local::writeLangPack(); } - Messenger::Instance().authSessionCreate(user); + Core::App().authSessionCreate(user); Local::writeMtpData(); App::wnd()->setupMain(); diff --git a/Telegram/SourceFiles/lang/lang_cloud_manager.cpp b/Telegram/SourceFiles/lang/lang_cloud_manager.cpp index ca5b38f42..cd0a9bd18 100644 --- a/Telegram/SourceFiles/lang/lang_cloud_manager.cpp +++ b/Telegram/SourceFiles/lang/lang_cloud_manager.cpp @@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_instance.h" #include "mtproto/mtp_instance.h" #include "storage/localstorage.h" -#include "messenger.h" +#include "core/application.h" #include "apiwrap.h" #include "auth_session.h" #include "boxes/confirm_box.h" @@ -514,7 +514,7 @@ void CloudManager::switchToLanguage(const Language &data) { void CloudManager::performSwitchToCustom() { auto filter = qsl("Language files (*.strings)"); 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()) { return; } @@ -605,7 +605,7 @@ void CloudManager::changeIdAndReInitConnection(const Language &data) { } CloudManager &CurrentCloudManager() { - auto result = Messenger::Instance().langCloudManager(); + auto result = Core::App().langCloudManager(); Assert(result != nullptr); return *result; } diff --git a/Telegram/SourceFiles/lang/lang_instance.cpp b/Telegram/SourceFiles/lang/lang_instance.cpp index 8d1fc347e..7824ac0b5 100644 --- a/Telegram/SourceFiles/lang/lang_instance.cpp +++ b/Telegram/SourceFiles/lang/lang_instance.cpp @@ -7,7 +7,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "lang/lang_instance.h" -#include "messenger.h" +#include "core/application.h" #include "storage/serialize_common.h" #include "storage/localstorage.h" #include "platform/platform_specific.h" @@ -777,7 +777,7 @@ void Instance::resetValue(const QByteArray &key) { } Instance &Current() { - return Messenger::Instance().langpack(); + return Core::App().langpack(); } rpl::producer Viewer(LangKey key) { diff --git a/Telegram/SourceFiles/layout.cpp b/Telegram/SourceFiles/layout.cpp index f5e8bf424..ef9bafd7e 100644 --- a/Telegram/SourceFiles/layout.cpp +++ b/Telegram/SourceFiles/layout.cpp @@ -10,7 +10,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_document.h" #include "lang/lang_keys.h" #include "mainwidget.h" -#include "application.h" #include "storage/file_upload.h" #include "mainwindow.h" #include "core/file_utilities.h" diff --git a/Telegram/SourceFiles/logs.cpp b/Telegram/SourceFiles/logs.cpp index ed2c7ce76..84c9af066 100644 --- a/Telegram/SourceFiles/logs.cpp +++ b/Telegram/SourceFiles/logs.cpp @@ -233,7 +233,7 @@ NEW LOGGING INSTANCE STARTED!!!\n\ LogsDataFields *LogsData = 0; -typedef QList > LogsInMemoryList; +using LogsInMemoryList = QList>; LogsInMemoryList *LogsInMemory = 0; LogsInMemoryList *DeletedLogsInMemory = SharedMemoryLocation(); @@ -320,9 +320,9 @@ bool DebugEnabled() { } void start(not_null launcher) { - Assert(LogsData == 0); + Assert(LogsData == nullptr); - if (!Sandbox::CheckPortableVersionDir()) { + if (!launcher->checkPortableVersionFolder()) { return; } @@ -394,12 +394,12 @@ void start(not_null launcher) { QDir().mkpath(cWorkingDir() + qstr("tdata")); - Sandbox::WorkingDirReady(); - CrashReports::StartCatching(); + launcher->workingFolderReady(); + CrashReports::StartCatching(launcher); if (!LogsData->openMain()) { delete LogsData; - LogsData = 0; + LogsData = nullptr; } LOG(("Launched version: %1, " diff --git a/Telegram/SourceFiles/mainwidget.cpp b/Telegram/SourceFiles/mainwidget.cpp index ffe31f940..6df3accc3 100644 --- a/Telegram/SourceFiles/mainwidget.cpp +++ b/Telegram/SourceFiles/mainwidget.cpp @@ -25,9 +25,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/special_buttons.h" #include "ui/widgets/buttons.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/widgets/dropdown_menu.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/text_options.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/stickers.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 "boxes/add_contact_box.h" #include "storage/file_upload.h" -#include "messenger.h" -#include "application.h" #include "mainwindow.h" #include "inline_bots/inline_bot_layout_item.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/update_checker.h" #include "core/shortcuts.h" +#include "core/application.h" #include "calls/calls_instance.h" #include "calls/calls_top_bar.h" #include "export/export_settings.h" @@ -374,9 +373,6 @@ MainWidget::MainWidget( , _failDifferenceTimer([=] { getDifferenceAfterFail(); }) , _cacheBackgroundTimer([=] { cacheBackground(); }) , _viewsIncrementTimer([=] { viewsIncrement(); }) { - Messenger::Instance().mtp()->setUpdatesHandler(rpcDone(&MainWidget::updateReceived)); - Messenger::Instance().mtp()->setGlobalFailHandler(rpcFail(&MainWidget::updateFail)); - _controller->setDefaultFloatPlayerDelegate(floatPlayerDelegate()); _controller->floatPlayerClosed( ) | rpl::start_with_next([=](FullMsgId itemId) { @@ -786,7 +782,7 @@ void MainWidget::clearHider(not_null instance) { } void MainWidget::hiderLayer(base::unique_qptr hider) { - if (Messenger::Instance().locked()) { + if (Core::App().locked()) { return; } @@ -1044,7 +1040,7 @@ bool MainWidget::sendMessageFail(const RPCError &error) { return true; } else if (error.type() == qstr("USER_BANNED_IN_CHANNEL")) { const auto link = textcmdLink( - Messenger::Instance().createInternalLinkFull(qsl("spambot")), + Core::App().createInternalLinkFull(qsl("spambot")), lang(lng_cant_more_info)); const auto text = lng_error_public_groups_denied(lt_more_info, link); Ui::show(Box(text)); @@ -1838,7 +1834,7 @@ void MainWidget::ui_showPeerHistory( auto animatedShow = [&] { if (_a_show.animating() - || Messenger::Instance().locked() + || Core::App().locked() || (params.animated == anim::type::instant)) { return false; } @@ -2147,7 +2143,7 @@ void MainWidget::showNewSection( auto animatedShow = [&] { if (_a_show.animating() - || Messenger::Instance().locked() + || Core::App().locked() || (params.animated == anim::type::instant) || memento.instant()) { return false; @@ -3039,11 +3035,6 @@ void MainWidget::feedMessageIds(const MTPVector &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) { if (pts) { _ptsWaiter.init(pts); @@ -3451,7 +3442,7 @@ void MainWidget::start() { _history->start(); - Messenger::Instance().checkStartUrl(); + Core::App().checkStartUrl(); } bool MainWidget::started() { @@ -3463,7 +3454,7 @@ void MainWidget::openPeerByName( MsgId msgId, const QString &startToken, FullMsgId clickFromMessageId) { - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); if (const auto peer = session().data().peerByUsername(username)) { if (msgId == ShowAtGameShareMsgId) { @@ -3753,9 +3744,9 @@ int32 MainWidget::dlgsWidth() const { } MainWidget::~MainWidget() { - if (App::main() == this) _history->showHistory(0, 0); - - Messenger::Instance().mtp()->clearGlobalHandlers(); + if (App::main() == this) { + _history->showHistory(0, 0); + } } void MainWidget::updateOnline(bool gotOtherOffline) { @@ -4398,11 +4389,11 @@ void MainWidget::feedUpdate(const MTPUpdate &update) { case mtpc_updateDcOptions: { auto &d = update.c_updateDcOptions(); - Messenger::Instance().dcOptions()->addFromList(d.vdc_options); + Core::App().dcOptions()->addFromList(d.vdc_options); } break; case mtpc_updateConfig: { - Messenger::Instance().mtp()->requestConfig(); + Core::App().mtp()->requestConfig(); } break; case mtpc_updateUserPhone: { @@ -4463,7 +4454,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) { TextUtilities::EntitiesFromMTP(d.ventities.v) }; if (IsForceLogoutNotification(d)) { - Messenger::Instance().forceLogOut(text); + Core::App().forceLogOut(text); } else if (d.is_popup()) { Ui::show(Box(text)); } else { diff --git a/Telegram/SourceFiles/mainwidget.h b/Telegram/SourceFiles/mainwidget.h index 1b381cc21..798752672 100644 --- a/Telegram/SourceFiles/mainwidget.h +++ b/Telegram/SourceFiles/mainwidget.h @@ -120,6 +120,7 @@ public: void incrementSticker(DocumentData *sticker); void activate(); + void updateReceived(const mtpPrime *from, const mtpPrime *end); void createDialog(Dialogs::Key key); void removeDialog(Dialogs::Key key); @@ -415,9 +416,6 @@ private: void deleteHistoryPart(DeleteHistoryRequest request, const MTPmessages_AffectedHistory &result); - void updateReceived(const mtpPrime *from, const mtpPrime *end); - bool updateFail(const RPCError &e); - void usernameResolveDone(QPair msgIdAndStartToken, const MTPcontacts_ResolvedPeer &result); bool usernameResolveFail(QString name, const RPCError &error); diff --git a/Telegram/SourceFiles/mainwindow.cpp b/Telegram/SourceFiles/mainwindow.cpp index 1e90896d1..3a6a62863 100644 --- a/Telegram/SourceFiles/mainwindow.cpp +++ b/Telegram/SourceFiles/mainwindow.cpp @@ -22,9 +22,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_instance.h" #include "lang/lang_keys.h" #include "core/shortcuts.h" -#include "messenger.h" +#include "core/sandbox.h" +#include "core/application.h" #include "auth_session.h" -#include "application.h" #include "intro/introwidget.h" #include "mainwidget.h" #include "boxes/confirm_box.h" @@ -66,12 +66,12 @@ void FeedLangTestingKey(int key) { } // namespace MainWindow::MainWindow() { - auto logo = Messenger::Instance().logo(); + auto logo = Core::App().logo(); icon16 = logo.scaledToWidth(16, Qt::SmoothTransformation); icon32 = logo.scaledToWidth(32, Qt::SmoothTransformation); icon64 = logo.scaledToWidth(64, Qt::SmoothTransformation); - auto logoNoMargin = Messenger::Instance().logoNoMargin(); + auto logoNoMargin = Core::App().logoNoMargin(); iconbig16 = logoNoMargin.scaledToWidth(16, Qt::SmoothTransformation); iconbig32 = logoNoMargin.scaledToWidth(32, Qt::SmoothTransformation); iconbig64 = logoNoMargin.scaledToWidth(64, Qt::SmoothTransformation); @@ -80,7 +80,7 @@ MainWindow::MainWindow() { setLocale(QLocale(QLocale::English, QLocale::UnitedStates)); - subscribe(Messenger::Instance().authSessionChanged(), [this] { + subscribe(Core::App().authSessionChanged(), [this] { updateGlobalMenu(); if (!AuthSession::Exists()) { _mediaPreview.destroy(); @@ -89,7 +89,7 @@ MainWindow::MainWindow() { subscribe(Window::Theme::Background(), [this](const Window::Theme::BackgroundUpdate &data) { themeUpdated(data); }); - Messenger::Instance().lockChanges( + Core::App().lockChanges( ) | rpl::start_with_next([=] { updateGlobalMenu(); }, lifetime()); @@ -164,7 +164,7 @@ void MainWindow::setupPasscodeLock() { _passcodeLock.create(bodyWidget()); updateControlsGeometry(); - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); Ui::hideSettingsAndLayer(anim::type::instant); if (_main) { _main->hide(); @@ -189,9 +189,9 @@ void MainWindow::clearPasscodeLock() { _intro->showAnimated(bg, true); } else if (_main) { _main->showAnimated(bg, true); - Messenger::Instance().checkStartUrl(); + Core::App().checkStartUrl(); } else { - Messenger::Instance().startMtp(); + Core::App().startMtp(); if (AuthSession::Exists()) { setupMain(); } else { @@ -350,7 +350,7 @@ void MainWindow::ui_showBox( destroyLayer(); } } - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); } } @@ -595,7 +595,7 @@ void MainWindow::onLogout() { } const auto logout = [] { - Messenger::Instance().logOut(); + Core::App().logOut(); }; const auto callback = [=] { if (AuthSession::Exists() && Auth().data().exportInProgress()) { @@ -680,7 +680,7 @@ bool MainWindow::skipTrayClick() const { } void MainWindow::toggleDisplayNotifyFromTray() { - if (Messenger::Instance().locked()) { + if (Core::App().locked()) { if (!isActive()) showFromTray(); Ui::show(Box(lang(lng_passcode_need_unblock))); return; @@ -714,7 +714,7 @@ void MainWindow::toggleDisplayNotifyFromTray() { } void MainWindow::closeEvent(QCloseEvent *e) { - if (Core::App().isSavingSession()) { + if (Core::Sandbox::Instance().isSavingSession()) { e->accept(); App::quit(); } else { @@ -896,10 +896,10 @@ QImage MainWindow::iconWithCounter(int size, int count, style::color bg, style:: } void MainWindow::sendPaths() { - if (Messenger::Instance().locked()) { + if (Core::App().locked()) { return; } - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); Ui::hideSettingsAndLayer(anim::type::instant); if (_main) { _main->activate(); diff --git a/Telegram/SourceFiles/media/media_audio.cpp b/Telegram/SourceFiles/media/media_audio.cpp index 2832e9af8..cb0cacb39 100644 --- a/Telegram/SourceFiles/media/media_audio.cpp +++ b/Telegram/SourceFiles/media/media_audio.cpp @@ -14,7 +14,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "media/media_audio_loaders.h" #include "media/media_audio_track.h" #include "platform/platform_audio.h" -#include "messenger.h" +#include "core/application.h" #include "facades.h" #include @@ -262,7 +262,7 @@ bool AttachToDevice() { } crl::on_main([] { - if (Messenger::InstancePointer()) { + if (!App::quitting()) { Current().reattachTracks(); } }); @@ -271,7 +271,7 @@ bool AttachToDevice() { void ScheduleDetachFromDeviceSafe() { crl::on_main([] { - if (Messenger::InstancePointer()) { + if (!App::quitting()) { Current().scheduleDetachFromDevice(); } }); @@ -279,7 +279,7 @@ void ScheduleDetachFromDeviceSafe() { void ScheduleDetachIfNotUsedSafe() { crl::on_main([] { - if (Messenger::InstancePointer()) { + if (!App::quitting()) { Current().scheduleDetachIfNotUsed(); } }); @@ -287,7 +287,7 @@ void ScheduleDetachIfNotUsedSafe() { void StopDetachIfNotUsedSafe() { crl::on_main([] { - if (Messenger::InstancePointer()) { + if (!App::quitting()) { Current().stopDetachIfNotUsed(); } }); diff --git a/Telegram/SourceFiles/media/media_audio_track.cpp b/Telegram/SourceFiles/media/media_audio_track.cpp index e31b75c2e..d62acd737 100644 --- a/Telegram/SourceFiles/media/media_audio_track.cpp +++ b/Telegram/SourceFiles/media/media_audio_track.cpp @@ -9,7 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "media/media_audio_ffmpeg_loader.h" #include "media/media_audio.h" -#include "messenger.h" +#include "core/application.h" #include #include @@ -339,7 +339,7 @@ void Instance::stopDetachIfNotUsed() { } Instance &Current() { - return Messenger::Instance().audio(); + return Core::App().audio(); } } // namespace Audio diff --git a/Telegram/SourceFiles/media/player/media_player_instance.cpp b/Telegram/SourceFiles/media/player/media_player_instance.cpp index 5ace3395a..63556c596 100644 --- a/Telegram/SourceFiles/media/player/media_player_instance.cpp +++ b/Telegram/SourceFiles/media/player/media_player_instance.cpp @@ -18,7 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_file_origin.h" #include "window/window_controller.h" #include "core/shortcuts.h" -#include "messenger.h" +#include "core/application.h" #include "mainwindow.h" #include "auth_session.h" @@ -74,7 +74,7 @@ Instance::Instance() } }; subscribe( - Messenger::Instance().authSessionChanged(), + Core::App().authSessionChanged(), handleAuthSessionChange); handleAuthSessionChange(); diff --git a/Telegram/SourceFiles/mediaview.cpp b/Telegram/SourceFiles/mediaview.cpp index 64c465f37..591b2e44d 100644 --- a/Telegram/SourceFiles/mediaview.cpp +++ b/Telegram/SourceFiles/mediaview.cpp @@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_keys.h" #include "mainwidget.h" #include "mainwindow.h" -#include "application.h" +#include "core/application.h" #include "core/file_utilities.h" #include "core/mime_type.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 "observer_peer.h" #include "auth_session.h" -#include "messenger.h" #include "layout.h" #include "storage/file_download.h" #include "calls/calls_instance.h" @@ -133,7 +132,7 @@ MediaView::MediaView() _collage = nullptr; } }; - subscribe(Messenger::Instance().authSessionChanged(), [handleAuthSessionChange] { + subscribe(Core::App().authSessionChanged(), [handleAuthSessionChange] { handleAuthSessionChange(); }); handleAuthSessionChange(); @@ -184,7 +183,7 @@ void MediaView::moveToScreen() { } return nullptr; }; - auto activeWindow = Messenger::Instance().getActiveWindow(); + auto activeWindow = Core::App().getActiveWindow(); auto activeWindowScreen = widgetScreen(activeWindow); auto myScreen = widgetScreen(this); if (activeWindowScreen && myScreen && myScreen != activeWindowScreen) { @@ -751,7 +750,7 @@ void MediaView::updateMixerVideoVolume() const { } void MediaView::close() { - Messenger::Instance().hideMediaView(); + Core::App().hideMediaView(); } void MediaView::activateControls() { @@ -906,7 +905,7 @@ void MediaView::onSaveAs() { })); } activateWindow(); - Core::App().setActiveWindow(this); + QApplication::setActiveWindow(this); setFocus(); } @@ -1777,7 +1776,7 @@ void MediaView::displayFinished() { show(); psShowOverAll(this); activateWindow(); - Core::App().setActiveWindow(this); + QApplication::setActiveWindow(this); setFocus(); } } diff --git a/Telegram/SourceFiles/mtproto/connection.cpp b/Telegram/SourceFiles/mtproto/connection.cpp index 2c90a9940..bdbc87fcc 100644 --- a/Telegram/SourceFiles/mtproto/connection.cpp +++ b/Telegram/SourceFiles/mtproto/connection.cpp @@ -13,7 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mtproto/dc_options.h" #include "mtproto/connection_abstract.h" #include "zlib.h" -#include "messenger.h" +#include "core/application.h" #include "core/launcher.h" #include "lang/lang_keys.h" #include "base/openssl_help.h" @@ -820,10 +820,10 @@ void ConnectionPrivate::tryToSend() { const auto langPackName = _connectionOptions->langPackName; const auto deviceModel = (_dcType == DcType::Cdn) ? "n/a" - : Messenger::Instance().launcher()->deviceModel(); + : Core::App().launcher()->deviceModel(); const auto systemVersion = (_dcType == DcType::Cdn) ? "n/a" - : Messenger::Instance().launcher()->systemVersion(); + : Core::App().launcher()->systemVersion(); #if defined OS_MAC_STORE || defined OS_WIN_STORE const auto appVersion = QString::fromLatin1(AppVersionStr) + " store"; @@ -1563,7 +1563,7 @@ void ConnectionPrivate::handleReceived() { uint32 toAckSize = ackRequestData.size(); if (toAckSize) { DEBUG_LOG(("MTP Info: will send %1 acks, ids: %2").arg(toAckSize).arg(LogIdsVector(ackRequestData))); - emit sendAnythingAsync(MTPAckSendWaiting); + emit sendAnythingAsync(kAckSendWaiting); } bool emitSignal = false; @@ -2321,10 +2321,10 @@ void ConnectionPrivate::requestsAcked(const QVector &ids, bool byRespon } uint32 ackedCount = wereAcked.size(); - if (ackedCount > MTPIdsBufferSize) { - DEBUG_LOG(("Message Info: removing some old acked sent msgIds %1").arg(ackedCount - MTPIdsBufferSize)); - clearedBecauseTooOld.reserve(ackedCount - MTPIdsBufferSize); - while (ackedCount-- > MTPIdsBufferSize) { + if (ackedCount > kIdsBufferSize) { + DEBUG_LOG(("Message Info: removing some old acked sent msgIds %1").arg(ackedCount - kIdsBufferSize)); + clearedBecauseTooOld.reserve(ackedCount - kIdsBufferSize); + while (ackedCount-- > kIdsBufferSize) { auto i = wereAcked.begin(); clearedBecauseTooOld.push_back(RPCCallbackClear( i.value(), diff --git a/Telegram/SourceFiles/mtproto/connection.h b/Telegram/SourceFiles/mtproto/connection.h index bed266878..559de0c61 100644 --- a/Telegram/SourceFiles/mtproto/connection.h +++ b/Telegram/SourceFiles/mtproto/connection.h @@ -15,6 +15,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL namespace MTP { +// How much time to wait for some more requests, when sending msg acks. +constexpr auto kAckSendWaiting = TimeMs(10000); + class Instance; bool IsPrimeAndGood(bytes::const_span primeBytes, int g); diff --git a/Telegram/SourceFiles/mtproto/dedicated_file_loader.cpp b/Telegram/SourceFiles/mtproto/dedicated_file_loader.cpp index 2da934259..13a53fd6f 100644 --- a/Telegram/SourceFiles/mtproto/dedicated_file_loader.cpp +++ b/Telegram/SourceFiles/mtproto/dedicated_file_loader.cpp @@ -8,7 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mtproto/dedicated_file_loader.h" #include "auth_session.h" -#include "messenger.h" +#include "core/application.h" namespace MTP { namespace { @@ -88,7 +88,7 @@ WeakInstance::WeakInstance(QPointer instance) _instance = nullptr; die(); }); - subscribe(Messenger::Instance().authSessionChanged(), [=] { + subscribe(Core::App().authSessionChanged(), [=] { if (!AuthSession::Exists()) { die(); } diff --git a/Telegram/SourceFiles/mtproto/facade.cpp b/Telegram/SourceFiles/mtproto/facade.cpp index de93dd4ba..7ec65548d 100644 --- a/Telegram/SourceFiles/mtproto/facade.cpp +++ b/Telegram/SourceFiles/mtproto/facade.cpp @@ -8,7 +8,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mtproto/facade.h" #include "storage/localstorage.h" -#include "messenger.h" +#include "core/application.h" +#include "core/sandbox.h" namespace MTP { namespace internal { @@ -38,7 +39,9 @@ void unpause() { } // namespace internal Instance *MainInstance() { - return Messenger::Instance().mtp(); + return Core::Sandbox::Instance().applicationLaunched() + ? Core::App().mtp() + : nullptr; } } // namespace MTP diff --git a/Telegram/SourceFiles/mtproto/facade.h b/Telegram/SourceFiles/mtproto/facade.h index 16ed4c0f9..315f0ef94 100644 --- a/Telegram/SourceFiles/mtproto/facade.h +++ b/Telegram/SourceFiles/mtproto/facade.h @@ -152,7 +152,7 @@ inline DcId maindc() { } inline int32 dcstate(ShiftedDcId shiftedDcId = 0) { - if (auto instance = MainInstance()) { + if (const auto instance = MainInstance()) { return instance->dcstate(shiftedDcId); } return DisconnectedState; @@ -187,23 +187,33 @@ inline mtpRequestId send( } 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) { - return MainInstance()->cancel(requestId); + if (const auto instance = MainInstance()) { + instance->cancel(requestId); + } } inline void ping() { - return MainInstance()->ping(); + if (const auto instance = MainInstance()) { + instance->ping(); + } } inline void killSession(ShiftedDcId shiftedDcId) { - return MainInstance()->killSession(shiftedDcId); + if (const auto instance = MainInstance()) { + instance->killSession(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 diff --git a/Telegram/SourceFiles/mtproto/mtp_instance.cpp b/Telegram/SourceFiles/mtproto/mtp_instance.cpp index bc0ccd1e6..2056bd53a 100644 --- a/Telegram/SourceFiles/mtproto/mtp_instance.cpp +++ b/Telegram/SourceFiles/mtproto/mtp_instance.cpp @@ -18,9 +18,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/localstorage.h" #include "calls/calls_instance.h" #include "auth_session.h" -#include "application.h" #include "apiwrap.h" -#include "messenger.h" +#include "core/application.h" #include "lang/lang_instance.h" #include "lang/lang_cloud_manager.h" #include "base/timer.h" @@ -413,7 +412,7 @@ void Instance::Private::setUserPhone(const QString &phone) { void Instance::Private::badConfigurationError() { 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::SetStickersFavedLimit(data.vstickers_faved_limit.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::SetWebFileDcId(data.vwebfile_dc_id.v); Global::SetTxtDomainString(qs(data.vdc_txt_domain_name)); diff --git a/Telegram/SourceFiles/mtproto/session.cpp b/Telegram/SourceFiles/mtproto/session.cpp index ac5234906..878a612f0 100644 --- a/Telegram/SourceFiles/mtproto/session.cpp +++ b/Telegram/SourceFiles/mtproto/session.cpp @@ -16,6 +16,20 @@ namespace MTP { namespace internal { 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 &ids) { if (!ids.size()) return "[]"; 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) { auto &req = i.value(); if (req->msDate > 0) { - if (req->msDate + MTPCheckResendTimeout < ms) { // need to resend or check state - if (req.messageSize() < MTPResendThreshold) { // resend + if (req->msDate + kCheckResendTimeout < ms) { // need to resend or check state + if (req.messageSize() < kResendThreshold) { // resend resendingIds.reserve(haveSentCount); resendingIds.push_back(i.key()); } else { @@ -315,7 +329,7 @@ void Session::checkRequestsByTimer() { 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.push_back(i.key()); } @@ -330,12 +344,12 @@ void Session::checkRequestsByTimer() { data.stateRequestMap().insert(stateRequestIds[i], true); } } - sendAnything(MTPCheckResendWaiting); + sendAnything(kCheckResendWaiting); } if (!resendingIds.isEmpty()) { for (uint32 i = 0, l = resendingIds.size(); i < l; ++i) { DEBUG_LOG(("MTP Info: resending request %1").arg(resendingIds[i])); - resend(resendingIds[i], MTPCheckResendWaiting); + resend(resendingIds[i], kCheckResendWaiting); } } if (!removingIds.isEmpty()) { diff --git a/Telegram/SourceFiles/mtproto/session.h b/Telegram/SourceFiles/mtproto/session.h index f2004ac59..e9c183f5e 100644 --- a/Telegram/SourceFiles/mtproto/session.h +++ b/Telegram/SourceFiles/mtproto/session.h @@ -18,6 +18,9 @@ using AuthKeyPtr = std::shared_ptr; namespace internal { +// Received msgIds and wereAcked msgIds count stored. +constexpr auto kIdsBufferSize = 400; + class Dcenter; class Connection; @@ -44,7 +47,7 @@ public: bool registerMsgId(mtpMsgId msgId, bool needAck) { auto i = _idsNeedAck.constFind(msgId); if (i == _idsNeedAck.cend()) { - if (_idsNeedAck.size() < MTPIdsBufferSize || msgId > min()) { + if (_idsNeedAck.size() < kIdsBufferSize || msgId > min()) { _idsNeedAck.insert(msgId, needAck); return true; } @@ -66,7 +69,7 @@ public: void shrink() { auto size = _idsNeedAck.size(); - while (size-- > MTPIdsBufferSize) { + while (size-- > kIdsBufferSize) { _idsNeedAck.erase(_idsNeedAck.begin()); } } diff --git a/Telegram/SourceFiles/overview/overview_layout.cpp b/Telegram/SourceFiles/overview/overview_layout.cpp index f4ca1fd82..82354c25e 100644 --- a/Telegram/SourceFiles/overview/overview_layout.cpp +++ b/Telegram/SourceFiles/overview/overview_layout.cpp @@ -19,7 +19,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/confirm_box.h" #include "lang/lang_keys.h" #include "mainwidget.h" -#include "application.h" #include "storage/file_upload.h" #include "mainwindow.h" #include "media/media_audio.h" diff --git a/Telegram/SourceFiles/platform/linux/file_utilities_linux.cpp b/Telegram/SourceFiles/platform/linux/file_utilities_linux.cpp index 6aabb4c59..e90960f63 100644 --- a/Telegram/SourceFiles/platform/linux/file_utilities_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/file_utilities_linux.cpp @@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include #include "platform/linux/linux_libs.h" #include "platform/linux/linux_gdk_helper.h" -#include "messenger.h" +#include "core/application.h" #include "mainwindow.h" #include "storage/localstorage.h" diff --git a/Telegram/SourceFiles/platform/linux/main_window_linux.cpp b/Telegram/SourceFiles/platform/linux/main_window_linux.cpp index f3a504136..52b819f8c 100644 --- a/Telegram/SourceFiles/platform/linux/main_window_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/main_window_linux.cpp @@ -13,8 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "platform/platform_notifications_manager.h" #include "history/history.h" #include "mainwindow.h" -#include "messenger.h" -#include "application.h" +#include "core/application.h" #include "lang/lang_keys.h" #include "storage/localstorage.h" @@ -71,14 +70,14 @@ gboolean _trayIconResized(GtkStatusIcon *status_icon, gint size, gpointer popup_ #endif // !TDESKTOP_DISABLE_GTK_INTEGRATION QImage _trayIconImageGen() { - const auto counter = Messenger::Instance().unreadBadge(); - const auto muted = Messenger::Instance().unreadBadgeMuted(); + const auto counter = Core::App().unreadBadge(); + const auto muted = Core::App().unreadBadgeMuted(); const auto counterSlice = (counter >= 1000) ? (1000 + (counter % 100)) : counter; if (_trayIconImage.isNull() || _trayIconImage.width() != _trayIconSize || muted != _trayIconMuted || counterSlice != _trayIconCount) { 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); int w = _trayIconImageBack.width(), h = _trayIconImageBack.height(), perline = _trayIconImageBack.bytesPerLine(); uchar *bytes = _trayIconImageBack.bits(); @@ -114,8 +113,8 @@ QImage _trayIconImageGen() { } QString _trayIconImageFile() { - const auto counter = Messenger::Instance().unreadBadge(); - const auto muted = Messenger::Instance().unreadBadgeMuted(); + const auto counter = Core::App().unreadBadge(); + const auto muted = Core::App().unreadBadgeMuted(); 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); @@ -335,7 +334,7 @@ void MainWindow::unreadCounterChangedHook() { void MainWindow::updateIconCounters() { 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 (_psUnityLauncherEntry) { @@ -374,8 +373,8 @@ void MainWindow::updateIconCounters() { QByteArray path = QFile::encodeName(iconFile.absoluteFilePath()); icon = QIcon(path.constData()); } else { - const auto counter = Messenger::Instance().unreadBadge(); - const auto muted = Messenger::Instance().unreadBadgeMuted(); + const auto counter = Core::App().unreadBadge(); + const auto muted = Core::App().unreadBadgeMuted(); auto &bg = (muted ? st::trayCounterBgMute : st::trayCounterBg); auto &fg = st::trayCounterFg; diff --git a/Telegram/SourceFiles/platform/linux/specific_linux.cpp b/Telegram/SourceFiles/platform/linux/specific_linux.cpp index 465f36d40..d9964a715 100644 --- a/Telegram/SourceFiles/platform/linux/specific_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/specific_linux.cpp @@ -9,7 +9,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "platform/linux/linux_libs.h" #include "lang/lang_keys.h" -#include "application.h" #include "mainwidget.h" #include "mainwindow.h" #include "platform/linux/linux_desktop_environment.h" @@ -91,11 +90,11 @@ void FallbackFontConfig() { namespace Platform { bool IsApplicationActive() { - return static_cast(QApplication::instance())->activeWindow() != nullptr; + return QApplication::activeWindow() != nullptr; } void SetApplicationIcon(const QIcon &icon) { - qApp->setWindowIcon(icon); + QApplication::setWindowIcon(icon); } QString CurrentExecutablePath(int argc, char *argv[]) { diff --git a/Telegram/SourceFiles/platform/mac/main_window_mac.mm b/Telegram/SourceFiles/platform/mac/main_window_mac.mm index 0ea58ab8c..dbb330d9e 100644 --- a/Telegram/SourceFiles/platform/mac/main_window_mac.mm +++ b/Telegram/SourceFiles/platform/mac/main_window_mac.mm @@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "styles/style_window.h" #include "mainwindow.h" #include "mainwidget.h" -#include "messenger.h" +#include "core/application.h" #include "auth_session.h" #include "history/history.h" #include "history/history_widget.h" @@ -521,8 +521,8 @@ void MainWindow::unreadCounterChangedHook() { } void MainWindow::updateIconCounters() { - const auto counter = Messenger::Instance().unreadBadge(); - const auto muted = Messenger::Instance().unreadBadgeMuted(); + const auto counter = Core::App().unreadBadge(); + const auto muted = Core::App().unreadBadgeMuted(); const auto string = !counter ? QString() @@ -699,7 +699,7 @@ void MainWindow::updateGlobalMenuHook() { } App::wnd()->updateIsActive(0); const auto logged = AuthSession::Exists(); - const auto locked = Messenger::Instance().locked(); + const auto locked = Core::App().locked(); const auto inactive = !logged || locked; const auto support = logged && Auth().supportMode(); _forceDisabled(psLogout, !logged && !locked); diff --git a/Telegram/SourceFiles/platform/mac/specific_mac.mm b/Telegram/SourceFiles/platform/mac/specific_mac.mm index 2e7d0b897..30829bc89 100644 --- a/Telegram/SourceFiles/platform/mac/specific_mac.mm +++ b/Telegram/SourceFiles/platform/mac/specific_mac.mm @@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "platform/mac/specific_mac.h" #include "lang/lang_keys.h" -#include "application.h" #include "mainwidget.h" #include "history/history_widget.h" #include "core/crash_reports.h" diff --git a/Telegram/SourceFiles/platform/mac/specific_mac_p.mm b/Telegram/SourceFiles/platform/mac/specific_mac_p.mm index b69d6a6b8..5e487fd9c 100644 --- a/Telegram/SourceFiles/platform/mac/specific_mac_p.mm +++ b/Telegram/SourceFiles/platform/mac/specific_mac_p.mm @@ -9,15 +9,16 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwindow.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 "media/player/media_player_instance.h" #include "media/media_audio.h" #include "platform/mac/mac_utilities.h" -#include "styles/style_window.h" #include "lang/lang_keys.h" #include "base/timer.h" -#include "core/crash_reports.h" +#include "styles/style_window.h" #include #include @@ -141,9 +142,9 @@ ApplicationDelegate *_sharedDelegate = nil; - (void) applicationDidBecomeActive:(NSNotification *)aNotification { ApplicationIsActive = true; - if (auto messenger = Messenger::InstancePointer()) { + if (Core::Sandbox::Instance().applicationLaunched()) { if (!_ignoreActivation) { - messenger->handleAppActivated(); + Core::App().handleAppActivated(); if (auto window = App::wnd()) { if (window->isHidden()) { window->showFromTray(); @@ -158,8 +159,8 @@ ApplicationDelegate *_sharedDelegate = nil; } - (void) receiveWakeNote:(NSNotification*)aNotification { - if (auto messenger = Messenger::InstancePointer()) { - messenger->checkLocalTime(); + if (Core::Sandbox::Instance().applicationLaunched()) { + Core::App().checkLocalTime(); } LOG(("Audio Info: -receiveWakeNote: received, scheduling detach from audio device")); diff --git a/Telegram/SourceFiles/platform/win/file_utilities_win.cpp b/Telegram/SourceFiles/platform/win/file_utilities_win.cpp index f32fbca50..5155462b5 100644 --- a/Telegram/SourceFiles/platform/win/file_utilities_win.cpp +++ b/Telegram/SourceFiles/platform/win/file_utilities_win.cpp @@ -11,7 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/localstorage.h" #include "platform/win/windows_dlls.h" #include "lang/lang_keys.h" -#include "messenger.h" +#include "core/application.h" #include "core/crash_reports.h" #include diff --git a/Telegram/SourceFiles/platform/win/main_window_win.cpp b/Telegram/SourceFiles/platform/win/main_window_win.cpp index ea1937c38..af1f0e9ea 100644 --- a/Telegram/SourceFiles/platform/win/main_window_win.cpp +++ b/Telegram/SourceFiles/platform/win/main_window_win.cpp @@ -12,8 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "platform/win/windows_dlls.h" #include "window/notifications_manager.h" #include "mainwindow.h" -#include "messenger.h" -#include "application.h" +#include "core/application.h" #include "lang/lang_keys.h" #include "storage/localstorage.h" #include "ui/widgets/popup_menu.h" @@ -665,7 +664,7 @@ void MainWindow::psSetupTrayIcon() { if (!trayIcon) { trayIcon = new QSystemTrayIcon(this); - auto icon = QIcon(App::pixmapFromImageInPlace(Messenger::Instance().logoNoMargin())); + auto icon = QIcon(App::pixmapFromImageInPlace(Core::App().logoNoMargin())); trayIcon->setIcon(icon); trayIcon->setToolTip(str_const_toString(AppName)); @@ -727,8 +726,8 @@ void MainWindow::unreadCounterChangedHook() { } void MainWindow::updateIconCounters() { - const auto counter = Messenger::Instance().unreadBadge(); - const auto muted = Messenger::Instance().unreadBadgeMuted(); + const auto counter = Core::App().unreadBadge(); + const auto muted = Core::App().unreadBadgeMuted(); auto iconSizeSmall = QSize(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON)); auto iconSizeBig = QSize(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON)); @@ -800,7 +799,7 @@ void MainWindow::psFirstShow() { if (cStartInTray() || (cLaunchMode() == LaunchModeAutoStart && cStartMinimized() - && !Messenger::Instance().passcodeLocked())) { + && !Core::App().passcodeLocked())) { DEBUG_LOG(("Window Pos: First show, setting minimized after.")); setWindowState(Qt::WindowMinimized); if (Global::WorkMode().value() == dbiwmTrayOnly diff --git a/Telegram/SourceFiles/platform/win/specific_win.cpp b/Telegram/SourceFiles/platform/win/specific_win.cpp index 48492949e..6c619c71c 100644 --- a/Telegram/SourceFiles/platform/win/specific_win.cpp +++ b/Telegram/SourceFiles/platform/win/specific_win.cpp @@ -329,11 +329,11 @@ QString SystemCountry() { } bool IsApplicationActive() { - return static_cast(QApplication::instance())->activeWindow() != nullptr; + return QApplication::activeWindow() != nullptr; } void SetApplicationIcon(const QIcon &icon) { - qApp->setWindowIcon(icon); + QApplication::setWindowIcon(icon); } QString CurrentExecutablePath(int argc, char *argv[]) { diff --git a/Telegram/SourceFiles/settings/settings_advanced.cpp b/Telegram/SourceFiles/settings/settings_advanced.cpp index 979da5e83..4eb350c44 100644 --- a/Telegram/SourceFiles/settings/settings_advanced.cpp +++ b/Telegram/SourceFiles/settings/settings_advanced.cpp @@ -21,6 +21,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "platform/platform_specific.h" #include "lang/lang_keys.h" #include "core/update_checker.h" +#include "core/application.h" #include "storage/localstorage.h" #include "data/data_session.h" #include "auth_session.h" @@ -174,7 +175,7 @@ void SetupUpdate(not_null container) { return (toggled != cInstallBetaVersion()); }) | rpl::start_with_next([=](bool toggled) { cSetInstallBetaVersion(toggled); - Sandbox::WriteInstallBetaVersionsSetting(); + Core::App().writeInstallBetaVersionsSetting(); Core::UpdateChecker checker; checker.stop(); diff --git a/Telegram/SourceFiles/settings/settings_codes.cpp b/Telegram/SourceFiles/settings/settings_codes.cpp index 2bcf8adfb..ae2aa9269 100644 --- a/Telegram/SourceFiles/settings/settings_codes.cpp +++ b/Telegram/SourceFiles/settings/settings_codes.cpp @@ -15,7 +15,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/confirm_box.h" #include "lang/lang_cloud_manager.h" #include "lang/lang_instance.h" -#include "messenger.h" +#include "core/application.h" #include "mtproto/mtp_instance.h" #include "mtproto/dc_options.h" #include "core/file_utilities.h" @@ -34,7 +34,7 @@ auto GenerateCodes() { : qsl("Do you want to enable DEBUG logs?\n\n" "All network events will be logged."); Ui::show(Box(text, [] { - Messenger::Instance().switchDebugMode(); + Core::App().switchDebugMode(); })); }); codes.emplace(qsl("viewlogs"), [] { @@ -43,7 +43,7 @@ auto GenerateCodes() { 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."); Ui::show(Box(text, [] { - Messenger::Instance().switchTestMode(); + Core::App().switchTestMode(); })); }); if (!Core::UpdaterDisabled()) { @@ -71,7 +71,7 @@ auto GenerateCodes() { codes.emplace(qsl("workmode"), [] { auto text = Global::DialogsModeEnabled() ? qsl("Disable work mode?") : qsl("Enable work mode?"); Ui::show(Box(text, [] { - Messenger::Instance().switchWorkMode(); + Core::App().switchWorkMode(); })); }); codes.emplace(qsl("moderate"), [] { @@ -88,7 +88,7 @@ auto GenerateCodes() { } }); 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()) { Window::Theme::Apply(result.paths.front()); } @@ -106,9 +106,9 @@ auto GenerateCodes() { })); }); 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 (!Messenger::Instance().mtp()->dcOptions()->loadFromFile(result.paths.front())) { + if (!Core::App().mtp()->dcOptions()->loadFromFile(result.paths.front())) { Ui::show(Box("Could not load endpoints :( Errors in 'log.txt'.")); } } @@ -137,7 +137,7 @@ auto GenerateCodes() { 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()) { auto track = Media::Audio::Current().createTrack(); track->fillFromFile(result.paths.front()); diff --git a/Telegram/SourceFiles/settings/settings_notifications.cpp b/Telegram/SourceFiles/settings/settings_notifications.cpp index 8c5f417ab..91efa99bd 100644 --- a/Telegram/SourceFiles/settings/settings_notifications.cpp +++ b/Telegram/SourceFiles/settings/settings_notifications.cpp @@ -19,7 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/notifications_manager.h" #include "platform/platform_notifications_manager.h" #include "mainwindow.h" -#include "messenger.h" +#include "core/application.h" #include "auth_session.h" #include "apiwrap.h" #include "styles/style_settings.h" @@ -239,7 +239,7 @@ void NotificationsCount::prepareNotificationSampleSmall() { void NotificationsCount::prepareNotificationSampleUserpic() { if (_notificationSampleUserpic.isNull()) { _notificationSampleUserpic = App::pixmapFromImageInPlace( - Messenger::Instance().logoNoMargin().scaled( + Core::App().logoNoMargin().scaled( st::notifyPhotoSize * cIntRetinaFactor(), st::notifyPhotoSize * cIntRetinaFactor(), Qt::IgnoreAspectRatio, diff --git a/Telegram/SourceFiles/settings/settings_privacy_security.cpp b/Telegram/SourceFiles/settings/settings_privacy_security.cpp index f65d1c818..855584317 100644 --- a/Telegram/SourceFiles/settings/settings_privacy_security.cpp +++ b/Telegram/SourceFiles/settings/settings_privacy_security.cpp @@ -463,8 +463,8 @@ void SetupCloudPassword(not_null container) { } }; QObject::connect( - qApp, - &QApplication::applicationStateChanged, + static_cast(QCoreApplication::instance()), + &QGuiApplication::applicationStateChanged, label, reloadOnActivation); diff --git a/Telegram/SourceFiles/storage/file_download.cpp b/Telegram/SourceFiles/storage/file_download.cpp index 2583d085a..e3cddbfae 100644 --- a/Telegram/SourceFiles/storage/file_download.cpp +++ b/Telegram/SourceFiles/storage/file_download.cpp @@ -11,9 +11,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_session.h" #include "mainwidget.h" #include "mainwindow.h" -#include "messenger.h" +#include "core/application.h" #include "storage/localstorage.h" #include "platform/platform_file_utilities.h" +#include "mtproto/connection.h" // for MTP::kAckSendWaiting #include "auth_session.h" #include "apiwrap.h" #include "core/crash_reports.h" @@ -21,8 +22,15 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "base/openssl_help.h" 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() { @@ -38,9 +46,49 @@ void Downloader::requestedAmountIncrement(MTP::DcId dcId, int index, int amount) } it->second[index] += amount; if (it->second[index]) { - Messenger::Instance().killDownloadSessionsStop(dcId); + killDownloadSessionsStop(dcId); } 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; } -Downloader::~Downloader() = default; +Downloader::~Downloader() { + killDownloadSessions(); +} } // namespace Storage diff --git a/Telegram/SourceFiles/storage/file_download.h b/Telegram/SourceFiles/storage/file_download.h index d2ff66594..ac9d86daf 100644 --- a/Telegram/SourceFiles/storage/file_download.h +++ b/Telegram/SourceFiles/storage/file_download.h @@ -8,8 +8,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #pragma once #include "base/observer.h" -#include "data/data_file_origin.h" +#include "base/timer.h" #include "base/binary_guard.h" +#include "data/data_file_origin.h" namespace Storage { namespace Cache { @@ -42,12 +43,19 @@ public: ~Downloader(); private: + void killDownloadSessionsStart(MTP::DcId dcId); + void killDownloadSessionsStop(MTP::DcId dcId); + void killDownloadSessions(); + base::Observable _taskFinishedObservable; int _priority = 1; using RequestedInDc = std::array; std::map _requestedBytesAmount; + base::flat_map _killDownloadSessionTimes; + base::Timer _killDownloadSessionsTimer; + }; } // namespace Storage diff --git a/Telegram/SourceFiles/storage/file_upload.cpp b/Telegram/SourceFiles/storage/file_upload.cpp index cf9196dcf..b21d9c4ad 100644 --- a/Telegram/SourceFiles/storage/file_upload.cpp +++ b/Telegram/SourceFiles/storage/file_upload.cpp @@ -9,6 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/localimageloader.h" #include "storage/file_download.h" +#include "mtproto/connection.h" // for MTP::kAckSendWaiting #include "data/data_document.h" #include "data/data_photo.h" #include "data/data_session.h" @@ -40,6 +41,9 @@ constexpr auto kDocumentUploadPartSize4 = 512 * 1024; // One part each half second, if not uploaded faster. constexpr auto kUploadRequestInterval = TimeMs(500); +// How much time without upload causes additional session kill. +constexpr auto kKillSessionTimeout = TimeMs(5000); + } // namespace struct Uploader::File { @@ -254,7 +258,8 @@ void Uploader::sendNext() { bool stopping = stopSessionsTimer.isActive(); if (queue.empty()) { if (!stopping) { - stopSessionsTimer.start(MTPAckSendWaiting + MTPKillFileSessionTimeout); + stopSessionsTimer.start( + MTP::kAckSendWaiting + kKillSessionTimeout); } return; } diff --git a/Telegram/SourceFiles/storage/localstorage.cpp b/Telegram/SourceFiles/storage/localstorage.cpp index a24b55dae..866564bf6 100644 --- a/Telegram/SourceFiles/storage/localstorage.cpp +++ b/Telegram/SourceFiles/storage/localstorage.cpp @@ -28,8 +28,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_cloud_manager.h" #include "media/media_audio.h" #include "mtproto/dc_options.h" -#include "messenger.h" -#include "application.h" +#include "core/application.h" #include "apiwrap.h" #include "auth_session.h" #include "window/window_controller.h" @@ -48,6 +47,7 @@ constexpr auto kThemeFileSizeLimit = 5 * 1024 * 1024; constexpr auto kFileLoaderQueueStopTimeout = TimeMs(5000); constexpr auto kDefaultStickerInstallDate = TimeId(1); constexpr auto kProxyTypeShift = 1024; +constexpr auto kWriteMapTimeout = TimeMs(1000); constexpr auto kSinglePeerTypeUser = qint32(1); constexpr auto kSinglePeerTypeChat = qint32(2); @@ -881,7 +881,7 @@ struct ReadSettingsContext { }; 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) { Lang::Current().fillFromLegacy(context.legacyLanguageId, context.legacyLanguageFile); writeLangPack(); @@ -1011,8 +1011,8 @@ bool _readSetting(quint32 blockId, QDataStream &stream, int version, ReadSetting if (!_checkStreamStatus(stream)) return false; DEBUG_LOG(("MTP Info: user found, dc %1, uid %2").arg(dcId).arg(userId)); - Messenger::Instance().setMtpMainDcId(dcId); - Messenger::Instance().setAuthSessionUserId(userId); + Core::App().setMtpMainDcId(dcId); + Core::App().setAuthSessionUserId(userId); } break; case dbiKey: { @@ -1021,7 +1021,7 @@ bool _readSetting(quint32 blockId, QDataStream &stream, int version, ReadSetting auto key = Serialize::read(stream); if (!_checkStreamStatus(stream)) return false; - Messenger::Instance().setMtpKey(dcId, key); + Core::App().setMtpKey(dcId, key); } break; case dbiMtpAuthorization: { @@ -1029,7 +1029,7 @@ bool _readSetting(quint32 blockId, QDataStream &stream, int version, ReadSetting stream >> serialized; if (!_checkStreamStatus(stream)) return false; - Messenger::Instance().setMtpAuthorization(serialized); + Core::App().setMtpAuthorization(serialized); } break; case dbiAutoStart: { @@ -2045,7 +2045,7 @@ void _writeUserSettings() { } auto userDataInstance = StoredAuthSessionCache ? StoredAuthSessionCache.get() - : Messenger::Instance().getAuthSessionSettings(); + : Core::App().getAuthSessionSettings(); auto userData = userDataInstance ? userDataInstance->serialize() : QByteArray(); @@ -2168,7 +2168,7 @@ void _writeMtpData() { return; } - auto mtpAuthorizationSerialized = Messenger::Instance().serializeMtpAuthorization(); + auto mtpAuthorizationSerialized = Core::App().serializeMtpAuthorization(); quint32 size = sizeof(quint32) + Serialize::bytearraySize(mtpAuthorizationSerialized); @@ -2402,7 +2402,7 @@ ReadMapState _readMap(const QByteArray &pass) { _readMtpData(); DEBUG_LOG(("selfSerialized set: %1").arg(selfSerialized.size())); - Messenger::Instance().setAuthSessionFromStorage( + Core::App().setAuthSessionFromStorage( std::move(StoredAuthSessionCache), std::move(selfSerialized), _oldMapVersion); @@ -2640,7 +2640,7 @@ void writeSettings() { } settings.writeData(_settingsSalt); - auto dcOptionsSerialized = Messenger::Instance().dcOptions()->serialize(); + auto dcOptionsSerialized = Core::App().dcOptions()->serialize(); quint32 size = 12 * (sizeof(quint32) + sizeof(qint32)); size += sizeof(quint32) + Serialize::bytearraySize(dcOptionsSerialized); @@ -5045,7 +5045,7 @@ Manager::Manager() { void Manager::writeMap(bool fast) { if (!_mapWriteTimer.isActive() || fast) { - _mapWriteTimer.start(fast ? 1 : WriteMapTimeout); + _mapWriteTimer.start(fast ? 1 : kWriteMapTimeout); } else if (_mapWriteTimer.remainingTime() <= 0) { mapWriteTimeout(); } @@ -5057,7 +5057,7 @@ void Manager::writingMap() { void Manager::writeLocations(bool fast) { if (!_locationsWriteTimer.isActive() || fast) { - _locationsWriteTimer.start(fast ? 1 : WriteMapTimeout); + _locationsWriteTimer.start(fast ? 1 : kWriteMapTimeout); } else if (_locationsWriteTimer.remainingTime() <= 0) { locationsWriteTimeout(); } diff --git a/Telegram/SourceFiles/support/support_helper.cpp b/Telegram/SourceFiles/support/support_helper.cpp index b5f051191..d8f3d8acf 100644 --- a/Telegram/SourceFiles/support/support_helper.cpp +++ b/Telegram/SourceFiles/support/support_helper.cpp @@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/window_controller.h" #include "storage/storage_media_prepare.h" #include "storage/localimageloader.h" +#include "core/sandbox.h" #include "auth_session.h" #include "observer_peer.h" #include "apiwrap.h" @@ -137,7 +138,7 @@ QString FormatDateTime(TimeId value) { } uint32 OccupationTag() { - return uint32(Sandbox::UserTag() & 0xFFFFFFFFU); + return uint32(Core::Sandbox::Instance().installationTag() & 0xFFFFFFFF); } QString NormalizeName(QString name) { @@ -280,7 +281,9 @@ Helper::Helper(not_null session) }); }).fail([=](const RPCError &error) { setSupportName( - qsl("[rand^") + QString::number(Sandbox::UserTag()) + ']'); + qsl("[rand^") + + QString::number(Core::Sandbox::Instance().installationTag()) + + ']'); }).send(); } diff --git a/Telegram/SourceFiles/ui/abstract_button.cpp b/Telegram/SourceFiles/ui/abstract_button.cpp index 748940c74..e4a2fcf50 100644 --- a/Telegram/SourceFiles/ui/abstract_button.cpp +++ b/Telegram/SourceFiles/ui/abstract_button.cpp @@ -9,7 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include #include -#include "messenger.h" +#include "core/application.h" namespace Ui { @@ -102,12 +102,12 @@ void AbstractButton::setOver(bool over, StateChangeSource source) { if (over && !(_state & StateFlag::Over)) { auto was = _state; _state |= StateFlag::Over; - Messenger::Instance().registerLeaveSubscription(this); + Core::App().registerLeaveSubscription(this); onStateChanged(was, source); } else if (!over && (_state & StateFlag::Over)) { auto was = _state; _state &= ~State(StateFlag::Over); - Messenger::Instance().unregisterLeaveSubscription(this); + Core::App().unregisterLeaveSubscription(this); onStateChanged(was, source); } updateCursor(); diff --git a/Telegram/SourceFiles/ui/countryinput.cpp b/Telegram/SourceFiles/ui/countryinput.cpp index 18341eded..221411faa 100644 --- a/Telegram/SourceFiles/ui/countryinput.cpp +++ b/Telegram/SourceFiles/ui/countryinput.cpp @@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/countryinput.h" #include "lang/lang_keys.h" -#include "application.h" #include "ui/widgets/scroll_area.h" #include "ui/widgets/multi_select.h" #include "ui/effects/ripple_animation.h" diff --git a/Telegram/SourceFiles/ui/special_buttons.cpp b/Telegram/SourceFiles/ui/special_buttons.cpp index 3a3e6282d..e1b5f9b89 100644 --- a/Telegram/SourceFiles/ui/special_buttons.cpp +++ b/Telegram/SourceFiles/ui/special_buttons.cpp @@ -20,6 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_channel.h" #include "history/history.h" #include "core/file_utilities.h" +#include "core/application.h" #include "boxes/photo_crop_box.h" #include "boxes/confirm_box.h" #include "window/window_controller.h" @@ -27,7 +28,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "auth_session.h" #include "apiwrap.h" #include "mainwidget.h" -#include "messenger.h" #include "observer_peer.h" namespace Ui { @@ -546,7 +546,7 @@ void UserpicButton::openPeerPhoto() { } const auto photo = Auth().data().photo(id); if (photo->date) { - Messenger::Instance().showPhoto(photo, _peer); + Core::App().showPhoto(photo, _peer); } } diff --git a/Telegram/SourceFiles/ui/toast/toast_manager.cpp b/Telegram/SourceFiles/ui/toast/toast_manager.cpp index 346bdcb03..e90d096d1 100644 --- a/Telegram/SourceFiles/ui/toast/toast_manager.cpp +++ b/Telegram/SourceFiles/ui/toast/toast_manager.cpp @@ -7,7 +7,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "ui/toast/toast_manager.h" -#include "application.h" #include "ui/toast/toast_widget.h" namespace Ui { diff --git a/Telegram/SourceFiles/ui/twidget.cpp b/Telegram/SourceFiles/ui/twidget.cpp index be9ecce12..d105f78c2 100644 --- a/Telegram/SourceFiles/ui/twidget.cpp +++ b/Telegram/SourceFiles/ui/twidget.cpp @@ -7,8 +7,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "twidget.h" -#include "application.h" #include "mainwindow.h" +#include "core/application.h" namespace Fonts { namespace { diff --git a/Telegram/SourceFiles/ui/widgets/dropdown_menu.cpp b/Telegram/SourceFiles/ui/widgets/dropdown_menu.cpp index de0c6ae52..5a6477ac5 100644 --- a/Telegram/SourceFiles/ui/widgets/dropdown_menu.cpp +++ b/Telegram/SourceFiles/ui/widgets/dropdown_menu.cpp @@ -7,7 +7,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "ui/widgets/dropdown_menu.h" -#include "application.h" #include "lang/lang_keys.h" namespace Ui { diff --git a/Telegram/SourceFiles/ui/widgets/input_fields.cpp b/Telegram/SourceFiles/ui/widgets/input_fields.cpp index d3b47e0f6..064e40a80 100644 --- a/Telegram/SourceFiles/ui/widgets/input_fields.cpp +++ b/Telegram/SourceFiles/ui/widgets/input_fields.cpp @@ -18,7 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwindow.h" #include "numbers.h" #include "auth_session.h" -#include "messenger.h" +#include "core/application.h" namespace Ui { namespace { @@ -4118,7 +4118,7 @@ void HexInput::correctValue( } UsernameInput::UsernameInput(QWidget *parent, const style::InputField &st, Fn placeholderFactory, const QString &val, bool isLink) : MaskedInputField(parent, st, std::move(placeholderFactory), val) { - setLinkPlaceholder(isLink ? Messenger::Instance().createInternalLink(QString()) : QString()); + setLinkPlaceholder(isLink ? Core::App().createInternalLink(QString()) : QString()); } void UsernameInput::setLinkPlaceholder(const QString &placeholder) { diff --git a/Telegram/SourceFiles/ui/widgets/popup_menu.cpp b/Telegram/SourceFiles/ui/widgets/popup_menu.cpp index 09fa9558d..325b94e62 100644 --- a/Telegram/SourceFiles/ui/widgets/popup_menu.cpp +++ b/Telegram/SourceFiles/ui/widgets/popup_menu.cpp @@ -10,9 +10,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/widgets/shadow.h" #include "ui/image/image_prepare.h" #include "platform/platform_specific.h" -#include "application.h" #include "mainwindow.h" -#include "messenger.h" +#include "core/application.h" #include "lang/lang_keys.h" namespace Ui { @@ -50,8 +49,8 @@ void PopupMenu::init() { using namespace rpl::mappers; rpl::merge( - Messenger::Instance().passcodeLockChanges(), - Messenger::Instance().termsLockChanges() + Core::App().passcodeLockChanges(), + Core::App().termsLockChanges() ) | rpl::start_with_next([=] { hideMenu(true); }, lifetime()); @@ -499,11 +498,11 @@ void PopupMenu::showMenu(const QPoint &p, PopupMenu *parent, TriggeredSource sou } PopupMenu::~PopupMenu() { - for (const auto submenu : base::take(_submenus)) { + for (const auto &submenu : base::take(_submenus)) { delete submenu; } if (const auto parent = parentWidget()) { - if (Core::App().focusWidget() != nullptr) { + if (QApplication::focusWidget() != nullptr) { Core::App().activateWindowDelayed(parent); } } diff --git a/Telegram/SourceFiles/ui/widgets/separate_panel.cpp b/Telegram/SourceFiles/ui/widgets/separate_panel.cpp index e416fa06c..05fcd70c0 100644 --- a/Telegram/SourceFiles/ui/widgets/separate_panel.cpp +++ b/Telegram/SourceFiles/ui/widgets/separate_panel.cpp @@ -18,7 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/widgets/tooltip.h" #include "window/layer_widget.h" #include "window/themes/window_theme.h" -#include "messenger.h" +#include "core/application.h" #include "styles/style_widgets.h" #include "styles/style_info.h" #include "styles/style_calls.h" @@ -333,7 +333,7 @@ void SeparatePanel::setInnerSize(QSize size) { } void SeparatePanel::initGeometry(QSize size) { - const auto center = Messenger::Instance().getPointForCallPanelCenter(); + const auto center = Core::App().getPointForCallPanelCenter(); _useTransparency = Platform::TranslucentWindowsSupported(center); _padding = _useTransparency ? st::callShadow.extend diff --git a/Telegram/SourceFiles/window/layer_widget.cpp b/Telegram/SourceFiles/window/layer_widget.cpp index 76e1e2026..7154f45f5 100644 --- a/Telegram/SourceFiles/window/layer_widget.cpp +++ b/Telegram/SourceFiles/window/layer_widget.cpp @@ -12,7 +12,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_document.h" #include "media/media_clip_reader.h" #include "boxes/abstract_box.h" -#include "application.h" #include "mainwindow.h" #include "mainwidget.h" #include "core/file_utilities.h" diff --git a/Telegram/SourceFiles/window/main_window.cpp b/Telegram/SourceFiles/window/main_window.cpp index 847c9a112..e13c6c599 100644 --- a/Telegram/SourceFiles/window/main_window.cpp +++ b/Telegram/SourceFiles/window/main_window.cpp @@ -15,12 +15,13 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/window_lock_widgets.h" #include "boxes/confirm_box.h" #include "core/click_handler_types.h" +#include "core/application.h" +#include "core/sandbox.h" #include "lang/lang_keys.h" #include "data/data_session.h" #include "mediaview.h" #include "auth_session.h" #include "apiwrap.h" -#include "messenger.h" #include "mainwindow.h" #include "styles/style_window.h" #include "styles/style_boxes.h" @@ -92,8 +93,8 @@ void ConvertIconToBlack(QImage &image) { QIcon CreateOfficialIcon() { auto image = [&] { - if (const auto messenger = Messenger::InstancePointer()) { - return messenger->logo(); + if (Core::Sandbox::Instance().applicationLaunched()) { + return Core::App().logo(); } return LoadLogo(); }(); @@ -128,13 +129,13 @@ MainWindow::MainWindow() subscribe(Global::RefWorkMode(), [=](DBIWorkMode mode) { workmodeUpdated(mode); }); - subscribe(Messenger::Instance().authSessionChanged(), [=] { + subscribe(Core::App().authSessionChanged(), [=] { checkAuthSession(); updateWindowIcon(); }); checkAuthSession(); - Messenger::Instance().termsLockValue( + Core::App().termsLockValue( ) | rpl::start_with_next([=] { checkLockByTerms(); }, lifetime()); @@ -144,7 +145,7 @@ MainWindow::MainWindow() } void MainWindow::checkLockByTerms() { - const auto data = Messenger::Instance().termsLocked(); + const auto data = Core::App().termsLocked(); if (!data || !AuthSession::Exists()) { if (_termsBox) { _termsBox->closeBox(); @@ -170,7 +171,7 @@ void MainWindow::checkLockByTerms() { MentionClickHandler(mention).onClick({}); } } - Messenger::Instance().unlockTerms(); + Core::App().unlockTerms(); }, box->lifetime()); box->cancelClicks( @@ -217,7 +218,7 @@ void MainWindow::showTermsDelete() { lang(lng_terms_delete_warning), lang(lng_terms_delete_now), st::attentionBoxButton, - [=] { Messenger::Instance().termsDeleteNow(); }, + [=] { Core::App().termsDeleteNow(); }, [=] { if (*box) (*box)->closeBox(); }), LayerOption::KeepOther); } @@ -301,7 +302,7 @@ void MainWindow::handleStateChanged(Qt::WindowState state) { void MainWindow::handleActiveChanged() { if (isActiveWindow()) { - Messenger::Instance().checkMediaViewActivation(); + Core::App().checkMediaViewActivation(); } App::CallDelayed(1, this, [this] { updateTrayMenu(); diff --git a/Telegram/SourceFiles/window/notifications_manager.cpp b/Telegram/SourceFiles/window/notifications_manager.cpp index a471aa0b8..da9cf910c 100644 --- a/Telegram/SourceFiles/window/notifications_manager.cpp +++ b/Telegram/SourceFiles/window/notifications_manager.cpp @@ -18,9 +18,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_session.h" #include "data/data_channel.h" #include "window/window_controller.h" +#include "core/application.h" #include "mainwindow.h" #include "mainwidget.h" -#include "messenger.h" #include "apiwrap.h" #include "auth_session.h" @@ -383,7 +383,7 @@ void System::updateAll() { } Manager::DisplayOptions Manager::getNotificationOptions(HistoryItem *item) { - const auto hideEverything = Messenger::Instance().locked() + const auto hideEverything = Core::App().locked() || Global::ScreenIsLocked(); DisplayOptions result; @@ -399,7 +399,7 @@ void Manager::notificationActivated(PeerId peerId, MsgId msgId) { auto history = Auth().data().history(peerId); window->showFromTray(); window->reActivateWindow(); - if (Messenger::Instance().locked()) { + if (Core::App().locked()) { window->setInnerFocus(); system()->clearAll(); } else { diff --git a/Telegram/SourceFiles/window/notifications_manager_default.cpp b/Telegram/SourceFiles/window/notifications_manager_default.cpp index 75037fdc6..bf5c68ac7 100644 --- a/Telegram/SourceFiles/window/notifications_manager_default.cpp +++ b/Telegram/SourceFiles/window/notifications_manager_default.cpp @@ -8,8 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/notifications_manager_default.h" #include "platform/platform_notifications_manager.h" -#include "application.h" -#include "messenger.h" +#include "core/application.h" #include "lang/lang_keys.h" #include "ui/widgets/buttons.h" #include "ui/widgets/input_fields.h" @@ -78,7 +77,7 @@ Manager::QueuedNotification::QueuedNotification( QPixmap Manager::hiddenUserpicPlaceholder() const { if (_hiddenUserpicPlaceholder.isNull()) { - _hiddenUserpicPlaceholder = App::pixmapFromImageInPlace(Messenger::Instance().logoNoMargin().scaled(st::notifyPhotoSize, st::notifyPhotoSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + _hiddenUserpicPlaceholder = App::pixmapFromImageInPlace(Core::App().logoNoMargin().scaled(st::notifyPhotoSize, st::notifyPhotoSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); _hiddenUserpicPlaceholder.setDevicePixelRatio(cRetinaFactor()); } return _hiddenUserpicPlaceholder; @@ -759,7 +758,7 @@ bool Notification::unlinkItem(HistoryItem *deleted) { bool Notification::canReply() const { return !_hideReplyButton && (_item != nullptr) - && !Messenger::Instance().locked() + && !Core::App().locked() && (Global::NotifyView() <= dbinvShowPreview); } diff --git a/Telegram/SourceFiles/window/notifications_utilities.cpp b/Telegram/SourceFiles/window/notifications_utilities.cpp index 24ae98b51..ecca77827 100644 --- a/Telegram/SourceFiles/window/notifications_utilities.cpp +++ b/Telegram/SourceFiles/window/notifications_utilities.cpp @@ -8,7 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/notifications_utilities.h" #include "platform/platform_specific.h" -#include "messenger.h" +#include "core/application.h" #include "data/data_peer.h" #include "styles/style_window.h" @@ -51,7 +51,7 @@ QString CachedUserpics::get(const StorageKey &key, PeerData *peer) { peer->saveUserpic(v.path, st::notifyMacPhotoSize); } } else { - Messenger::Instance().logoNoMargin().save(v.path, "PNG"); + Core::App().logoNoMargin().save(v.path, "PNG"); } i = _images.insert(key, v); _someSavedFlag = true; diff --git a/Telegram/SourceFiles/window/section_widget.cpp b/Telegram/SourceFiles/window/section_widget.cpp index 24890b12f..fd5bc33c3 100644 --- a/Telegram/SourceFiles/window/section_widget.cpp +++ b/Telegram/SourceFiles/window/section_widget.cpp @@ -8,7 +8,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/section_widget.h" #include -#include "application.h" #include "mainwidget.h" #include "window/section_memento.h" #include "window/window_slide_animation.h" diff --git a/Telegram/SourceFiles/window/window_lock_widgets.cpp b/Telegram/SourceFiles/window/window_lock_widgets.cpp index 8fa08f974..cc783984f 100644 --- a/Telegram/SourceFiles/window/window_lock_widgets.cpp +++ b/Telegram/SourceFiles/window/window_lock_widgets.cpp @@ -10,7 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_keys.h" #include "storage/localstorage.h" #include "mainwindow.h" -#include "messenger.h" +#include "core/application.h" #include "ui/text/text.h" #include "ui/widgets/buttons.h" #include "ui/widgets/checkbox.h" @@ -143,7 +143,7 @@ void PasscodeLockWidget::submit() { return; } - Messenger::Instance().unlockPasscode(); // Destroys this widget. + Core::App().unlockPasscode(); // Destroys this widget. } void PasscodeLockWidget::error() { diff --git a/Telegram/gyp/telegram_sources.txt b/Telegram/gyp/telegram_sources.txt index 2a2d718b8..1a97f80de 100644 --- a/Telegram/gyp/telegram_sources.txt +++ b/Telegram/gyp/telegram_sources.txt @@ -113,6 +113,8 @@ <(src_loc)/chat_helpers/tabbed_section.h <(src_loc)/chat_helpers/tabbed_selector.cpp <(src_loc)/chat_helpers/tabbed_selector.h +<(src_loc)/core/application.cpp +<(src_loc)/core/application.h <(src_loc)/core/changelogs.cpp <(src_loc)/core/changelogs.h <(src_loc)/core/click_handler.cpp @@ -138,6 +140,8 @@ <(src_loc)/core/media_active_cache.h <(src_loc)/core/mime_type.cpp <(src_loc)/core/mime_type.h +<(src_loc)/core/sandbox.cpp +<(src_loc)/core/sandbox.h <(src_loc)/core/shortcuts.cpp <(src_loc)/core/shortcuts.h <(src_loc)/core/update_checker.cpp @@ -799,8 +803,6 @@ <(src_loc)/apiwrap.h <(src_loc)/app.cpp <(src_loc)/app.h -<(src_loc)/application.cpp -<(src_loc)/application.h <(src_loc)/auth_session.cpp <(src_loc)/auth_session.h <(src_loc)/config.h @@ -818,8 +820,6 @@ <(src_loc)/mainwindow.h <(src_loc)/mediaview.cpp <(src_loc)/mediaview.h -<(src_loc)/messenger.cpp -<(src_loc)/messenger.h <(src_loc)/observer_peer.cpp <(src_loc)/observer_peer.h <(src_loc)/qt_static_plugins.cpp