tdesktop/Telegram/SourceFiles/core/application.cpp

1025 lines
26 KiB
C++
Raw Normal View History

/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "core/application.h"
#include "data/data_photo.h"
#include "data/data_document.h"
#include "data/data_session.h"
#include "data/data_user.h"
#include "base/timer.h"
#include "base/concurrent_timer.h"
#include "base/unixtime.h"
#include "core/update_checker.h"
2018-11-16 12:15:14 +00:00
#include "core/shortcuts.h"
#include "core/sandbox.h"
#include "core/local_url_handlers.h"
#include "core/launcher.h"
#include "core/ui_integration.h"
#include "chat_helpers/emoji_keywords.h"
2020-06-03 05:43:59 +00:00
#include "base/platform/base_platform_info.h"
2017-03-04 10:23:56 +00:00
#include "platform/platform_specific.h"
#include "mainwindow.h"
#include "dialogs/dialogs_entry.h"
#include "history/history.h"
#include "apiwrap.h"
#include "api/api_updates.h"
#include "calls/calls_instance.h"
2017-04-13 08:27:10 +00:00
#include "lang/lang_file_parser.h"
#include "lang/lang_translator.h"
#include "lang/lang_cloud_manager.h"
2018-05-24 13:40:19 +00:00
#include "lang/lang_hardcoded.h"
#include "mainwidget.h"
#include "core/file_utilities.h"
#include "main/main_account.h"
2020-06-15 16:25:02 +00:00
#include "main/main_accounts.h"
#include "main/main_session.h"
#include "media/view/media_view_overlay_widget.h"
#include "mtproto/dc_options.h"
#include "mtproto/mtp_instance.h"
#include "media/audio/media_audio.h"
#include "media/audio/media_audio_track.h"
#include "media/player/media_player_instance.h"
2019-04-02 10:29:28 +00:00
#include "media/clip/media_clip_reader.h" // For Media::Clip::Finish().
#include "window/notifications_manager.h"
#include "window/themes/window_theme.h"
#include "window/window_lock_widgets.h"
#include "history/history_location_manager.h"
#include "ui/widgets/tooltip.h"
#include "ui/image/image.h"
#include "ui/text_options.h"
#include "ui/emoji_config.h"
2019-02-04 13:34:50 +00:00
#include "ui/effects/animations.h"
2017-03-04 10:23:56 +00:00
#include "storage/serialize_common.h"
2020-06-15 16:25:02 +00:00
#include "storage/storage_accounts.h"
#include "storage/storage_databases.h"
#include "storage/localstorage.h"
#include "window/window_session_controller.h"
#include "window/window_controller.h"
2017-06-27 20:11:38 +00:00
#include "base/qthelp_regex.h"
#include "base/qthelp_url.h"
#include "boxes/connection_box.h"
#include "boxes/confirm_phone_box.h"
2018-05-24 13:40:19 +00:00
#include "boxes/confirm_box.h"
2017-06-27 20:11:38 +00:00
#include "boxes/share_box.h"
#include "facades.h"
#include "app.h"
2019-09-04 07:19:15 +00:00
#include <QtWidgets/QDesktopWidget>
#include <QtCore/QMimeDatabase>
#include <QtGui/QGuiApplication>
#include <QtGui/QDesktopServices>
namespace Core {
namespace {
constexpr auto kQuitPreventTimeoutMs = crl::time(1500);
constexpr auto kAutoLockTimeoutLateMs = crl::time(3000);
} // namespace
2019-02-04 13:34:50 +00:00
Application *Application::Instance = nullptr;
struct Application::Private {
base::Timer quitTimer;
2019-09-16 11:14:06 +00:00
UiIntegration uiIntegration;
};
Application::Application(not_null<Launcher*> launcher)
: QObject()
, _launcher(launcher)
, _private(std::make_unique<Private>())
, _databases(std::make_unique<Storage::Databases>())
2019-02-04 13:34:50 +00:00
, _animationsManager(std::make_unique<Ui::Animations::Manager>())
2019-07-24 08:46:23 +00:00
, _dcOptions(std::make_unique<MTP::DcOptions>())
2020-06-15 16:25:02 +00:00
, _accounts(std::make_unique<Main::Accounts>(cDataFile()))
, _langpack(std::make_unique<Lang::Instance>())
2019-11-27 08:02:56 +00:00
, _langCloudManager(std::make_unique<Lang::CloudManager>(langpack()))
, _emojiKeywords(std::make_unique<ChatHelpers::EmojiKeywords>())
, _audio(std::make_unique<Media::Audio::Instance>())
, _logo(Window::LoadLogo())
, _logoNoMargin(Window::LoadLogoNoMargin())
, _autoLockTimer([=] { checkAutoLock(); }) {
Expects(!_logo.isNull());
Expects(!_logoNoMargin.isNull());
2019-02-04 13:34:50 +00:00
2019-09-16 11:14:06 +00:00
Ui::Integration::Set(&_private->uiIntegration);
passcodeLockChanges(
) | rpl::start_with_next([=] {
_shouldLockAt = 0;
}, _lifetime);
2020-06-15 16:25:02 +00:00
accounts().activeSessionChanges(
2020-06-10 10:49:10 +00:00
) | rpl::start_with_next([=](Main::Session *session) {
2020-06-10 14:52:44 +00:00
if (session && !UpdaterDisabled()) { // #TODO multi someSessionValue
UpdateChecker().setMtproto(session);
2020-06-10 10:49:10 +00:00
}
2019-07-24 08:46:23 +00:00
}, _lifetime);
2020-06-15 16:25:02 +00:00
accounts().activeValue(
) | rpl::map([=](Main::Account *account) {
return account ? account->mtpValue() : rpl::never<MTP::Instance*>();
}) | rpl::flatten_latest(
2019-07-24 08:46:23 +00:00
) | rpl::filter([=](MTP::Instance *instance) {
return instance != nullptr;
2020-06-10 10:49:10 +00:00
}) | rpl::start_with_next([=] {
if (_window) {
2020-06-15 16:25:02 +00:00
// Global::DesktopNotify is used in updateTrayMenu.
// This should be called when user settings are read.
// Right now after they are read the startMtp() is called.
_window->widget()->updateTrayMenu();
}
2019-07-24 08:46:23 +00:00
}, _lifetime);
}
Application::~Application() {
2020-06-15 16:25:02 +00:00
// Depend on activeWindow() for now :(
Shortcuts::Finish();
_window.reset();
2020-06-15 16:25:02 +00:00
if (_mediaView) {
_mediaView->clearData();
_mediaView = nullptr;
}
2020-06-16 06:42:47 +00:00
unlockTerms();
for (const auto &[index, account] : accounts().list()) {
if (account->sessionExists()) {
account->session().saveSettingsNowIfNeeded();
}
// Some MTP requests can be cancelled from data clearing.
account->destroySession();
account->clearMtp();
}
Local::finish();
Shortcuts::Finish();
Ui::Emoji::Clear();
2019-04-02 10:29:28 +00:00
Media::Clip::Finish();
App::deinitMedia();
2019-09-05 06:51:46 +00:00
Window::Theme::Uninitialize();
Media::Player::finish(_audio.get());
style::stopManager();
Global::finish();
ThirdParty::finish();
Instance = nullptr;
}
void Application::run() {
2019-09-13 10:24:06 +00:00
style::internal::StartFonts();
ThirdParty::start();
Global::start();
refreshGlobalProxy(); // Depends on Global::started().
startLocalStorage();
2019-09-13 10:24:06 +00:00
ValidateScale();
if (Local::oldSettingsVersion() < AppVersion) {
psNewVersion();
}
2020-05-29 17:49:39 +00:00
if (cAutoStart() && !Platform::AutostartSupported()) {
cSetAutoStart(false);
}
if (cLaunchMode() == LaunchModeAutoStart && !cAutoStart()) {
psAutoStart(false, true);
App::quit();
return;
}
_translator = std::make_unique<Lang::Translator>();
QCoreApplication::instance()->installTranslator(_translator.get());
2019-09-13 10:24:06 +00:00
style::startManager(cScale());
Ui::InitTextOptions();
Ui::Emoji::Init();
Media::Player::start(_audio.get());
2019-09-13 16:45:48 +00:00
style::ShortAnimationPlaying(
) | rpl::start_with_next([=](bool playing) {
if (playing) {
2019-12-02 13:10:19 +00:00
MTP::details::pause();
2019-09-13 16:45:48 +00:00
} else {
2019-12-02 13:10:19 +00:00
MTP::details::unpause();
2019-09-13 16:45:48 +00:00
}
}, _lifetime);
DEBUG_LOG(("Application Info: inited..."));
cChangeTimeFormat(QLocale::system().timeFormat(QLocale::ShortFormat));
DEBUG_LOG(("Application Info: starting app..."));
// Create mime database, so it won't be slow later.
QMimeDatabase().mimeTypeForName(qsl("text/plain"));
2020-06-15 16:25:02 +00:00
_window = std::make_unique<Window::Controller>();
2020-06-16 06:42:47 +00:00
accounts().activeChanges(
) | rpl::start_with_next([=](not_null<Main::Account*> account) {
_window->showAccount(account);
}, _window->widget()->lifetime());
QCoreApplication::instance()->installEventFilter(this);
2019-01-18 11:26:43 +00:00
connect(
static_cast<QGuiApplication*>(QCoreApplication::instance()),
&QGuiApplication::applicationStateChanged,
2019-01-18 11:26:43 +00:00
this,
&Application::stateChanged);
DEBUG_LOG(("Application Info: window created..."));
2020-06-15 16:25:02 +00:00
// Depend on activeWindow() for now :(
2018-11-16 12:15:14 +00:00
startShortcuts();
2020-06-15 16:25:02 +00:00
App::initMedia();
2020-06-15 16:25:02 +00:00
const auto state = accounts().start(QByteArray());
if (state == Storage::StartResult::IncorrectPasscode) {
Global::SetLocalPasscode(true);
Global::RefLocalPasscodeChanged().notify();
lockByPasscode();
DEBUG_LOG(("Application Info: passcode needed..."));
}
_window->widget()->show();
2020-02-11 09:28:53 +00:00
const auto currentGeometry = _window->widget()->geometry();
_mediaView = std::make_unique<Media::View::OverlayWidget>();
2020-02-11 09:28:53 +00:00
_window->widget()->setGeometry(currentGeometry);
DEBUG_LOG(("Application Info: showing."));
_window->finishFirstShow();
if (!locked() && cStartToSettings()) {
_window->showSettings();
}
_window->updateIsActive(Global::OnlineFocusTimeout());
2018-11-16 12:15:14 +00:00
for (const auto &error : Shortcuts::Errors()) {
LOG(("Shortcuts Error: %1").arg(error));
}
}
bool Application::hideMediaView() {
if (_mediaView && !_mediaView->isHidden()) {
_mediaView->hide();
if (const auto window = activeWindow()) {
window->reActivate();
2017-08-08 09:56:10 +00:00
}
return true;
}
return false;
}
void Application::showPhoto(not_null<const PhotoOpenClickHandler*> link) {
2019-06-06 11:59:00 +00:00
const auto photo = link->photo();
const auto peer = link->peer();
2019-06-06 11:59:00 +00:00
const auto item = photo->owner().message(link->context());
return (!item && peer)
2019-06-06 11:59:00 +00:00
? showPhoto(photo, peer)
: showPhoto(photo, item);
}
void Application::showPhoto(not_null<PhotoData*> photo, HistoryItem *item) {
Expects(_mediaView != nullptr);
_mediaView->showPhoto(photo, item);
_mediaView->activateWindow();
_mediaView->setFocus();
}
void Application::showPhoto(
not_null<PhotoData*> photo,
not_null<PeerData*> peer) {
Expects(_mediaView != nullptr);
_mediaView->showPhoto(photo, peer);
_mediaView->activateWindow();
_mediaView->setFocus();
}
void Application::showDocument(not_null<DocumentData*> document, HistoryItem *item) {
Expects(_mediaView != nullptr);
2019-02-28 21:03:25 +00:00
if (cUseExternalVideoPlayer()
&& document->isVideoFile()
&& !document->filepath().isEmpty()) {
File::Launch(document->location(false).fname);
} else {
_mediaView->showDocument(document, item);
_mediaView->activateWindow();
_mediaView->setFocus();
}
}
2019-09-06 15:31:01 +00:00
void Application::showTheme(
not_null<DocumentData*> document,
const Data::CloudTheme &cloud) {
Expects(_mediaView != nullptr);
2019-09-06 15:31:01 +00:00
_mediaView->showTheme(document, cloud);
_mediaView->activateWindow();
_mediaView->setFocus();
}
PeerData *Application::ui_getPeerForMouseAction() {
if (_mediaView && !_mediaView->isHidden()) {
return _mediaView->ui_getPeerForMouseAction();
2020-06-12 14:09:04 +00:00
} else if (const auto m = App::main()) { // multi good
return m->ui_getPeerForMouseAction();
}
return nullptr;
}
bool Application::eventFilter(QObject *object, QEvent *e) {
switch (e->type()) {
case QEvent::KeyPress:
case QEvent::MouseButtonPress:
case QEvent::TouchBegin:
case QEvent::Wheel: {
updateNonIdle();
} break;
case QEvent::ShortcutOverride: {
// handle shortcuts ourselves
return true;
} break;
case QEvent::Shortcut: {
2018-11-16 12:15:14 +00:00
const auto event = static_cast<QShortcutEvent*>(e);
DEBUG_LOG(("Shortcut event caught: %1"
).arg(event->key().toString()));
if (Shortcuts::HandleEvent(event)) {
return true;
}
} break;
case QEvent::ApplicationActivate: {
if (object == QCoreApplication::instance()) {
updateNonIdle();
}
} break;
case QEvent::FileOpen: {
if (object == QCoreApplication::instance()) {
const auto event = static_cast<QFileOpenEvent*>(e);
const auto url = QString::fromUtf8(
event->url().toEncoded().trimmed());
if (url.startsWith(qstr("tg://"), Qt::CaseInsensitive)) {
cSetStartUrl(url.mid(0, 8192));
checkStartUrl();
}
if (StartUrlRequiresActivate(url)) {
_window->activate();
}
}
} break;
}
return QObject::eventFilter(object, e);
}
2019-08-23 13:52:59 +00:00
void Application::saveSettingsDelayed(crl::time delay) {
_saveSettingsTimer.callOnce(delay);
}
void Application::setCurrentProxy(
2019-11-13 14:12:04 +00:00
const MTP::ProxyData &proxy,
MTP::ProxyData::Settings settings) {
2019-07-24 08:46:23 +00:00
const auto current = [&] {
2019-11-13 14:12:04 +00:00
return (Global::ProxySettings() == MTP::ProxyData::Settings::Enabled)
? Global::SelectedProxy()
2019-11-13 14:12:04 +00:00
: MTP::ProxyData();
2019-07-24 08:46:23 +00:00
};
const auto was = current();
Global::SetSelectedProxy(proxy);
Global::SetProxySettings(settings);
2019-07-24 08:46:23 +00:00
const auto now = current();
refreshGlobalProxy();
2019-07-24 08:46:23 +00:00
_proxyChanges.fire({ was, now });
Global::RefConnectionTypeChanged().notify();
}
2019-07-24 08:46:23 +00:00
auto Application::proxyChanges() const -> rpl::producer<ProxyChange> {
return _proxyChanges.events();
}
void Application::badMtprotoConfigurationError() {
2019-11-13 14:12:04 +00:00
if (Global::ProxySettings() == MTP::ProxyData::Settings::Enabled
&& !_badProxyDisableBox) {
const auto disableCallback = [=] {
setCurrentProxy(
Global::SelectedProxy(),
2019-11-13 14:12:04 +00:00
MTP::ProxyData::Settings::System);
};
2018-05-24 13:40:19 +00:00
_badProxyDisableBox = Ui::show(Box<InformBox>(
Lang::Hard::ProxyConfigError(),
disableCallback));
2018-05-24 13:40:19 +00:00
}
}
void Application::startLocalStorage() {
Local::start();
const auto writing = _lifetime.make_state<bool>(false);
_dcOptions->changed(
) | rpl::filter([=] {
return !*writing;
}) | rpl::start_with_next([=] {
*writing = true;
Ui::PostponeCall(this, [=] {
Local::writeSettings();
});
}, _lifetime);
2019-08-23 13:52:59 +00:00
_saveSettingsTimer.setCallback([=] { Local::writeSettings(); });
}
2020-06-16 09:40:43 +00:00
void Application::logout(Main::Account *account) {
if (account) {
account->logOut();
} else {
accounts().resetWithForgottenPasscode();
if (Global::LocalPasscode()) {
Global::SetLocalPasscode(false);
Global::RefLocalPasscodeChanged().notify();
}
Core::App().unlockPasscode();
Core::App().unlockTerms();
}
}
void Application::forceLogOut(
not_null<Main::Account*> account,
const TextWithEntities &explanation) {
const auto box = Ui::show(Box<InformBox>(
explanation,
2019-06-19 15:09:03 +00:00
tr::lng_passcode_logout(tr::now)));
box->setCloseByEscape(false);
box->setCloseByOutsideClick(false);
2020-06-16 09:40:43 +00:00
const auto weak = base::make_weak(account.get());
connect(box, &QObject::destroyed, [=] {
2020-06-16 09:40:43 +00:00
crl::on_main(weak, [=] {
account->forcedLogOut();
});
});
}
void Application::checkLocalTime() {
const auto adjusted = crl::adjust_time();
if (adjusted) {
base::Timer::Adjust();
base::ConcurrentTimerEnvironment::Adjust();
base::unixtime::http_invalidate();
}
if (activeAccount().sessionExists()) {
activeAccount().session().updates().checkLastUpdate(adjusted);
}
}
void Application::stateChanged(Qt::ApplicationState state) {
if (state == Qt::ApplicationActive) {
handleAppActivated();
} else {
handleAppDeactivated();
}
}
void Application::handleAppActivated() {
checkLocalTime();
if (_window) {
_window->updateIsActive(Global::OnlineFocusTimeout());
}
}
void Application::handleAppDeactivated() {
if (_window) {
_window->updateIsActive(Global::OfflineBlurTimeout());
}
Ui::Tooltip::Hide();
}
void Application::call_handleUnreadCounterUpdate() {
Global::RefUnreadCounterUpdate().notify(true);
}
void Application::call_handleObservables() {
base::HandleObservables();
}
void Application::switchDebugMode() {
if (Logs::DebugEnabled()) {
Logs::SetDebugEnabled(false);
_launcher->writeDebugModeSetting();
App::restart();
} else {
Logs::SetDebugEnabled(true);
_launcher->writeDebugModeSetting();
DEBUG_LOG(("Debug logs started."));
Ui::hideLayer();
}
}
void Application::switchTestMode() {
if (cTestMode()) {
QFile(cWorkingDir() + qsl("tdata/withtestmode")).remove();
cSetTestMode(false);
} else {
QFile f(cWorkingDir() + qsl("tdata/withtestmode"));
if (f.open(QIODevice::WriteOnly)) {
f.write("1");
f.close();
}
cSetTestMode(true);
}
App::restart();
}
void Application::switchFreeType() {
if (cUseFreeType()) {
QFile(cWorkingDir() + qsl("tdata/withfreetype")).remove();
cSetUseFreeType(false);
} else {
QFile f(cWorkingDir() + qsl("tdata/withfreetype"));
if (f.open(QIODevice::WriteOnly)) {
f.write("1");
f.close();
}
cSetUseFreeType(true);
}
App::restart();
}
void Application::writeInstallBetaVersionsSetting() {
_launcher->writeInstallBetaVersionsSetting();
}
2020-06-15 16:25:02 +00:00
Main::Account &Application::activeAccount() const {
return _accounts->active();
}
2019-07-24 14:00:30 +00:00
bool Application::exportPreventsQuit() {
if (!activeAccount().sessionExists()
|| !activeAccount().session().data().exportInProgress()) {
return false;
}
activeAccount().session().data().stopExportWithConfirmation([] {
App::quit();
});
return true;
}
int Application::unreadBadge() const {
2020-06-15 16:25:02 +00:00
return (accounts().started() && activeAccount().sessionExists())
? activeAccount().session().data().unreadBadge()
: 0;
2018-12-04 10:32:06 +00:00
}
bool Application::unreadBadgeMuted() const {
2020-06-15 16:25:02 +00:00
return (accounts().started() && activeAccount().sessionExists())
? activeAccount().session().data().unreadBadgeMuted()
: false;
2018-12-04 10:32:06 +00:00
}
2020-06-10 14:52:44 +00:00
bool Application::offerLegacyLangPackSwitch() const {
2020-06-15 16:25:02 +00:00
return (accounts().list().size() == 1) && activeAccount().sessionExists();
}
bool Application::canApplyLangPackWithoutRestart() const {
2020-06-15 16:25:02 +00:00
for (const auto &[index, account] : accounts().list()) {
if (account->sessionExists()) {
return false;
}
}
return true;
}
void Application::setInternalLinkDomain(const QString &domain) const {
2018-12-04 10:32:06 +00:00
// This domain should start with 'http[s]://' and end with '/'.
// Like 'https://telegram.me/' or 'https://t.me/'.
auto validate = [](const auto &domain) {
const auto prefixes = {
qstr("https://"),
qstr("http://"),
};
2018-12-04 10:32:06 +00:00
for (const auto &prefix : prefixes) {
if (domain.startsWith(prefix, Qt::CaseInsensitive)) {
return domain.endsWith('/');
}
}
return false;
};
if (validate(domain) && domain != Global::InternalLinksDomain()) {
Global::SetInternalLinksDomain(domain);
}
}
QString Application::createInternalLink(const QString &query) const {
auto result = createInternalLinkFull(query);
auto prefixes = {
qstr("https://"),
qstr("http://"),
};
for (auto &prefix : prefixes) {
if (result.startsWith(prefix, Qt::CaseInsensitive)) {
return result.mid(prefix.size());
}
}
LOG(("Warning: bad internal url '%1'").arg(result));
return result;
}
QString Application::createInternalLinkFull(const QString &query) const {
return Global::InternalLinksDomain() + query;
}
void Application::checkStartUrl() {
if (!cStartUrl().isEmpty() && !locked()) {
2019-04-02 10:29:28 +00:00
const auto url = cStartUrl();
2017-06-27 20:11:38 +00:00
cSetStartUrl(QString());
if (!openLocalUrl(url, {})) {
2017-06-27 20:11:38 +00:00
cSetStartUrl(url);
}
}
}
bool Application::openLocalUrl(const QString &url, QVariant context) {
return openCustomUrl("tg://", LocalUrlHandlers(), url, context);
}
bool Application::openInternalUrl(const QString &url, QVariant context) {
return openCustomUrl("internal:", InternalUrlHandlers(), url, context);
}
2017-06-27 20:11:38 +00:00
bool Application::openCustomUrl(
const QString &protocol,
const std::vector<LocalUrlHandler> &handlers,
const QString &url,
const QVariant &context) {
const auto urlTrimmed = url.trimmed();
if (!urlTrimmed.startsWith(protocol, Qt::CaseInsensitive) || locked()) {
2017-06-27 20:11:38 +00:00
return false;
}
const auto command = urlTrimmed.midRef(protocol.size(), 8192);
2019-07-24 14:00:30 +00:00
const auto session = activeAccount().sessionExists()
? &activeAccount().session()
: nullptr;
2017-06-27 20:11:38 +00:00
using namespace qthelp;
const auto options = RegExOption::CaseInsensitive;
for (const auto &[expression, handler] : handlers) {
const auto match = regex_match(expression, command, options);
if (match) {
2019-07-24 14:00:30 +00:00
return handler(session, match, context);
}
2017-06-27 20:11:38 +00:00
}
return false;
2017-06-27 20:11:38 +00:00
}
void Application::lockByPasscode() {
_passcodeLock = true;
_window->setupPasscodeLock();
}
void Application::unlockPasscode() {
clearPasscodeLock();
2019-07-24 08:46:23 +00:00
if (_window) {
_window->clearPasscodeLock();
}
}
void Application::clearPasscodeLock() {
cSetPasscodeBadTries(0);
_passcodeLock = false;
}
bool Application::passcodeLocked() const {
return _passcodeLock.current();
}
void Application::updateNonIdle() {
_lastNonIdleTime = crl::now();
if (activeAccount().sessionExists()) {
activeAccount().session().updates().checkIdleFinish();
}
}
crl::time Application::lastNonIdleTime() const {
return std::max(
Platform::LastUserInputTime().value_or(0),
_lastNonIdleTime);
}
rpl::producer<bool> Application::passcodeLockChanges() const {
return _passcodeLock.changes();
}
rpl::producer<bool> Application::passcodeLockValue() const {
return _passcodeLock.value();
}
void Application::lockByTerms(const Window::TermsLock &data) {
if (!_termsLock || *_termsLock != data) {
_termsLock = std::make_unique<Window::TermsLock>(data);
_termsLockChanges.fire(true);
}
}
2020-06-15 16:25:02 +00:00
bool Application::someSessionExists() const {
const auto &list = _accounts->list();
for (const auto &[index, account] : list) {
if (account->sessionExists()) {
return true;
}
}
return false;
}
void Application::checkAutoLock() {
if (!Global::LocalPasscode()
|| passcodeLocked()
2020-06-15 16:25:02 +00:00
|| !someSessionExists()) {
_shouldLockAt = 0;
_autoLockTimer.cancel();
return;
}
checkLocalTime();
const auto now = crl::now();
const auto shouldLockInMs = Global::AutoLock() * 1000LL;
const auto checkTimeMs = now - lastNonIdleTime();
if (checkTimeMs >= shouldLockInMs || (_shouldLockAt > 0 && now > _shouldLockAt + kAutoLockTimeoutLateMs)) {
_shouldLockAt = 0;
_autoLockTimer.cancel();
lockByPasscode();
} else {
_shouldLockAt = now + (shouldLockInMs - checkTimeMs);
_autoLockTimer.callOnce(shouldLockInMs - checkTimeMs);
}
}
void Application::checkAutoLockIn(crl::time time) {
if (_autoLockTimer.isActive()) {
auto remain = _autoLockTimer.remainingTime();
if (remain > 0 && remain <= time) return;
}
_autoLockTimer.callOnce(time);
}
void Application::localPasscodeChanged() {
_shouldLockAt = 0;
_autoLockTimer.cancel();
checkAutoLock();
}
void Application::unlockTerms() {
if (_termsLock) {
_termsLock = nullptr;
_termsLockChanges.fire(false);
}
}
std::optional<Window::TermsLock> Application::termsLocked() const {
2018-09-21 16:28:46 +00:00
return _termsLock ? base::make_optional(*_termsLock) : std::nullopt;
}
rpl::producer<bool> Application::termsLockChanges() const {
return _termsLockChanges.events();
}
rpl::producer<bool> Application::termsLockValue() const {
return rpl::single(
_termsLock != nullptr
) | rpl::then(termsLockChanges());
}
bool Application::locked() const {
return passcodeLocked() || termsLocked();
}
rpl::producer<bool> Application::lockChanges() const {
return lockValue() | rpl::skip(1);
}
rpl::producer<bool> Application::lockValue() const {
using namespace rpl::mappers;
return rpl::combine(
passcodeLockValue(),
termsLockValue(),
_1 || _2);
}
bool Application::hasActiveWindow(not_null<Main::Session*> session) const {
if (App::quitting() || !_window) {
return false;
} else if (const auto controller = _window->sessionController()) {
if (&controller->session() == session) {
return _window->widget()->isActive();
}
}
return false;
}
void Application::saveCurrentDraftsToHistories() {
if (!_window) {
return;
} else if (const auto controller = _window->sessionController()) {
controller->content()->saveFieldToHistoryLocalDraft();
}
}
Window::Controller *Application::activeWindow() const {
return _window.get();
}
bool Application::closeActiveWindow() {
2017-08-08 09:56:10 +00:00
if (hideMediaView()) {
return true;
}
if (const auto window = activeWindow()) {
window->close();
2017-08-08 09:56:10 +00:00
return true;
}
return false;
}
bool Application::minimizeActiveWindow() {
2017-08-08 09:56:10 +00:00
hideMediaView();
if (const auto window = activeWindow()) {
window->minimize();
2017-08-08 09:56:10 +00:00
return true;
}
return false;
}
QWidget *Application::getFileDialogParent() {
return (_mediaView && _mediaView->isVisible())
? (QWidget*)_mediaView.get()
: activeWindow()
? (QWidget*)activeWindow()->widget()
: nullptr;
}
void Application::notifyFileDialogShown(bool shown) {
if (_mediaView) {
_mediaView->notifyFileDialogShown(shown);
}
}
2020-05-27 05:50:07 +00:00
QWidget *Application::getModalParent() {
2020-06-03 05:43:59 +00:00
return Platform::IsWayland()
2020-05-27 05:50:07 +00:00
? App::wnd()
: nullptr;
}
void Application::checkMediaViewActivation() {
if (_mediaView && !_mediaView->isHidden()) {
_mediaView->activateWindow();
QApplication::setActiveWindow(_mediaView.get());
_mediaView->setFocus();
}
}
QPoint Application::getPointForCallPanelCenter() const {
if (const auto window = activeWindow()) {
return window->getPointForCallPanelCenter();
}
2017-08-08 09:56:10 +00:00
return QApplication::desktop()->screenGeometry().center();
}
// macOS Qt bug workaround, sometimes no leaveEvent() gets to the nested widgets.
2019-09-13 16:45:48 +00:00
void Application::registerLeaveSubscription(not_null<QWidget*> widget) {
#ifdef Q_OS_MAC
2019-06-06 12:01:01 +00:00
if (const auto topLevel = widget->window()) {
if (topLevel == _window->widget()) {
2019-09-13 12:22:54 +00:00
auto weak = Ui::MakeWeak(widget);
2019-06-06 12:01:01 +00:00
auto subscription = _window->widget()->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
}
2019-09-13 16:45:48 +00:00
void Application::unregisterLeaveSubscription(not_null<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<void()> &&callable) {
Sandbox::Instance().postponeCall(std::move(callable));
}
void Application::refreshGlobalProxy() {
Sandbox::Instance().refreshGlobalProxy();
}
void Application::QuitAttempt() {
auto prevents = false;
2019-06-06 11:59:00 +00:00
if (IsAppLaunched()
&& App().activeAccount().sessionExists()
&& !Sandbox::Instance().isSavingSession()) {
if (App().activeAccount().session().updates().isQuitPrevent()) {
prevents = true;
}
2019-06-06 11:59:00 +00:00
if (App().activeAccount().session().api().isQuitPrevent()) {
prevents = true;
}
2019-06-06 11:59:00 +00:00
if (App().activeAccount().session().calls().isQuitPrevent()) {
prevents = true;
}
}
if (prevents) {
App().quitDelayed();
} else {
2019-01-18 11:26:43 +00:00
QApplication::quit();
}
}
void Application::quitPreventFinished() {
if (App::quitting()) {
QuitAttempt();
}
}
void Application::quitDelayed() {
if (!_private->quitTimer.isActive()) {
2019-01-18 11:26:43 +00:00
_private->quitTimer.setCallback([] { QApplication::quit(); });
_private->quitTimer.callOnce(kQuitPreventTimeoutMs);
}
}
2018-11-16 12:15:14 +00:00
void Application::startShortcuts() {
2018-11-16 12:15:14 +00:00
Shortcuts::Start();
2020-06-15 16:25:02 +00:00
_accounts->activeSessionChanges(
) | rpl::start_with_next([=](Main::Session *session) {
const auto support = session && session->supportMode();
Shortcuts::ToggleSupportShortcuts(support);
Platform::SetApplicationIcon(Window::CreateIcon(session));
}, _lifetime);
2018-11-16 12:15:14 +00:00
Shortcuts::Requests(
) | rpl::start_with_next([=](not_null<Shortcuts::Request*> 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);
}
2019-02-04 13:34:50 +00:00
bool IsAppLaunched() {
return (Application::Instance != nullptr);
}
Application &App() {
2019-02-04 13:34:50 +00:00
Expects(Application::Instance != nullptr);
return *Application::Instance;
}
} // namespace Core