ZaStoGram_desktop/Telegram/SourceFiles/boxes/connection_box.cpp
loop-uh f9095afd3b zsg_pathtest: stealth gate (selected server by default, all servers one at a time with a 10-20 s pause) and a headless developer hook
The probe no longer touches the whole proxy list at once: default scope is the proxy in use (or the WSS route
when none), every server only on the explicit Check all proxies tick; DNS/TCP of a host happen in its own turn.
ZSG_PATHTEST_SELFTEST runs the check without a window for real-traffic verification.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-29 14:08:47 +00:00

3618 lines
100 KiB
C++

/*
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 "boxes/connection_box.h"
#include <QtCore/QTimer>
#include "zsg_naive/zsg_warp.h"
#include "zsg_pathtest/pathtest_runner.h"
#include "base/qt/qt_key_modifiers.h"
#include "base/call_delayed.h"
#include "base/qthelp_regex.h"
#include "base/qthelp_url.h"
#include "base/weak_ptr.h"
#include "boxes/abstract_box.h" // Ui::show().
#include "core/application.h"
#include "core/core_settings.h"
#include "core/file_utilities.h"
#include "core/local_url_handlers.h"
#include "lang/lang_keys.h"
#include "main/main_account.h"
#include "main/main_session.h"
#include "mtproto/instance/mtp_instance.h"
#include "mtproto/runtime/connection_status.h"
#include "mtproto/session/session_state.h"
#include "mtproto/config/mtproto_config.h"
#include "mtproto/proxy/mtproxy/endpoint_identity.h"
#include "mtproto/proxy/check.h"
#include "mtproto/proxy/diagnostics.h"
#include "mtproto/proxy/proxy_services.h"
#include "mtproto/proxy/transport_policy.h"
#include "mtproto/runtime/runtime_environment.h"
#include "mtproto/web_proxy/web_proxy_transport.h"
#include "qr/qr_generate.h"
#include "settings/settings_common.h"
#include "settings.h"
#include "storage/localstorage.h"
#include "ui/boxes/confirm_box.h"
#include "ui/boxes/peer_qr_box.h"
#include "ui/effects/animations.h"
#include "ui/effects/radial_animation.h"
#include "ui/effects/round_checkbox.h"
#include "ui/text/text_options.h"
#include "ui/text/text_utilities.h"
#include "ui/toast/toast.h"
#include "ui/widgets/fields/input_field.h"
#include "ui/widgets/fields/number_input.h"
#include "ui/widgets/fields/password_input.h"
#include "ui/widgets/menu/menu_add_action_callback.h"
#include "ui/widgets/menu/menu_add_action_callback_factory.h"
#include "ui/widgets/buttons.h"
#include "ui/widgets/checkbox.h"
#include "ui/widgets/discrete_sliders.h"
#include "ui/widgets/dropdown_menu.h"
#include "ui/widgets/labels.h"
#include "ui/widgets/popup_menu.h"
#include "ui/widgets/selecting_scroll.h"
#include "ui/wrap/slide_wrap.h"
#include "ui/wrap/table_layout.h"
#include "ui/wrap/vertical_layout.h"
#include "ui/wrap/vertical_layout_reorder.h"
#include "ui/basic_click_handlers.h"
#include "ui/painter.h"
#include "ui/rect.h"
#include "ui/ui_utility.h"
#include "ui/vertical_list.h"
#include "window/window_session_controller.h"
#include "styles/style_boxes.h"
#include "styles/style_chat_helpers.h"
#include "styles/style_connection_box.h"
#include "styles/style_info.h"
#include "styles/style_intro.h"
#include "styles/style_layers.h"
#include "styles/style_menu_icons.h"
#include "styles/style_settings.h"
#include <QtCore/QDir>
#include <QtCore/QUrl>
#include <QtGui/QDesktopServices>
#include <QtGui/QGuiApplication>
#include <QtGui/QClipboard>
#include <QtCore/QStringList>
#include <QtWidgets/QTextEdit>
#include <rpl/skip.h>
namespace {
constexpr auto kSaveSettingsDelayedTimeout = crl::time(1000);
using ProxyData = MTP::ProxyData;
using ItemState = ProxiesBoxController::ItemState;
struct TopButtonMenuState {
~TopButtonMenuState() {
closing = true;
}
bool closing = false;
base::unique_qptr<Ui::PopupMenu> menu;
};
[[nodiscard]] std::vector<QString> ExtractLinkCandidates(const QString &input) {
auto urls = std::vector<QString>();
static const auto urlRegex = QRegularExpression(
R"((?:https?:\/\/[^\s]+|tg:\/\/[^\s]+|naive\+https:\/\/[^\s]+|(?:www\.)?(?:t\.me|telegram\.me|telegram\.dog)\/[^\s]+))",
QRegularExpression::CaseInsensitiveOption);
auto it = urlRegex.globalMatch(input);
while (it.hasNext()) {
urls.push_back(it.next().captured(0));
}
return urls;
}
[[nodiscard]] bool ProxyDataIsShareable(const ProxyData &proxy) {
using Type = ProxyData::Type;
return (proxy.type == Type::Socks5)
|| (proxy.type == Type::Mtproto)
|| (proxy.type == Type::Web)
|| (proxy.type == Type::Naive);
}
[[nodiscard]] bool ProxyCheckStatusTerminal(MTP::ProxyCheckStatus status) {
switch (status) {
case MTP::ProxyCheckStatus::WaitingForConnectionSlot:
case MTP::ProxyCheckStatus::ConnectedByActiveSession:
return true;
case MTP::ProxyCheckStatus::Idle:
case MTP::ProxyCheckStatus::Resolving:
case MTP::ProxyCheckStatus::TcpConnected:
case MTP::ProxyCheckStatus::ClientHelloSent:
case MTP::ProxyCheckStatus::ServerHelloOk:
case MTP::ProxyCheckStatus::FirstTlsAppData:
case MTP::ProxyCheckStatus::FirstMtprotoPayload:
return false;
}
return false;
}
[[nodiscard]] QString ProxyCheckStatusText(MTP::ProxyCheckStatus status) {
switch (status) {
case MTP::ProxyCheckStatus::Idle:
return tr::lng_proxy_box_table_checking(tr::now);
case MTP::ProxyCheckStatus::WaitingForConnectionSlot:
return tr::lng_proxy_box_table_waiting_slot(tr::now);
case MTP::ProxyCheckStatus::Resolving:
return tr::lng_proxy_box_table_resolving(tr::now);
case MTP::ProxyCheckStatus::TcpConnected:
return tr::lng_proxy_box_table_tcp_connected(tr::now);
case MTP::ProxyCheckStatus::ClientHelloSent:
return tr::lng_proxy_box_table_client_hello_sent(tr::now);
case MTP::ProxyCheckStatus::ServerHelloOk:
return tr::lng_proxy_box_table_server_hello_ok(tr::now);
case MTP::ProxyCheckStatus::FirstTlsAppData:
return tr::lng_proxy_box_table_first_tls_appdata(tr::now);
case MTP::ProxyCheckStatus::FirstMtprotoPayload:
return tr::lng_proxy_box_table_first_mtproto(tr::now);
case MTP::ProxyCheckStatus::ConnectedByActiveSession:
return tr::lng_proxy_box_table_connected_active(tr::now);
}
return tr::lng_proxy_box_table_checking(tr::now);
}
[[nodiscard]] style::color ProxyCheckStatusColor(MTP::ProxyCheckStatus status) {
switch (status) {
case MTP::ProxyCheckStatus::ConnectedByActiveSession:
case MTP::ProxyCheckStatus::FirstMtprotoPayload:
return st::proxyRowStatusFgAvailable;
case MTP::ProxyCheckStatus::Idle:
case MTP::ProxyCheckStatus::WaitingForConnectionSlot:
case MTP::ProxyCheckStatus::Resolving:
case MTP::ProxyCheckStatus::TcpConnected:
case MTP::ProxyCheckStatus::ClientHelloSent:
case MTP::ProxyCheckStatus::ServerHelloOk:
case MTP::ProxyCheckStatus::FirstTlsAppData:
return st::proxyRowStatusFg;
}
return st::proxyRowStatusFg;
}
[[nodiscard]] QString ProxyDataToQueryPath(const ProxyData &proxy) {
using Type = ProxyData::Type;
const auto path = [&] {
switch (proxy.type) {
case Type::Socks5: return u"socks"_q;
case Type::Mtproto: return u"proxy"_q;
case Type::Web: return u"webproxy"_q;
case Type::Naive: return u"naive"_q;
case Type::None:
case Type::Http: return QString();
}
Unexpected("Proxy type in ProxyDataToQueryPath.");
}();
if (path.isEmpty()) {
return QString();
}
const auto server = (proxy.type == Type::Web)
? qthelp::url_encode(proxy.webAddress())
: proxy.host;
return path
+ "?server=" + server
+ ((proxy.type != Type::Web)
? "&port=" + QString::number(proxy.port) : "")
+ (((proxy.type == Type::Socks5 || proxy.type == Type::Naive)
&& !proxy.user.isEmpty())
? "&user=" + qthelp::url_encode(proxy.user) : "")
+ (((proxy.type == Type::Socks5 || proxy.type == Type::Naive)
&& !proxy.password.isEmpty())
? "&pass=" + qthelp::url_encode(proxy.password) : "")
+ (((proxy.type == Type::Mtproto || proxy.type == Type::Web)
&& !proxy.password.isEmpty())
? "&secret=" + ((proxy.type == Type::Web)
? MTP::EncodeWebProxyLinkSecret(proxy)
: proxy.password) : "");
}
[[nodiscard]] QString ProxyDataToLocalLink(const ProxyData &proxy) {
const auto queryPath = ProxyDataToQueryPath(proxy);
return queryPath.isEmpty() ? QString() : (u"tg://"_q + queryPath);
}
[[nodiscard]] QString ProxyDataToPublicLink(
not_null<Main::Account*> account,
const ProxyData &proxy) {
const auto queryPath = ProxyDataToQueryPath(proxy);
if (queryPath.isEmpty()) {
return QString();
}
if (const auto session = account->maybeSession()) {
return session->createInternalLinkFull(queryPath);
}
auto domain = MTP::ConfigFields(
account->mtp().environment()
).internalLinksDomain;
if (domain.endsWith('/') && queryPath.startsWith('/')) {
domain.chop(1);
} else if (!domain.endsWith('/') && !queryPath.startsWith('/')) {
domain += '/';
}
return domain + queryPath;
}
[[nodiscard]] QColor ProxyQrActiveColor() {
return QColor(0x40, 0xA7, 0xE3);
}
[[nodiscard]] QImage ProxyQr(const Qr::Data &data, int pixel, int max = 0) {
Expects(data.size > 0);
const auto available = max
? std::max(max - 2 * st::introQrBackgroundSkip, 1)
: 0;
if (available > 0 && data.size * pixel > available) {
pixel = std::max(available / data.size, 1);
}
return Qr::Generate(
data,
pixel * style::DevicePixelRatio(),
Qt::black,
Qt::white);
}
[[nodiscard]] QImage ProxyQrLogo() {
const auto size = QSize(st::introQrCenterSize, st::introQrCenterSize);
auto result = QImage(
size * style::DevicePixelRatio(),
QImage::Format_ARGB32_Premultiplied);
result.fill(Qt::transparent);
result.setDevicePixelRatio(style::DevicePixelRatio());
{
auto p = QPainter(&result);
auto hq = PainterHighQualityEnabler(p);
p.setBrush(ProxyQrActiveColor());
p.setPen(Qt::NoPen);
p.drawEllipse(QRect(QPoint(), size));
st::introQrPlane.paintInCenter(p, QRect(QPoint(), size));
}
return result;
}
[[nodiscard]] QImage ProxyQrTile(const QString &link, int max = 0) {
const auto data = Qr::Encode(link, Qr::Redundancy::Quartile);
const auto qr = ProxyQr(
data,
st::introQrPixel,
max);
const auto qrSize = qr.width() / style::DevicePixelRatio();
const auto skip = st::introQrBackgroundSkip;
const auto size = QSize(qrSize + 2 * skip, qrSize + 2 * skip);
auto result = QImage(
size * style::DevicePixelRatio(),
QImage::Format_ARGB32_Premultiplied);
result.fill(Qt::transparent);
result.setDevicePixelRatio(style::DevicePixelRatio());
{
auto p = QPainter(&result);
auto hq = PainterHighQualityEnabler(p);
p.setPen(Qt::NoPen);
p.setBrush(Qt::white);
p.drawRoundedRect(
QRect(QPoint(), size),
st::introQrBackgroundRadius,
st::introQrBackgroundRadius);
p.drawImage(QRect(skip, skip, qrSize, qrSize), qr);
const auto logo = ProxyQrLogo();
p.drawImage(
QRect(
(size.width() - st::introQrCenterSize) / 2,
(size.height() - st::introQrCenterSize) / 2,
st::introQrCenterSize,
st::introQrCenterSize),
logo);
}
return result;
}
[[nodiscard]] QImage ProxyQrForShare(const QString &link) {
return ProxyQrTile(
link,
st::boxWidth - st::boxRowPadding.left() - st::boxRowPadding.right());
}
void ShowProxyQrBox(std::shared_ptr<Ui::Show> show, const QString &link) {
show->showBox(Box([=](not_null<Ui::GenericBox*> box) {
box->setTitle(tr::lng_proxy_edit_share_qr_box_title());
box->addButton(tr::lng_about_done(), [=] { box->closeBox(); });
const auto copyCallback = [=, image = ProxyQrForShare(link)] {
QGuiApplication::clipboard()->setImage(image);
show->showToast({
.text = { tr::lng_group_invite_qr_copied(tr::now) },
.iconLottie = u"toast/copy"_q,
.iconLottieSize = st::toastLottieIconSize,
});
};
const auto qr = ProxyQrTile(
link,
st::boxWidth
- st::boxRowPadding.left()
- st::boxRowPadding.right());
const auto size = qr.width() / style::DevicePixelRatio();
const auto height = st::inviteLinkQrSkip * 2 + size;
const auto container = box->addRow(
object_ptr<Ui::BoxContentDivider>(box, height),
st::inviteLinkQrMargin);
const auto button = Ui::CreateChild<Ui::AbstractButton>(container);
button->resize(size, size);
button->paintRequest(
) | rpl::on_next([=] {
QPainter(button).drawImage(QRect(0, 0, size, size), qr);
}, button->lifetime());
container->widthValue(
) | rpl::on_next([=](int width) {
button->move((width - size) / 2, st::inviteLinkQrSkip);
}, button->lifetime());
button->setClickedCallback(copyCallback);
box->addLeftButton(tr::lng_group_invite_context_copy(), copyCallback);
}));
}
void ShareProxy(
std::shared_ptr<Ui::Show> show,
not_null<Main::Account*> account,
const ProxyData &proxy,
bool qr) {
if (!ProxyDataIsShareable(proxy)) {
return;
}
const auto qrLink = ProxyDataToLocalLink(proxy);
if (qrLink.isEmpty()) {
return;
}
if (qr) {
if (account->sessionExists()) {
show->showBox(Box([=](not_null<Ui::GenericBox*> box) {
Ui::FillPeerQrBox(
box,
nullptr,
qrLink,
rpl::single(QString()),
tr::lng_proxy_edit_share_qr_box_title());
}));
} else {
ShowProxyQrBox(show, qrLink);
}
return;
}
const auto internal = base::IsCtrlPressed()
|| base::IsAltPressed()
|| base::IsShiftPressed();
const auto shareLink = internal
? qrLink
: ProxyDataToPublicLink(account, proxy);
if (shareLink.isEmpty()) {
return;
}
TextUtilities::SetClipboardText(TextForMimeData::Simple(shareLink));
show->showToast({
.text = { tr::lng_username_copied(tr::now) },
.iconLottie = u"toast/voip_invite"_q,
.iconLottieSize = st::toastLottieIconSize,
});
}
[[nodiscard]] ProxyData ProxyDataFromFields(
ProxyData::Type type,
const QMap<QString, QString> &fields) {
auto proxy = ProxyData();
proxy.type = type;
const auto web = (type == ProxyData::Type::Web);
const auto server = fields.value(u"server"_q);
proxy.port = web ? 443 : fields.value(u"port"_q).toUInt();
if (web) {
proxy.setWebAddress(
server.isEmpty() ? fields.value(u"host"_q) : server);
} else {
proxy.host = server;
}
if (type == ProxyData::Type::Socks5 || type == ProxyData::Type::Naive) {
proxy.user = fields.value(u"user"_q);
proxy.password = fields.value(u"pass"_q);
} else if (type == ProxyData::Type::Mtproto || web) {
proxy.password = fields.value(u"secret"_q);
proxy.password.replace('+', '-').replace('/', '_');
if (web) {
proxy.password = MTP::DecodeWebProxyLinkSecret(
proxy.password,
!proxy.webBasePath().isEmpty());
}
}
return proxy;
};
[[nodiscard]] ProxyData ProxyDataFromLocalUrl(const QString &local) {
const auto protocol = u"tg://"_q;
const auto proxyString = u"proxy"_q;
const auto socksString = u"socks"_q;
const auto webproxyString = u"webproxy"_q;
const auto naiveString = u"naive"_q;
if (!local.startsWith(protocol + proxyString, Qt::CaseInsensitive)
&& !local.startsWith(protocol + socksString, Qt::CaseInsensitive)
&& !local.startsWith(protocol + webproxyString, Qt::CaseInsensitive)
&& !local.startsWith(protocol + naiveString, Qt::CaseInsensitive)) {
return ProxyData();
}
const auto command = base::StringViewMid(local, protocol.size(), 8192);
using namespace qthelp;
const auto options = RegExOption::CaseInsensitive;
for (const auto &[expression, _] : Core::LocalUrlHandlers()) {
const auto midExpression = base::StringViewMid(expression, 1);
const auto isSocks = midExpression.startsWith(socksString);
const auto isWeb = midExpression.startsWith(webproxyString);
const auto isNaive = midExpression.startsWith(naiveString);
if (!midExpression.startsWith(proxyString)
&& !isSocks
&& !isWeb
&& !isNaive) {
continue;
}
const auto match = regex_match(expression, command, options);
if (!match) {
continue;
}
const auto type = isWeb
? ProxyData::Type::Web
: isNaive
? ProxyData::Type::Naive
: isSocks
? ProxyData::Type::Socks5
: ProxyData::Type::Mtproto;
auto fields = url_parse_params(
match->captured(1),
qthelp::UrlParamNameTransform::ToLower);
return ProxyDataFromFields(type, fields);
}
return ProxyData();
}
[[nodiscard]] ProxyData ProxyDataFromClipboard() {
const auto candidates = ExtractLinkCandidates(
QGuiApplication::clipboard()->text());
if (candidates.size() != 1) {
return ProxyData();
}
const auto trimmed = candidates.front().trimmed();
const auto converted = Core::TryConvertUrlToLocal(trimmed);
const auto local = converted.isEmpty() ? trimmed : converted;
const auto proxy = ProxyDataFromLocalUrl(local);
return proxy.valid() ? proxy : ProxyData();
}
void AddProxyFromClipboard(
not_null<ProxiesBoxController*> controller,
std::shared_ptr<Ui::Show> show) {
const auto proxyString = u"proxy"_q;
const auto socksString = u"socks"_q;
const auto webproxyString = u"webproxy"_q;
const auto protocol = u"tg://"_q;
const auto maybeUrls = ExtractLinkCandidates(
QGuiApplication::clipboard()->text());
const auto isSingle = maybeUrls.size() == 1;
enum class Result {
Success,
Failed,
Unsupported,
IncorrectSecret,
Invalid,
};
const auto proceedUrl = [=](const QString &local) {
const auto isProxyLink
= local.startsWith(protocol + proxyString, Qt::CaseInsensitive)
|| local.startsWith(protocol + socksString, Qt::CaseInsensitive)
|| local.startsWith(
protocol + webproxyString,
Qt::CaseInsensitive);
if (!isProxyLink) {
return Result::Failed;
}
const auto proxy = ProxyDataFromLocalUrl(local);
if (proxy.type == ProxyData::Type::None) {
return Result::Success;
} else if (!proxy) {
const auto status = proxy.status();
return (status == ProxyData::Status::Unsupported)
? Result::Unsupported
: (status == ProxyData::Status::IncorrectSecret)
? Result::IncorrectSecret
: Result::Invalid;
}
const auto contains = controller->contains(proxy);
const auto toast = (contains
? tr::lng_proxy_add_from_clipboard_existing_toast
: tr::lng_proxy_add_from_clipboard_good_toast)(tr::now);
if (isSingle) {
show->showToast(toast);
}
if (!contains) {
controller->addNewItem(proxy);
}
return Result::Success;
};
auto success = Result::Failed;
for (const auto &maybeUrl : maybeUrls) {
const auto trimmed = maybeUrl.trimmed();
const auto local = Core::TryConvertUrlToLocal(trimmed);
const auto check = local.isEmpty() ? trimmed : local;
const auto result = proceedUrl(check);
if (success != Result::Success) {
success = result;
}
}
if (success != Result::Success) {
if (success == Result::Failed) {
show->showToast(
tr::lng_proxy_add_from_clipboard_failed_toast(tr::now));
} else {
show->showBox(Ui::MakeInformBox(
((success == Result::IncorrectSecret)
? tr::lng_proxy_incorrect_secret(tr::now, tr::rich)
: (success == Result::Unsupported)
? tr::lng_proxy_unsupported(tr::now, tr::rich)
: tr::lng_proxy_invalid(tr::now, tr::rich))));
}
}
}
class HostInput : public Ui::MaskedInputField {
public:
HostInput(
QWidget *parent,
const style::InputField &st,
rpl::producer<QString> placeholder,
const QString &val);
protected:
void correctValue(
const QString &was,
int wasCursor,
QString &now,
int &nowCursor) override;
};
HostInput::HostInput(
QWidget *parent,
const style::InputField &st,
rpl::producer<QString> placeholder,
const QString &val)
: MaskedInputField(parent, st, std::move(placeholder), val) {
setInputMethodHints(Qt::ImhUrlCharactersOnly
| Qt::ImhNoAutoUppercase
| Qt::ImhNoPredictiveText);
}
void HostInput::correctValue(
const QString &was,
int wasCursor,
QString &now,
int &nowCursor) {
QString newText;
int newCursor = nowCursor;
newText.reserve(now.size());
for (auto i = 0, l = int(now.size()); i < l; ++i) {
if (now[i] == ',') {
newText.append('.');
} else {
newText.append(now[i]);
}
}
setCorrectedText(now, nowCursor, newText, newCursor);
}
class Base64UrlInput : public Ui::MaskedInputField {
public:
Base64UrlInput(
QWidget *parent,
const style::InputField &st,
rpl::producer<QString> placeholder,
const QString &val);
protected:
void correctValue(
const QString &was,
int wasCursor,
QString &now,
int &nowCursor) override;
};
Base64UrlInput::Base64UrlInput(
QWidget *parent,
const style::InputField &st,
rpl::producer<QString> placeholder,
const QString &val)
: MaskedInputField(parent, st, std::move(placeholder), val) {
setInputMethodHints(Qt::ImhLatinOnly
| Qt::ImhNoAutoUppercase
| Qt::ImhNoPredictiveText
| Qt::ImhSensitiveData);
static const auto RegExp = QRegularExpression("^[a-zA-Z0-9_\\-]+$");
if (!RegExp.match(val).hasMatch()) {
setText(QString());
}
}
void Base64UrlInput::correctValue(
const QString &was,
int wasCursor,
QString &now,
int &nowCursor) {
QString newText;
newText.reserve(now.size());
auto newPos = nowCursor;
for (auto i = 0, l = int(now.size()); i < l; ++i) {
const auto ch = now[i];
if ((ch >= '0' && ch <= '9')
|| (ch >= 'a' && ch <= 'z')
|| (ch >= 'A' && ch <= 'Z')
|| (ch == '-')
|| (ch == '_')) {
newText.append(ch);
} else if (i < nowCursor) {
--newPos;
}
}
setCorrectedText(now, nowCursor, newText, newPos);
}
class ProxyRow : public Ui::RippleButton {
public:
using View = ProxiesBoxController::ItemView;
using State = ProxiesBoxController::ItemState;
ProxyRow(QWidget *parent, View &&view);
void updateFields(View &&view);
void setChosen(bool selecting, bool chosen, anim::type animated);
[[nodiscard]] bool deleted() const;
rpl::producer<> chooseClicks() const;
rpl::producer<> deleteClicks() const;
rpl::producer<> restoreClicks() const;
rpl::producer<> checkClicks() const;
rpl::producer<> editClicks() const;
rpl::producer<> shareClicks() const;
rpl::producer<> showQrClicks() const;
rpl::producer<> openBrowserClicks() const;
protected:
int resizeGetHeight(int newWidth) override;
void paintEvent(QPaintEvent *e) override;
void contextMenuEvent(QContextMenuEvent *e) override;
private:
using AddAction = Fn<void(
const QString &text,
Fn<void()> callback,
const style::icon *icon)>;
void setupControls(View &&view);
int countAvailableWidth() const;
void radialAnimationCallback();
void paintCheck(Painter &p);
void paintRadio(Painter &p);
void paintChosen(Painter &p);
void paintMenuToggle(Painter &p);
void showMenu();
void fillMenu(const AddAction &addAction);
View _view;
Ui::Text::String _title;
object_ptr<Ui::IconButton> _menuToggle;
rpl::event_stream<> _chooseClicks;
rpl::event_stream<> _deleteClicks;
rpl::event_stream<> _restoreClicks;
rpl::event_stream<> _checkClicks;
rpl::event_stream<> _editClicks;
rpl::event_stream<> _shareClicks;
rpl::event_stream<> _showQrClicks;
rpl::event_stream<> _openBrowserClicks;
base::unique_qptr<Ui::DropdownMenu> _menu;
base::unique_qptr<Ui::PopupMenu> _contextMenu;
bool _set = false;
Ui::Animations::Simple _toggled;
Ui::Animations::Simple _setAnimation;
bool _selecting = false;
Ui::Animations::Simple _selectingAnimation;
Ui::RoundCheckbox _check;
std::unique_ptr<Ui::InfiniteRadialAnimation> _progress;
std::unique_ptr<Ui::InfiniteRadialAnimation> _checking;
int _skipLeft = 0;
int _skipRight = 0;
};
class ProxySettingsColumns final : public Ui::RpWidget {
public:
explicit ProxySettingsColumns(QWidget *parent)
: RpWidget(parent)
, _left(this)
, _right(this) {
}
[[nodiscard]] not_null<Ui::VerticalLayout*> left() const {
return _left.data();
}
[[nodiscard]] not_null<Ui::VerticalLayout*> right() const {
return _right.data();
}
protected:
int resizeGetHeight(int newWidth) override {
const auto wideEnough = newWidth >= st::proxySettingsListColumnWidth
+ st::proxySettingsColumnSkip
+ st::proxySettingsControlsMinWidth;
if (!wideEnough) {
_left->resizeToWidth(newWidth);
const auto leftHeight = _left->height();
_left->setGeometryToLeft(0, 0, newWidth, leftHeight, newWidth);
_right->resizeToWidth(newWidth);
const auto rightHeight = _right->height();
_right->setGeometryToLeft(
0,
leftHeight,
newWidth,
rightHeight,
newWidth);
return leftHeight + rightHeight;
}
const auto leftWidth = st::proxySettingsListColumnWidth;
const auto rightLeft = leftWidth + st::proxySettingsColumnSkip;
const auto rightWidth = newWidth - rightLeft;
_left->resizeToWidth(leftWidth);
const auto leftHeight = _left->height();
_right->resizeToWidth(rightWidth);
const auto rightHeight = _right->height();
_left->setGeometryToLeft(0, 0, leftWidth, leftHeight, newWidth);
_right->setGeometryToLeft(
rightLeft,
0,
rightWidth,
rightHeight,
newWidth);
return std::max(leftHeight, rightHeight);
}
private:
object_ptr<Ui::VerticalLayout> _left;
object_ptr<Ui::VerticalLayout> _right;
};
class ProxiesBox : public Ui::BoxContent {
public:
using View = ProxiesBoxController::ItemView;
ProxiesBox(
QWidget*,
not_null<ProxiesBoxController*> controller,
Core::SettingsProxy &settings,
const QString &highlightId = QString());
void beginInitialRows();
void finishInitialRows();
protected:
void prepare() override;
void showFinished() override;
void keyPressEvent(QKeyEvent *e) override;
private:
void setupContent();
void setupTopButton();
void createNoRowsLabel();
void addNewProxy();
void applyView(View &&view);
void setupButtons(int id, not_null<ProxyRow*> button);
int rowHeight() const;
void refreshRouteViaWss();
void refreshReorder();
void refreshButtons();
void refreshSelection();
void toggleChosen(int id);
void chooseRange(int fromId, int tillId, bool chosen);
void handleRowEvent(int id, not_null<QEvent*> e);
void rowClicked(int id);
void updateDragSelection(QPoint globalPosition);
void finishPress();
void cancelPress();
[[nodiscard]] int rowIdAt(QPoint globalPosition) const;
[[nodiscard]] int dragScrollDelta(QPoint globalPosition) const;
void clearChosen();
void deleteChosen();
void shareChosen();
not_null<ProxiesBoxController*> _controller;
Core::SettingsProxy &_settings;
QPointer<Ui::Checkbox> _tryIPv6;
QPointer<Ui::Checkbox> _fastWarmup;
std::shared_ptr<Ui::RadioenumGroup<ProxyData::Settings>> _proxySettings;
QPointer<Ui::Checkbox> _routeViaWss;
QPointer<Ui::DividerLabel> _about;
base::unique_qptr<Ui::RpWidget> _noRows;
object_ptr<Ui::VerticalLayout> _initialWrap;
QPointer<Ui::VerticalLayout> _wrap;
base::flat_map<int, base::unique_qptr<ProxyRow>> _rows;
std::unique_ptr<Ui::VerticalLayoutReorder> _reorder;
int _reordering = 0;
struct Press {
int id = 0;
bool selection = false;
bool chosen = false;
bool dragged = false;
bool held = true;
base::flat_set<int> initial;
};
base::flat_set<int> _chosen;
std::optional<Press> _press;
int _anchorId = 0;
bool _selecting = false;
QPointer<Ui::RpWidget> _inner;
QPointer<Ui::RpWidget> _addProxyButton;
QPointer<Ui::RpWidget> _shareListButton;
QString _highlightId;
bool _initializingRows = false;
};
class ProxyBox final : public Ui::BoxContent {
public:
ProxyBox(
QWidget*,
const ProxyData &data,
Fn<void(ProxyData)> callback,
Fn<void(ProxyData)> shareCallback);
private:
using Type = ProxyData::Type;
void prepare() override;
void setInnerFocus() override {
if (_type->current() == Type::Web) {
_webHost->setFocusFast();
} else {
_host->setFocusFast();
}
}
void refreshButtons();
ProxyData collectData();
void save();
void share();
void setupControls(const ProxyData &data);
void setupTypes();
void setupSocketAddress(const ProxyData &data);
void setupWebAddress(const ProxyData &data);
void setupCredentials(const ProxyData &data);
void setupMtprotoCredentials(const ProxyData &data);
void addLabel(
not_null<Ui::VerticalLayout*> parent,
const QString &text) const;
const bool _allowShare = false;
Fn<void(ProxyData)> _callback;
Fn<void(ProxyData)> _shareCallback;
object_ptr<Ui::VerticalLayout> _content;
std::shared_ptr<Ui::RadioenumGroup<Type>> _type;
QPointer<Ui::SlideWrap<>> _aboutSponsored;
QPointer<HostInput> _host;
QPointer<Ui::NumberInput> _port;
QPointer<Ui::InputField> _user;
QPointer<Ui::PasswordInput> _password;
QPointer<Base64UrlInput> _secret;
QPointer<Ui::InputField> _webHost;
QPointer<Ui::SlideWrap<Ui::VerticalLayout>> _socketAddress;
QPointer<Ui::SlideWrap<Ui::VerticalLayout>> _webAddress;
QPointer<Ui::SlideWrap<Ui::VerticalLayout>> _credentials;
QPointer<Ui::SlideWrap<Ui::VerticalLayout>> _mtprotoCredentials;
};
ProxyRow::ProxyRow(QWidget *parent, View &&view)
: RippleButton(parent, st::proxyRowRipple)
, _menuToggle(this, st::topBarMenuToggle)
, _check(st::proxyRowCheck, [=] { update(); }) {
setupControls(std::move(view));
}
void ProxyRow::setChosen(bool selecting, bool chosen, anim::type animated) {
_check.setChecked(chosen, animated);
if (_selecting != selecting) {
_selecting = selecting;
if (_selecting) {
_menuToggle->hide();
}
_selectingAnimation.start(
[=] { update(); },
_selecting ? 0. : 1.,
_selecting ? 1. : 0.,
st::defaultRadio.duration);
_selectingAnimation.setFinishedCallback([=] {
_menuToggle->setVisible(!_selecting);
});
if (animated == anim::type::instant) {
_selectingAnimation.stop();
_menuToggle->setVisible(!_selecting);
}
}
}
bool ProxyRow::deleted() const {
return _view.deleted;
}
rpl::producer<> ProxyRow::chooseClicks() const {
return _chooseClicks.events();
}
rpl::producer<> ProxyRow::deleteClicks() const {
return _deleteClicks.events();
}
rpl::producer<> ProxyRow::restoreClicks() const {
return _restoreClicks.events();
}
rpl::producer<> ProxyRow::checkClicks() const {
return _checkClicks.events();
}
rpl::producer<> ProxyRow::editClicks() const {
return _editClicks.events();
}
rpl::producer<> ProxyRow::shareClicks() const {
return _shareClicks.events();
}
rpl::producer<> ProxyRow::showQrClicks() const {
return _showQrClicks.events();
}
rpl::producer<> ProxyRow::openBrowserClicks() const {
return _openBrowserClicks.events();
}
void ProxyRow::setupControls(View &&view) {
updateFields(std::move(view));
_toggled.stop();
_setAnimation.stop();
_menuToggle->addClickHandler([=] { showMenu(); });
}
int ProxyRow::countAvailableWidth() const {
const auto selecting = _selectingAnimation.value(_selecting ? 1. : 0.);
return width()
- _skipLeft
- anim::interpolate(
_skipRight,
st::proxyRowSelectingSkipRight,
selecting);
}
void ProxyRow::updateFields(View &&view) {
if (_view.selected != view.selected) {
_toggled.start(
[=] { update(); },
view.selected ? 0. : 1.,
view.selected ? 1. : 0.,
st::defaultRadio.duration);
}
_view = std::move(view);
const auto endpoint = _view.web
? _view.host
: _view.host + ':' + QString::number(_view.port);
_title.setMarkedText(
st::proxyRowTitleStyle,
TextWithEntities()
.append(_view.type)
.append(' ')
.append(tr::link(endpoint, QString())),
Ui::ItemTextDefaultOptions());
const auto state = _view.state;
if (state == State::Connecting) {
if (!_progress) {
_progress = std::make_unique<Ui::InfiniteRadialAnimation>(
[=] { radialAnimationCallback(); },
st::proxyCheckingAnimation);
}
_progress->start();
} else if (_progress) {
_progress->stop();
}
if (state == State::Checking
&& !ProxyCheckStatusTerminal(_view.progressStatus)) {
if (!_checking) {
_checking = std::make_unique<Ui::InfiniteRadialAnimation>(
[=] { radialAnimationCallback(); },
st::proxyCheckingAnimation);
_checking->start();
}
} else {
_checking = nullptr;
}
const auto set = (state == State::Connecting || state == State::Online);
if (_set != set) {
_set = set;
_setAnimation.start(
[=] { update(); },
_set ? 0. : 1.,
_set ? 1. : 0.,
st::defaultRadio.duration);
}
setPointerCursor(!_view.deleted);
update();
}
void ProxyRow::radialAnimationCallback() {
if (!anim::Disabled()) {
update();
}
}
int ProxyRow::resizeGetHeight(int newWidth) {
const auto result = st::proxyRowPadding.top()
+ st::semiboldFont->height
+ st::proxyRowSkip
+ st::normalFont->height
+ st::proxyRowPadding.bottom();
auto right = st::proxyRowPadding.right();
_menuToggle->moveToRight(
right,
(result - _menuToggle->height()) / 2,
newWidth);
right += _menuToggle->width();
_skipRight = right;
_skipLeft = st::proxyRowPadding.left()
+ st::proxyRowIconSkip;
return result;
}
void ProxyRow::paintEvent(QPaintEvent *e) {
Painter p(this);
if (!_view.deleted) {
paintRipple(p, 0, 0);
}
const auto left = _skipLeft;
const auto availableWidth = countAvailableWidth();
auto top = st::proxyRowPadding.top();
if (_view.deleted) {
p.setOpacity(st::stickersRowDisabledOpacity);
}
paintCheck(p);
paintMenuToggle(p);
p.setPen(st::proxyRowTitleFg);
p.setFont(st::semiboldFont);
p.setTextPalette(st::proxyRowTitlePalette);
_title.drawLeftElided(p, left, top, availableWidth, width());
top += st::semiboldFont->height + st::proxyRowSkip;
const auto statusFg = [&] {
switch (_view.state) {
case State::Online:
return st::proxyRowStatusFgOnline;
case State::Unavailable:
return st::proxyRowStatusFgOffline;
case State::WaitingForBrowser:
return st::proxyRowStatusFg;
case State::Available:
return st::proxyRowStatusFgAvailable;
case State::Checking:
return ProxyCheckStatusColor(_view.progressStatus);
default:
return st::proxyRowStatusFg;
}
}();
const auto status = [&] {
if (!_view.statusText.isEmpty()) {
return _view.statusText;
}
switch (_view.state) {
case State::Unknown:
return tr::lng_proxy_box_check_status(tr::now);
case State::Available:
return tr::lng_proxy_available(
tr::now,
lt_ping,
QString::number(_view.ping));
case State::Checking:
return ProxyCheckStatusText(_view.progressStatus);
case State::Connecting:
return tr::lng_proxy_connecting(tr::now);
case State::Online:
return _view.ping
? tr::lng_proxy_online_ping(
tr::now,
lt_ping,
QString::number(_view.ping))
: tr::lng_proxy_online(tr::now);
case State::Unavailable:
return tr::lng_proxy_unavailable(tr::now);
case State::WaitingForBrowser:
return tr::lng_proxy_web_waiting(tr::now);
}
Unexpected("State in ProxyRow::paintEvent.");
}();
p.setPen(_view.deleted ? st::proxyRowStatusFg : statusFg);
p.setFont(st::normalFont);
auto statusLeft = left;
if (_checking) {
_checking->draw(
p,
{
st::proxyCheckingPosition.x() + statusLeft,
st::proxyCheckingPosition.y() + top
},
width());
statusLeft += st::proxyCheckingPosition.x()
+ st::proxyCheckingAnimation.size.width()
+ st::proxyCheckingSkip;
}
p.drawTextLeft(statusLeft, top, width(), status);
top += st::normalFont->height + st::proxyRowPadding.bottom();
}
void ProxyRow::paintCheck(Painter &p) {
const auto selecting = _selectingAnimation.value(_selecting ? 1. : 0.);
const auto opacity = p.opacity();
if (selecting < 1.) {
p.setOpacity(opacity * (1. - selecting));
paintRadio(p);
}
if (selecting > 0.) {
p.setOpacity(opacity * selecting);
paintChosen(p);
}
p.setOpacity(opacity);
}
void ProxyRow::paintChosen(Painter &p) {
const auto &radio = st::defaultRadio;
const auto size = st::proxyRowCheck.size;
const auto left = st::proxyRowPadding.left()
+ (radio.diameter - size) / 2;
const auto top = (height() - radio.diameter - radio.thickness) / 2
+ (radio.diameter - size) / 2;
const auto half = radio.thickness / 2.;
PainterHighQualityEnabler hq(p);
auto pen = QPen(radio.untoggledFg);
pen.setWidth(radio.thickness);
p.setPen(pen);
p.setBrush(Qt::NoBrush);
p.drawEllipse(style::rtlrect(
QRectF(Rect(left, top, Size(size))) - Margins(half),
width()));
_check.paint(p, left, top, width());
}
void ProxyRow::paintMenuToggle(Painter &p) {
if (!_menuToggle->isHidden()) {
return;
}
const auto selecting = _selectingAnimation.value(_selecting ? 1. : 0.);
if (selecting >= 1.) {
return;
}
const auto &st = st::topBarMenuToggle;
const auto opacity = p.opacity();
p.setOpacity(opacity * (1. - selecting));
st.icon.paint(
p,
myrtlrect(_menuToggle->geometry()).topLeft() + st.iconPosition,
width());
p.setOpacity(opacity);
}
void ProxyRow::paintRadio(Painter &p) {
const auto loading = _progress
? _progress->computeState()
: Ui::RadialState{ 0., 0, arc::kFullLength };
const auto toggled = _toggled.value(_view.selected ? 1. : 0.)
* (1. - loading.shown);
const auto _st = &st::defaultRadio;
const auto set = _setAnimation.value(_set ? 1. : 0.);
PainterHighQualityEnabler hq(p);
const auto left = st::proxyRowPadding.left();
const auto top = (height() - _st->diameter - _st->thickness) / 2;
const auto outerWidth = width();
auto pen = anim::pen(_st->untoggledFg, _st->toggledFg, toggled * set);
pen.setWidth(_st->thickness);
pen.setCapStyle(Qt::RoundCap);
p.setPen(pen);
p.setBrush(_st->bg);
const auto rect = style::rtlrect(QRectF(left, top, _st->diameter, _st->diameter).marginsRemoved(QMarginsF(_st->thickness / 2., _st->thickness / 2., _st->thickness / 2., _st->thickness / 2.)), outerWidth);
if (_progress && loading.shown > 0 && anim::Disabled()) {
anim::DrawStaticLoading(
p,
rect,
_st->thickness,
pen.color(),
_st->bg);
} else if (loading.arcLength < arc::kFullLength) {
p.drawArc(rect, loading.arcFrom, loading.arcLength);
} else {
p.drawEllipse(rect);
}
if (toggled > 0 && (!_progress || !anim::Disabled())) {
p.setPen(Qt::NoPen);
p.setBrush(anim::brush(_st->untoggledFg, _st->toggledFg, toggled * set));
auto skip0 = _st->diameter / 2., skip1 = _st->skip / 10., checkSkip = skip0 * (1. - toggled) + skip1 * toggled;
p.drawEllipse(style::rtlrect(QRectF(left, top, _st->diameter, _st->diameter).marginsRemoved(QMarginsF(checkSkip, checkSkip, checkSkip, checkSkip)), outerWidth));
}
}
void ProxyRow::showMenu() {
if (_menu) {
return;
}
_menu = base::make_unique_q<Ui::DropdownMenu>(
window(),
st::dropdownMenuWithIcons);
const auto weak = _menu.get();
_menu->setHiddenCallback([=] {
weak->deleteLater();
if (_menu == weak) {
_menuToggle->setForceRippled(false);
}
});
_menu->setShowStartCallback([=] {
if (_menu == weak) {
_menuToggle->setForceRippled(true);
}
});
_menu->setHideStartCallback([=] {
if (_menu == weak) {
_menuToggle->setForceRippled(false);
}
});
_menuToggle->installEventFilter(_menu);
fillMenu([&](
const QString &text,
Fn<void()> callback,
const style::icon *icon) {
_menu->addAction(text, std::move(callback), icon);
});
const auto parentTopLeft = window()->mapToGlobal(QPoint());
const auto buttonTopLeft = _menuToggle->mapToGlobal(QPoint());
const auto parent = QRect(parentTopLeft, window()->size());
const auto button = QRect(buttonTopLeft, _menuToggle->size());
const auto bottom = button.y()
+ st::proxyDropdownDownPosition.y()
+ _menu->height()
- parent.y();
const auto top = button.y()
+ st::proxyDropdownUpPosition.y()
- _menu->height()
- parent.y();
if (bottom > parent.height() && top >= 0) {
const auto left = button.x()
+ button.width()
+ st::proxyDropdownUpPosition.x()
- _menu->width()
- parent.x();
_menu->move(left, top);
_menu->showAnimated(Ui::PanelAnimation::Origin::BottomRight);
} else {
const auto left = button.x()
+ button.width()
+ st::proxyDropdownDownPosition.x()
- _menu->width()
- parent.x();
_menu->move(left, bottom - _menu->height());
_menu->showAnimated(Ui::PanelAnimation::Origin::TopRight);
}
}
void ProxyRow::fillMenu(const AddAction &addAction) {
if (!_view.deleted) {
addAction(tr::lng_proxy_box_check_status(tr::now), [=] {
_checkClicks.fire({});
}, &st::menuIconSearch);
}
addAction(tr::lng_proxy_menu_edit(tr::now), [=] {
_editClicks.fire({});
}, &st::menuIconEdit);
if (!_view.deleted && !_check.checked()) {
addAction(tr::lng_context_select_msg(tr::now), [=] {
_chooseClicks.fire({});
}, &st::menuIconSelect);
}
if (_view.canOpenBrowser) {
addAction(tr::lng_proxy_web_open(tr::now), [=] {
_openBrowserClicks.fire({});
}, &st::menuIconLink);
}
if (_view.supportsShare) {
addAction(tr::lng_proxy_edit_share(tr::now), [=] {
_shareClicks.fire({});
}, &st::menuIconShare);
addAction(tr::lng_group_invite_context_qr(tr::now), [=] {
_showQrClicks.fire({});
}, &st::menuIconQrCode);
}
if (_view.deleted) {
addAction(tr::lng_proxy_menu_restore(tr::now), [=] {
_restoreClicks.fire({});
}, &st::menuIconRestore);
} else {
addAction(tr::lng_proxy_menu_delete(tr::now), [=] {
_deleteClicks.fire({});
}, &st::menuIconDelete);
}
}
void ProxyRow::contextMenuEvent(QContextMenuEvent *e) {
e->accept();
if (_menu || _selecting) {
return;
}
_contextMenu = base::make_unique_q<Ui::PopupMenu>(
this,
st::popupMenuWithIcons);
fillMenu([&](
const QString &text,
Fn<void()> callback,
const style::icon *icon) {
_contextMenu->addAction(text, std::move(callback), icon);
});
_contextMenu->popup(e->globalPos());
}
ProxiesBox::ProxiesBox(
QWidget*,
not_null<ProxiesBoxController*> controller,
Core::SettingsProxy &settings,
const QString &highlightId)
: _controller(controller)
, _settings(settings)
, _initialWrap(this)
, _highlightId(highlightId) {
_controller->views(
) | rpl::on_next([=](View &&view) {
applyView(std::move(view));
}, lifetime());
}
void ProxiesBox::keyPressEvent(QKeyEvent *e) {
if (e->key() == Qt::Key_Escape && _selecting) {
clearChosen();
} else if (e->key() == Qt::Key_Copy
|| (e->key() == Qt::Key_C && e->modifiers() == Qt::ControlModifier)) {
if (_selecting) {
shareChosen();
} else {
_controller->shareItems();
}
} else if (e->key() == Qt::Key_Paste
|| (e->key() == Qt::Key_V && e->modifiers() == Qt::ControlModifier)) {
AddProxyFromClipboard(_controller, uiShow());
} else {
BoxContent::keyPressEvent(e);
}
}
void ProxiesBox::prepare() {
setTitle(tr::lng_proxy_settings());
refreshButtons();
setupContent();
}
void ProxiesBox::showFinished() {
if (_highlightId == u"proxy/add-proxy"_q) {
if (_addProxyButton) {
_highlightId = QString();
Settings::HighlightWidget(
_addProxyButton,
{ .rippleShape = true });
}
} else if (_highlightId == u"proxy/share-list"_q) {
if (_shareListButton) {
_highlightId = QString();
Settings::HighlightWidget(_shareListButton);
}
}
}
void ProxiesBox::setupTopButton() {
const auto top = addTopButton(st::infoTopBarMenu);
const auto state = top->lifetime().make_state<TopButtonMenuState>();
top->setClickedCallback([=] {
state->menu = base::make_unique_q<Ui::PopupMenu>(
top,
st::popupMenuWithIcons);
const auto raw = state->menu.get();
const auto addAction = Ui::Menu::CreateAddActionCallback(raw);
addAction({
.text = tr::lng_proxy_add_from_clipboard(tr::now),
.handler = [=] { AddProxyFromClipboard(_controller, uiShow()); },
.icon = &st::menuIconImportTheme,
});
if (!_rows.empty()) {
addAction({
.text = tr::lng_group_invite_context_delete_all(tr::now),
.handler = [=] { _controller->deleteItems(); },
.icon = &st::menuIconDeleteAttention,
.isAttention = true,
});
}
raw->setForcedOrigin(Ui::PanelAnimation::Origin::TopRight);
top->setForceRippled(true);
raw->setDestroyedCallback([=] {
if (!state->closing) {
top->setForceRippled(false);
}
});
raw->popup(
top->mapToGlobal(
QPoint(top->width(), top->height() - st::lineWidth * 3)));
return true;
});
}
void ProxiesBox::setupContent() {
const auto inner = setInnerWidget(object_ptr<Ui::VerticalLayout>(this));
_inner = inner;
scrolls() | rpl::on_next([=] {
if (_press && _press->held) {
updateDragSelection(QCursor::pos());
}
}, inner->lifetime());
const auto columns = inner->add(
object_ptr<ProxySettingsColumns>(inner),
style::al_justify);
const auto left = columns->left();
const auto right = columns->right();
_tryIPv6 = right->add(
object_ptr<Ui::Checkbox>(
right,
tr::lng_connection_try_ipv6(tr::now),
_settings.tryIPv6()),
st::proxySettingsRightCheckPadding);
_tryIPv6->setAllowTextLines(2);
_fastWarmup = right->add(
object_ptr<Ui::Checkbox>(
right,
tr::lng_connection_fast_warmup(tr::now),
_settings.fastWarmup()),
st::proxySettingsRightCheckPadding);
_fastWarmup->setAllowTextLines(2);
_proxySettings
= std::make_shared<Ui::RadioenumGroup<ProxyData::Settings>>(
_settings.settings());
left->add(
object_ptr<Ui::Radioenum<ProxyData::Settings>>(
left,
_proxySettings,
ProxyData::Settings::Disabled,
tr::lng_proxy_disable(tr::now)),
st::proxyUsePadding);
left->add(
object_ptr<Ui::Radioenum<ProxyData::Settings>>(
left,
_proxySettings,
ProxyData::Settings::System,
tr::lng_proxy_use_system_settings(tr::now)),
st::proxyUsePadding);
left->add(
object_ptr<Ui::Radioenum<ProxyData::Settings>>(
left,
_proxySettings,
ProxyData::Settings::Enabled,
tr::lng_proxy_use_custom(tr::now)),
st::proxyUsePadding);
const auto addStealthToggle = [&](
const QString &label,
bool checked,
Fn<void(bool)> save) {
const auto toggle = right->add(
object_ptr<Ui::Checkbox>(right, label, checked),
st::proxySettingsRightCheckPadding);
toggle->setAllowTextLines(2);
toggle->checkedChanges(
) | rpl::on_next([=](bool value) {
save(value);
}, toggle->lifetime());
return toggle;
};
{
const auto saved = Core::App().settings().proxyStealthOptions();
const auto addStealthHeader = [&](const QString &text) {
right->add(
object_ptr<Ui::FlatLabel>(
right,
text,
st::boxDividerLabel),
st::proxySettingsRightAboutPadding);
};
const auto raiseLevel = [](
MTP::ProxyStealthOptions &options,
MTP::ProxyStealthLevel level) {
if (int(options.level) < int(level)) {
options.level = level;
}
};
addStealthHeader(u"Cloudflare WARP"_q);
const auto warpStatus = right->add(
object_ptr<Ui::FlatLabel>(
right,
Zsg::Warp::StatusText(),
st::boxDividerLabel),
st::proxySettingsRightAboutPadding);
addStealthToggle(
u"Use WARP as the entry (experimental)"_q,
Zsg::Warp::Enabled(),
[=](bool on) {
Zsg::Warp::SetEnabled(on);
warpStatus->setText(Zsg::Warp::StatusText());
});
const auto warpScan = right->add(
object_ptr<Ui::FlatLabel>(
right,
Zsg::Warp::ScanText(),
st::boxDividerLabel),
st::proxySettingsRightAboutPadding);
const auto warpScanButton = right->add(
object_ptr<Ui::LinkButton>(right, u"Scan WARP endpoints"_q),
st::proxySettingsRightAboutPadding);
warpScanButton->setClickedCallback([=] {
if (!Zsg::Warp::ScanNow()) {
warpScan->setText(u"Turn WARP on first (or the tunnel is already up)."_q);
} else {
warpScan->setText(Zsg::Warp::ScanText());
}
});
{
// The status follows the tunnel: a timer owned by the label.
const auto timer = new QTimer(warpStatus);
timer->setInterval(1000);
QObject::connect(timer, &QTimer::timeout, warpStatus, [=] {
warpStatus->setText(Zsg::Warp::StatusText());
warpScan->setText(Zsg::Warp::ScanText());
});
timer->start();
}
addStealthHeader(u"Check connection"_q);
{
// The "Check connection" diagnostic (zsg_pathtest): the client's own code against every proxy and the
// WSS route, 12 times each, one log to hand to an AI.
const auto pathTest = right->add(
object_ptr<Ui::FlatLabel>(
right,
u"Connects to the proxy in use (or, with no proxy, to the WSS route) 12 times with the client's own code and saves one log to hand to an AI. Host names are masked unless you choose real names; secrets are never recorded."_q,
st::boxDividerLabel),
st::proxySettingsRightAboutPadding);
const auto start = [=](bool realNames, bool allServers) {
if (Zsg::PathTest::Running()) {
pathTest->setText(u"The check is already running."_q);
return;
}
pathTest->setText(u"Checking... 0%"_q);
Zsg::PathTest::Start(
{ .realNames = realNames, .allServers = allServers },
crl::guard(pathTest, [=](int percent) {
pathTest->setText(
u"Checking... "_q + QString::number(percent) + u"%"_q);
}),
crl::guard(pathTest, [=](QString path) {
pathTest->setText(path.isEmpty()
? u"The check failed."_q
: u"Done. Log: "_q + QDir::toNativeSeparators(path));
}));
};
const auto startButton = right->add(
object_ptr<Ui::LinkButton>(right, u"Check connection"_q),
st::proxySettingsRightAboutPadding);
startButton->setClickedCallback([=] { start(false, false); });
const auto namesButton = right->add(
object_ptr<Ui::LinkButton>(right, u"Check connection, real host names in the log"_q),
st::proxySettingsRightAboutPadding);
namesButton->setClickedCallback([=] { start(true, false); });
// Every server of the list, one at a time with a random 10-20 s pause, so the provider never sees
// the whole list at once.
const auto allButton = right->add(
object_ptr<Ui::LinkButton>(right, u"Check all proxies (one at a time, takes minutes)"_q),
st::proxySettingsRightAboutPadding);
allButton->setClickedCallback([=] { start(false, true); });
const auto cancelButton = right->add(
object_ptr<Ui::LinkButton>(right, u"Stop the check"_q),
st::proxySettingsRightAboutPadding);
cancelButton->setClickedCallback([] { Zsg::PathTest::Cancel(); });
const auto folderButton = right->add(
object_ptr<Ui::LinkButton>(right, u"Open the logs folder"_q),
st::proxySettingsRightAboutPadding);
folderButton->setClickedCallback([] {
QDesktopServices::openUrl(
QUrl::fromLocalFile(Zsg::PathTest::LogsFolder()));
});
}
addStealthHeader(u"Transport compatibility"_q);
_routeViaWss = addStealthToggle(
u"Route via WSS (web, DC2/DC4 only)"_q,
(saved.transport == MTP::ProxyTransport::Wss),
[this](bool on) {
auto o = Core::App().settings().proxyStealthOptions();
o.transport = on
? MTP::ProxyTransport::Wss
: MTP::ProxyTransport::Tcp;
Core::App().applyProxyStealthOptions(o);
refreshRouteViaWss();
});
addStealthHeader(u"Handshake compatibility"_q);
addStealthToggle(
u"Spread connection attempts (soft)"_q,
(saved.connectionPattern != MTP::ProxyConnectionPattern::Off),
[=](bool on) {
auto o = Core::App().settings().proxyStealthOptions();
o.connectionPattern = on
? MTP::ProxyConnectionPattern::Soft
: MTP::ProxyConnectionPattern::Off;
if (on) {
raiseLevel(o, MTP::ProxyStealthLevel::DpiAdaptiveHandshake);
}
Core::App().applyProxyStealthOptions(o);
});
addStealthHeader(u"Data-phase shaping"_q);
addStealthToggle(
u"Mask MTProxy start (anti-DPI)"_q,
(saved.startupCover != MTP::ProxyStartupCover::Off),
[=](bool on) {
auto o = Core::App().settings().proxyStealthOptions();
o.startupCover = on
? MTP::ProxyStartupCover::Soft
: MTP::ProxyStartupCover::Off;
if (on) {
raiseLevel(o, MTP::ProxyStealthLevel::DpiAdaptiveData);
}
Core::App().applyProxyStealthOptions(o);
});
addStealthToggle(
u"Vary TLS record sizes (conservative)"_q,
(saved.recordSizing != MTP::ProxyRecordSizing::Off),
[=](bool on) {
auto o = Core::App().settings().proxyStealthOptions();
o.recordSizing = on
? MTP::ProxyRecordSizing::Conservative
: MTP::ProxyRecordSizing::Off;
if (on) {
raiseLevel(o, MTP::ProxyStealthLevel::DpiAdaptiveData);
}
Core::App().applyProxyStealthOptions(o);
});
addStealthToggle(
u"Pace MTProxy traffic (gentle)"_q,
(saved.timing != MTP::ProxyTiming::Off),
[=](bool on) {
auto o = Core::App().settings().proxyStealthOptions();
o.timing = on
? MTP::ProxyTiming::Gentle
: MTP::ProxyTiming::Off;
if (on) {
raiseLevel(o, MTP::ProxyStealthLevel::DpiAdaptiveData);
}
Core::App().applyProxyStealthOptions(o);
});
addStealthHeader(u"Experimental MTProxy handshake"_q);
addStealthToggle(
u"Fragment ClientHello (experimental)"_q,
(saved.clientHelloFragmentation
!= MTP::ProxyClientHelloFragmentation::Off),
[=](bool on) {
auto o = Core::App().settings().proxyStealthOptions();
o.clientHelloFragmentation = on
? MTP::ProxyClientHelloFragmentation::Soft
: MTP::ProxyClientHelloFragmentation::Off;
if (on) {
raiseLevel(o, MTP::ProxyStealthLevel::Experimental);
}
Core::App().applyProxyStealthOptions(o);
});
addStealthToggle(
u"Synthetic PSK tickets (experimental)"_q,
saved.syntheticPsk,
[=](bool on) {
auto o = Core::App().settings().proxyStealthOptions();
o.syntheticPsk = on;
if (on) {
raiseLevel(o, MTP::ProxyStealthLevel::Experimental);
}
Core::App().applyProxyStealthOptions(o);
});
}
right->add(
object_ptr<Ui::FlatLabel>(
right,
u"TLS ClientHello profile"_q,
st::boxDividerLabel),
st::proxySettingsRightAboutPadding);
{
using Profile = MTP::ProxyTlsProfile;
const auto tlsGroup = std::make_shared<Ui::RadioenumGroup<Profile>>(
Core::App().settings().proxyStealthOptions().tlsProfile);
const auto addTls = [&](Profile value, const QString &label) {
const auto radio = right->add(
object_ptr<Ui::Radioenum<Profile>>(
right,
tlsGroup,
value,
label),
st::proxySettingsRightUsePadding);
radio->setAllowTextLines(2);
};
addTls(Profile::Auto, u"Auto (Chrome)"_q);
addTls(Profile::AutoRotate, u"Auto-rotate"_q);
addTls(Profile::ChromeModern, u"Chrome Modern"_q);
addTls(Profile::AndroidChrome, u"Android Chrome"_q);
addTls(Profile::Firefox, u"Firefox"_q);
addTls(Profile::FirefoxAndroid, u"Firefox Android"_q);
addTls(Profile::Yandex, u"Yandex"_q);
addTls(Profile::AndroidOkHttp, u"Android OkHttp"_q);
tlsGroup->setChangedCallback([=](Profile value) {
auto o = Core::App().settings().proxyStealthOptions();
o.tlsProfile = value;
Core::App().applyProxyStealthOptions(o);
});
}
{
const auto saved = Core::App().settings().proxyStealthOptions();
right->add(
object_ptr<Ui::FlatLabel>(
right,
u"Custom WSS relay (expert, any DC)"_q,
st::boxDividerLabel),
st::proxySettingsRightAboutPadding);
right->add(
object_ptr<Ui::FlatLabel>(
right,
u"No certificate check is done — use only a relay you trust."_q,
st::boxDividerLabel),
st::proxySettingsRightAboutPadding);
const auto addWssField = [&](
const QString &placeholder,
const QString &initial,
Fn<void(MTP::ProxyStealthOptions&, const QString&)> apply) {
const auto field = right->add(
object_ptr<Ui::InputField>(
right,
st::connectionHostInputField,
rpl::single(placeholder),
initial),
st::proxyEditInputPadding);
field->changes(
) | rpl::on_next([=] {
const auto value = field->getLastText().trimmed();
auto o = Core::App().settings().proxyStealthOptions();
apply(o, value);
Core::App().applyProxyStealthOptions(o);
}, field->lifetime());
};
addWssField(
u"WSS relay host (empty = official DC2/DC4)"_q,
saved.wssCustomHost,
[](MTP::ProxyStealthOptions &o, const QString &v) {
o.wssCustomHost = v;
});
addWssField(
u"WSS relay port"_q,
saved.wssCustomPort ? QString::number(saved.wssCustomPort) : QString(),
[](MTP::ProxyStealthOptions &o, const QString &v) {
const auto port = v.toInt();
o.wssCustomPort = (port > 0 && port <= 65535) ? port : 443;
});
addWssField(
u"WSS path (default /apiws)"_q,
saved.wssCustomPath,
[](MTP::ProxyStealthOptions &o, const QString &v) {
o.wssCustomPath = v;
});
addWssField(
u"WSS SNI domain (default = host)"_q,
saved.wssCustomDomain,
[](MTP::ProxyStealthOptions &o, const QString &v) {
o.wssCustomDomain = v;
});
}
_about = left->add(
object_ptr<Ui::DividerLabel>(
left,
object_ptr<Ui::FlatLabel>(
left,
tr::lng_proxy_about(tr::now),
st::boxDividerLabel),
st::proxyAboutPadding),
style::margins(0, 0, 0, st::proxyRowPadding.top()));
_wrap = left->add(std::move(_initialWrap));
left->add(object_ptr<Ui::FixedHeightWidget>(
left,
st::proxyRowPadding.bottom()));
_reorder = std::make_unique<Ui::VerticalLayoutReorder>(_wrap);
_reorder->updates(
) | rpl::on_next([=](Ui::VerticalLayoutReorder::Single data) {
using State = Ui::VerticalLayoutReorder::State;
if (data.state == State::Started) {
++_reordering;
} else {
Ui::PostponeCall(_wrap.data(), [=] {
--_reordering;
});
if (data.state == State::Applied) {
_controller->reorderItems(
data.oldPosition,
data.newPosition);
}
}
}, _wrap->lifetime());
_reorder->start();
_proxySettings->setChangedCallback([=](ProxyData::Settings value) {
if (!_controller->setProxySettings(value)) {
_proxySettings->setValue(_settings.settings());
addNewProxy();
}
refreshRouteViaWss();
});
_tryIPv6->checkedChanges(
) | rpl::on_next([=](bool checked) {
_controller->setTryIPv6(checked);
}, _tryIPv6->lifetime());
_fastWarmup->checkedChanges(
) | rpl::on_next([=](bool checked) {
_controller->setFastWarmup(checked);
}, _fastWarmup->lifetime());
_controller->proxySettingsValue(
) | rpl::on_next([=](ProxyData::Settings value) {
_proxySettings->setValue(value);
refreshRouteViaWss();
}, inner->lifetime());
_settings.connectionTypeChanges(
) | rpl::on_next([=] {
refreshRouteViaWss();
}, inner->lifetime());
if (_rows.empty()) {
createNoRowsLabel();
}
refreshRouteViaWss();
{
const auto wrap = left->add(
object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
left,
object_ptr<Ui::VerticalLayout>(left)));
const auto shareList = Settings::AddButtonWithIcon(
wrap->entity(),
tr::lng_proxy_edit_share_list_button(),
st::settingsButton,
{ &st::menuIconCopy });
_shareListButton = shareList;
shareList->setClickedCallback([=] {
_controller->shareItems();
});
wrap->toggleOn(_controller->listShareableChanges());
wrap->finishAnimating();
}
inner->resizeToWidth(st::proxySettingsBoxWidth);
inner->heightValue(
) | rpl::map([=](int height) {
return std::min(
std::max(
height,
_wrap->y() + 3 * rowHeight()),
st::proxySettingsBoxMaxHeight);
}) | rpl::distinct_until_changed(
) | rpl::on_next([=](int height) {
setDimensions(st::proxySettingsBoxWidth, height);
}, inner->lifetime());
}
void ProxiesBox::refreshRouteViaWss() {
if (!_routeViaWss) {
return;
}
const auto proxy = _settings.selected();
const auto settings = _settings.settings();
const auto checked = (MTP::EffectiveProxyTransport(
proxy,
settings,
Core::App().settings().proxyStealthOptions().transport)
== MTP::ProxyTransport::Wss);
_routeViaWss->setDisabled(!MTP::ProxyWssAllowed(proxy, settings));
_routeViaWss->setChecked(
checked,
Ui::Checkbox::NotifyAboutChange::DontNotify);
}
int ProxiesBox::rowHeight() const {
return st::proxyRowPadding.top()
+ st::semiboldFont->height
+ st::proxyRowSkip
+ st::normalFont->height
+ st::proxyRowPadding.bottom();
}
void ProxiesBox::addNewProxy() {
getDelegate()->show(_controller->addNewItemBox());
}
void ProxiesBox::beginInitialRows() {
_initializingRows = true;
}
void ProxiesBox::finishInitialRows() {
_initializingRows = false;
const auto wrap = _wrap
? _wrap.data()
: _initialWrap.data();
if (!_rows.empty()) {
wrap->resizeToWidth(st::proxySettingsListColumnWidth);
}
}
void ProxiesBox::applyView(View &&view) {
const auto id = view.id;
const auto i = _rows.find(id);
if (view.deleted || view.host.isEmpty()) {
if (_anchorId == id) {
_anchorId = 0;
}
if (_press) {
_press->initial.remove(id);
if (_press->id == id && view.host.isEmpty()) {
cancelPress();
}
}
if (_chosen.remove(id)) {
refreshSelection();
}
}
if (i == _rows.end()) {
const auto wrap = _wrap
? _wrap.data()
: _initialWrap.data();
const auto rowEntry = _rows.emplace(id, nullptr).first;
auto row = object_ptr<ProxyRow>(
wrap,
std::move(view));
rowEntry->second.reset(_initializingRows
? wrap->add(std::move(row))
: wrap->insert(0, std::move(row)));
setupButtons(id, rowEntry->second.get());
rowEntry->second->setChosen(
_selecting,
false,
anim::type::instant);
if (_noRows) {
_noRows.reset();
}
if (!_initializingRows) {
wrap->resizeToWidth(st::proxySettingsListColumnWidth);
refreshReorder();
}
} else if (view.host.isEmpty()) {
_rows.erase(i);
refreshReorder();
} else {
i->second->updateFields(std::move(view));
}
}
void ProxiesBox::refreshReorder() {
if (!_reorder) {
return;
}
_reorder->cancel();
Ui::PostponeCall(this, [=] {
if (_reorder) {
_reorder->cancel();
_reorder->start();
}
});
}
void ProxiesBox::createNoRowsLabel() {
_noRows.reset(_wrap->add(
object_ptr<Ui::FixedHeightWidget>(
_wrap,
rowHeight()),
st::proxyEmptyListPadding));
_noRows->resize(
(st::proxySettingsListColumnWidth
- st::proxyEmptyListPadding.left()
- st::proxyEmptyListPadding.right()),
_noRows->height());
const auto label = Ui::CreateChild<Ui::FlatLabel>(
_noRows.get(),
tr::lng_proxy_description(tr::now),
st::proxyEmptyListLabel);
_noRows->widthValue(
) | rpl::on_next([=](int width) {
label->resizeToWidth(width);
label->moveToLeft(0, 0);
}, label->lifetime());
}
void ProxiesBox::setupButtons(int id, not_null<ProxyRow*> button) {
button->deleteClicks(
) | rpl::on_next([=] {
_controller->deleteItem(id);
}, button->lifetime());
button->restoreClicks(
) | rpl::on_next([=] {
_controller->restoreItem(id);
}, button->lifetime());
button->checkClicks(
) | rpl::on_next([=] {
_controller->checkItem(id);
}, button->lifetime());
button->editClicks(
) | rpl::on_next([=] {
getDelegate()->show(_controller->editItemBox(id));
}, button->lifetime());
rpl::merge(
button->shareClicks() | rpl::map_to(false),
button->showQrClicks() | rpl::map_to(true)
) | rpl::on_next([=](bool qr) {
_controller->shareItem(id, qr);
}, button->lifetime());
button->openBrowserClicks(
) | rpl::on_next([=] {
_controller->openBrowser(id);
}, button->lifetime());
button->chooseClicks(
) | rpl::on_next([=] {
toggleChosen(id);
}, button->lifetime());
button->events(
) | rpl::on_next([=](not_null<QEvent*> e) {
handleRowEvent(id, e);
}, button->lifetime());
button->clicks(
) | rpl::on_next([=] {
if (!_reordering) {
rowClicked(id);
}
}, button->lifetime());
Ui::SetupSelectingScroll(button, [=](int pixels) {
scrollToY(scrollTop() + pixels);
}, [=](QPoint globalPosition) {
return dragScrollDelta(globalPosition);
});
}
void ProxiesBox::handleRowEvent(int id, not_null<QEvent*> e) {
const auto type = e->type();
if (type != QEvent::MouseButtonPress
&& type != QEvent::MouseMove
&& type != QEvent::MouseButtonRelease) {
return;
}
const auto mouse = static_cast<QMouseEvent*>(e.get());
if (type == QEvent::MouseButtonPress) {
if (mouse->button() == Qt::LeftButton) {
_press = Press{
.id = id,
.selection = _selecting
|| base::IsCtrlPressed()
|| base::IsShiftPressed(),
.chosen = !_chosen.contains(id),
.initial = _chosen,
};
if (_press->selection && _reorder) {
_reorder->cancel();
}
}
} else if (type == QEvent::MouseMove) {
if (!(mouse->buttons() & Qt::LeftButton)) {
finishPress();
} else {
updateDragSelection(mouse->globalPosition().toPoint());
}
} else if (mouse->button() == Qt::LeftButton) {
finishPress();
}
}
void ProxiesBox::rowClicked(int id) {
const auto press = base::take(_press);
const auto own = press && (press->id == id);
if (own && press->dragged) {
return;
}
const auto shift = base::IsShiftPressed();
const auto selection = own
? press->selection
: (_selecting || base::IsCtrlPressed() || shift);
if (!selection) {
_controller->applyItem(id);
} else if (shift && _anchorId && _anchorId != id) {
chooseRange(_anchorId, id, true);
refreshSelection();
} else {
toggleChosen(id);
}
}
void ProxiesBox::updateDragSelection(QPoint globalPosition) {
if (!_press || !_press->held || !_press->selection) {
return;
}
const auto id = rowIdAt(globalPosition);
if (!id || (!_press->dragged && id == _press->id)) {
return;
}
_press->dragged = true;
_anchorId = _press->id;
_chosen = _press->initial;
chooseRange(_press->id, id, _press->chosen);
refreshSelection();
}
void ProxiesBox::finishPress() {
if (_press && _press->held) {
_press->held = false;
if (_press->dragged) {
refreshSelection();
}
}
}
void ProxiesBox::cancelPress() {
if (_press) {
_press->held = false;
_press->dragged = true;
}
}
int ProxiesBox::rowIdAt(QPoint globalPosition) const {
if (!_wrap) {
return 0;
}
const auto y = _wrap->mapFromGlobal(globalPosition).y();
auto result = 0;
auto distance = std::numeric_limits<int>::max();
for (const auto &[id, row] : _rows) {
const auto top = row->y();
const auto bottom = top + row->height();
const auto rowDistance = (y < top)
? (top - y)
: (y >= bottom)
? (y - bottom + 1)
: 0;
if (rowDistance < distance) {
distance = rowDistance;
result = id;
}
}
return result;
}
int ProxiesBox::dragScrollDelta(QPoint globalPosition) const {
if (!_press || !_press->held || !_press->selection || !_inner) {
return 0;
}
return Ui::SelectingScrollDelta(
_inner->visibleRegion().boundingRect(),
_inner->mapFromGlobal(globalPosition).y());
}
void ProxiesBox::chooseRange(int fromId, int tillId, bool chosen) {
const auto from = _rows.find(fromId);
const auto till = _rows.find(tillId);
if (from == end(_rows) || till == end(_rows)) {
return;
}
const auto top = std::min(from->second->y(), till->second->y());
const auto bottom = std::max(from->second->y(), till->second->y());
for (const auto &[id, row] : _rows) {
if (row->y() < top || row->y() > bottom) {
continue;
} else if (!chosen) {
_chosen.remove(id);
} else if (!row->deleted()) {
_chosen.emplace(id);
}
}
}
void ProxiesBox::refreshButtons() {
clearButtons();
setupTopButton();
if (_selecting) {
addLeftButton(
tr::lng_selected_delete(),
[=] { deleteChosen(); },
st::attentionBoxButton);
addButton(tr::lng_proxy_edit_share(), [=] { shareChosen(); });
addButton(tr::lng_selected_clear(), [=] { clearChosen(); });
} else {
_addProxyButton = addButton(
tr::lng_proxy_add(),
[=] { addNewProxy(); });
addButton(tr::lng_close(), [=] { closeBox(); });
}
}
void ProxiesBox::refreshSelection() {
const auto selecting = !_chosen.empty()
|| (_press && _press->held && _press->dragged);
if (!selecting) {
_anchorId = 0;
}
for (const auto &[id, row] : _rows) {
row->setChosen(selecting, _chosen.contains(id), anim::type::normal);
}
if (selecting) {
setTitle(tr::lng_proxy_selected(
tr::now,
lt_count,
int(_chosen.size())));
} else {
setTitle(tr::lng_proxy_settings());
}
if (_selecting != selecting) {
_selecting = selecting;
if (_selecting) {
_reorder->cancel();
} else {
refreshReorder();
}
refreshButtons();
}
}
void ProxiesBox::toggleChosen(int id) {
const auto i = _rows.find(id);
if (i == _rows.end() || i->second->deleted()) {
return;
} else if (!_chosen.remove(id)) {
_chosen.emplace(id);
}
_anchorId = id;
refreshSelection();
}
void ProxiesBox::clearChosen() {
cancelPress();
_chosen.clear();
refreshSelection();
}
void ProxiesBox::deleteChosen() {
cancelPress();
_controller->deleteItems(base::take(_chosen));
refreshSelection();
}
void ProxiesBox::shareChosen() {
cancelPress();
_controller->shareItems(base::take(_chosen));
refreshSelection();
}
ProxyBox::ProxyBox(
QWidget*,
const ProxyData &data,
Fn<void(ProxyData)> callback,
Fn<void(ProxyData)> shareCallback)
: _allowShare(data.type != Type::None)
, _callback(std::move(callback))
, _shareCallback(std::move(shareCallback))
, _content(this) {
setupControls(data);
}
void ProxyBox::prepare() {
setTitle(tr::lng_proxy_edit());
connect(_host.data(), &HostInput::changed, [=] {
Ui::PostponeCall(_host, [=] {
const auto host = _host->getLastText().trimmed();
static const auto mask = QRegularExpression(
u"^\\d+\\.\\d+\\.\\d+\\.\\d+:(\\d*)$"_q);
const auto match = mask.match(host);
if (_host->cursorPosition() == host.size()
&& match.hasMatch()) {
const auto port = match.captured(1);
_port->setText(port);
_port->setCursorPosition(port.size());
_port->setFocus();
_host->setText(host.mid(0, host.size() - port.size() - 1));
}
});
});
_port.data()->events(
) | rpl::on_next([=](not_null<QEvent*> e) {
if (e->type() == QEvent::KeyPress
&& (static_cast<QKeyEvent*>(e.get())->key() == Qt::Key_Backspace)
&& _port->cursorPosition() == 0) {
_host->setCursorPosition(_host->getLastText().size());
_host->setFocus();
}
}, _port->lifetime());
const auto submit = [=] {
if (_webHost->hasFocus()
&& !_webHost->getLastText().trimmed().isEmpty()) {
_secret->setFocus();
} else if (_host->hasFocus()
&& !_host->getLastText().trimmed().isEmpty()) {
_port->setFocus();
} else if (_port->hasFocus()
&& !_port->getLastText().trimmed().isEmpty()) {
if (_type->current() == Type::Mtproto) {
_secret->setFocus();
} else {
_user->setFocus();
}
} else if (_user->hasFocus()) {
_password->setFocus();
} else {
save();
}
};
connect(_host.data(), &Ui::MaskedInputField::submitted, submit);
connect(_port.data(), &Ui::MaskedInputField::submitted, submit);
_user->submits(
) | rpl::on_next(submit, _user->lifetime());
_webHost->submits(
) | rpl::on_next(submit, _webHost->lifetime());
connect(_password.data(), &Ui::MaskedInputField::submitted, submit);
connect(_secret.data(), &Ui::MaskedInputField::submitted, submit);
refreshButtons();
setDimensionsToContent(st::boxWideWidth, _content);
}
void ProxyBox::refreshButtons() {
clearButtons();
addButton(tr::lng_settings_save(), [=] { save(); });
addButton(tr::lng_cancel(), [=] { closeBox(); });
const auto type = _type->current();
if (_allowShare
&& (type == Type::Socks5
|| type == Type::Mtproto
|| type == Type::Web
|| type == Type::Naive)) {
addLeftButton(tr::lng_proxy_share(), [=] { share(); });
}
}
void ProxyBox::save() {
if (const auto data = collectData()) {
_callback(data);
closeBox();
}
}
void ProxyBox::share() {
if (const auto data = collectData()) {
_shareCallback(data);
}
}
ProxyData ProxyBox::collectData() {
auto result = ProxyData();
result.type = _type->current();
const auto web = (result.type == Type::Web);
result.host = web
? QString()
: _host->getLastText().trimmed();
result.port = web
? 443
: _port->getLastText().trimmed().toInt();
result.user = (result.type == Type::Mtproto || web)
? QString()
: _user->getLastText();
result.password = (result.type == Type::Mtproto || web)
? _secret->getLastText()
: _password->getLastText();
if (web) {
result.setWebAddress(_webHost->getLastText());
}
if (result.host.isEmpty()) {
if (web) {
_webHost->showError();
} else {
_host->showError();
}
} else if (!web && !result.port) {
_port->showError();
} else if ((result.type == Type::Http || result.type == Type::Socks5)
&& !result.password.isEmpty() && result.user.isEmpty()) {
_user->showError();
} else if ((result.type == Type::Mtproto || web) && !result.valid()) {
_secret->showError();
} else if (!result) {
if (web) {
_webHost->showError();
} else {
_host->showError();
}
} else {
return result;
}
return ProxyData();
}
void ProxyBox::setupTypes() {
const auto types = std::vector<std::pair<Type, QString>>{
{ Type::Mtproto, u"MTPROTO"_q },
{ Type::Socks5, u"SOCKS5"_q },
{ Type::Http, u"HTTP"_q },
{ Type::Web, u"WEB"_q },
{ Type::Naive, u"NAIVE"_q },
};
for (const auto &[type, label] : types) {
_content->add(
object_ptr<Ui::Radioenum<Type>>(
_content,
_type,
type,
label),
st::proxyEditTypePadding);
}
auto warning = _type->value(
) | rpl::map([](Type type) {
return (type == Type::Web)
? tr::lng_proxy_web_warning(tr::now)
: tr::lng_proxy_sponsor_warning(tr::now);
});
_aboutSponsored = _content->add(object_ptr<Ui::SlideWrap<>>(
_content,
object_ptr<Ui::PaddingWrap<>>(
_content,
object_ptr<Ui::FlatLabel>(
_content,
std::move(warning),
st::boxDividerLabel),
st::proxyAboutSponsorPadding)));
}
void ProxyBox::setupSocketAddress(const ProxyData &data) {
_socketAddress = _content->add(
object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
_content,
object_ptr<Ui::VerticalLayout>(_content)));
const auto content = _socketAddress->entity();
addLabel(content, tr::lng_proxy_address_label(tr::now));
const auto address = content->add(
object_ptr<Ui::FixedHeightWidget>(
content,
st::connectionHostInputField.heightMin),
st::proxyEditInputPadding);
_host = Ui::CreateChild<HostInput>(
address,
st::connectionHostInputField,
tr::lng_connection_host_ph(),
data.host);
_port = Ui::CreateChild<Ui::NumberInput>(
address,
st::connectionPortInputField,
tr::lng_connection_port_ph(),
data.port ? QString::number(data.port) : QString(),
65535);
{
// The field is at least as wide as its placeholder.
const auto &st = st::connectionPortInputField;
const auto placeholder = st.placeholderFont->width(
tr::lng_connection_port_ph(tr::now))
+ st.textMargins.left()
+ st.textMargins.right()
+ st.placeholderMargins.left()
+ st.placeholderMargins.right();
if (placeholder > _port->width()) {
_port->resize(placeholder, _port->height());
}
}
address->widthValue(
) | rpl::on_next([=](int width) {
_port->moveToRight(0, 0);
_host->resize(
width - _port->width() - st::proxyEditSkip,
_host->height());
_host->moveToLeft(0, 0);
}, address->lifetime());
}
void ProxyBox::setupWebAddress(const ProxyData &data) {
_webAddress = _content->add(
object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
_content,
object_ptr<Ui::VerticalLayout>(_content)));
const auto content = _webAddress->entity();
addLabel(content, tr::lng_proxy_web_server_label(tr::now));
_webHost = content->add(
object_ptr<Ui::InputField>(
content,
st::connectionUserInputField,
tr::lng_proxy_web_host_ph(),
(data.type == Type::Web) ? data.webAddress() : QString()),
st::proxyEditInputPadding);
_webHost->setInputMethodHints(Qt::ImhUrlCharactersOnly
| Qt::ImhNoAutoUppercase
| Qt::ImhNoPredictiveText);
}
void ProxyBox::setupCredentials(const ProxyData &data) {
_credentials = _content->add(
object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
_content,
object_ptr<Ui::VerticalLayout>(_content)));
const auto credentials = _credentials->entity();
addLabel(credentials, tr::lng_proxy_credentials_optional(tr::now));
_user = credentials->add(
object_ptr<Ui::InputField>(
credentials,
st::connectionUserInputField,
tr::lng_connection_user_ph(),
data.user),
st::proxyEditInputPadding);
_user->setInputMethodHints(Qt::ImhNoAutoUppercase
| Qt::ImhNoPredictiveText);
auto passwordWrap = object_ptr<Ui::RpWidget>(credentials);
_password = Ui::CreateChild<Ui::PasswordInput>(
passwordWrap.data(),
st::connectionPasswordInputField,
tr::lng_connection_password_ph(),
(data.type == Type::Mtproto || data.type == Type::Web)
? QString()
: data.password);
_password->move(0, 0);
_password->heightValue(
) | rpl::on_next([=, wrap = passwordWrap.data()](int height) {
wrap->resize(wrap->width(), height);
}, _password->lifetime());
passwordWrap->widthValue(
) | rpl::on_next([=](int width) {
_password->resize(width, _password->height());
}, _password->lifetime());
credentials->add(std::move(passwordWrap), st::proxyEditInputPadding);
}
void ProxyBox::setupMtprotoCredentials(const ProxyData &data) {
_mtprotoCredentials = _content->add(
object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
_content,
object_ptr<Ui::VerticalLayout>(_content)));
const auto mtproto = _mtprotoCredentials->entity();
addLabel(mtproto, tr::lng_proxy_credentials(tr::now));
auto secretWrap = object_ptr<Ui::RpWidget>(mtproto);
_secret = Ui::CreateChild<Base64UrlInput>(
secretWrap.data(),
st::connectionUserInputField,
tr::lng_connection_proxy_secret_ph(),
(data.type == Type::Mtproto || data.type == Type::Web)
? data.password
: QString());
_secret->move(0, 0);
_secret->heightValue(
) | rpl::on_next([=, wrap = secretWrap.data()](int height) {
wrap->resize(wrap->width(), height);
}, _secret->lifetime());
secretWrap->widthValue(
) | rpl::on_next([=](int width) {
_secret->resize(width, _secret->height());
}, _secret->lifetime());
mtproto->add(std::move(secretWrap), st::proxyEditInputPadding);
}
void ProxyBox::setupControls(const ProxyData &data) {
_type = std::make_shared<Ui::RadioenumGroup<Type>>(
(data.type == Type::None
? Type::Mtproto
: data.type));
_content.create(this);
_content->resizeToWidth(st::boxWideWidth);
_content->moveToLeft(0, 0);
setupTypes();
setupSocketAddress(data);
setupWebAddress(data);
setupCredentials(data);
setupMtprotoCredentials(data);
const auto handleType = [=](Type type) {
const auto web = (type == Type::Web);
const auto credentialsShown = (type == Type::Http
|| type == Type::Socks5
|| type == Type::Naive);
const auto mtprotoShown = (type == Type::Mtproto || web);
_socketAddress->toggle(!web, anim::type::instant);
_webAddress->toggle(web, anim::type::instant);
_credentials->toggle(credentialsShown, anim::type::instant);
_mtprotoCredentials->toggle(mtprotoShown, anim::type::instant);
_aboutSponsored->toggle(mtprotoShown, anim::type::instant);
const auto credentialsPolicy = credentialsShown
? Qt::StrongFocus
: Qt::NoFocus;
_user->rawTextEdit()->setFocusPolicy(credentialsPolicy);
_password->setFocusPolicy(credentialsPolicy);
_secret->setFocusPolicy(
mtprotoShown ? Qt::StrongFocus : Qt::NoFocus);
_webHost->setFocusPolicy(web ? Qt::StrongFocus : Qt::NoFocus);
};
_type->setChangedCallback([=](Type type) {
handleType(type);
refreshButtons();
});
handleType(_type->current());
}
void ProxyBox::addLabel(
not_null<Ui::VerticalLayout*> parent,
const QString &text) const {
parent->add(
object_ptr<Ui::FlatLabel>(
parent,
text,
st::proxyEditTitle),
st::proxyEditTitlePadding);
}
using Connection = MTP::details::AbstractConnection;
using Checker = MTP::ProxyCheckConnection;
} // namespace
ProxiesBoxController::ProxiesBoxController(not_null<Main::Account*> account)
: _account(account)
, _settings(Core::App().settings().proxy())
, _saveTimer([] { Local::writeSettings(); })
{
_list = ranges::views::all(
_settings.list()
) | ranges::views::transform([&](const ProxyData &proxy) {
return Item{ ++_idCounter, proxy };
}) | ranges::to_vector;
_settings.connectionTypeChanges(
) | rpl::on_next([=] {
_proxySettingsChanges.fire_copy(_settings.settings());
const auto i = findByProxy(_settings.selected());
if (i != end(_list)) {
updateView(*i);
}
}, _lifetime);
_account->mtp().connectionStatus().pingTimeValue(
) | rpl::skip(1) | rpl::on_next([=] {
const auto i = findByProxy(_settings.selected());
if (i != end(_list)) {
updateView(*i);
}
}, _lifetime);
_account->mtp().ping();
}
ProxyData ProxiesBoxController::ProxyFromLink(const QString &link) {
const auto trimmed = link.trimmed();
const auto converted = Core::TryConvertUrlToLocal(trimmed);
return ProxyDataFromLocalUrl(converted.isEmpty() ? trimmed : converted);
}
void ProxiesBoxController::ShowApplyConfirmation(
Window::SessionController *controller,
Type type,
const QMap<QString, QString> &fields) {
const auto proxy = ProxyDataFromFields(type, fields);
if (!proxy) {
const auto status = proxy.status();
auto box = Ui::MakeInformBox(
((status == ProxyData::Status::Unsupported)
? tr::lng_proxy_unsupported(tr::now, tr::rich)
: (status == ProxyData::Status::IncorrectSecret)
? tr::lng_proxy_incorrect_secret(tr::now, tr::rich)
: tr::lng_proxy_invalid(tr::now, tr::rich)));
if (controller) {
controller->uiShow()->showBox(std::move(box));
} else {
Ui::show(std::move(box));
}
return;
}
static const auto UrlStartRegExp = QRegularExpression(
"^https://",
QRegularExpression::CaseInsensitiveOption);
static const auto UrlEndRegExp = QRegularExpression("/$");
const auto displayed = "https://"
+ ((type == Type::Web) ? proxy.webAddress() : proxy.host)
+ "/";
const auto parsed = QUrl::fromUserInput(displayed);
const auto displayUrl = !UrlClickHandler::IsSuspicious(displayed)
? displayed
: parsed.isValid()
? QString::fromUtf8(parsed.toEncoded())
: UrlClickHandler::ShowEncoded(displayed);
const auto displayServer = QString(
displayUrl
).replace(
UrlStartRegExp,
QString()
).replace(UrlEndRegExp, QString());
const auto box = [=](not_null<Ui::GenericBox*> box) {
box->setTitle(tr::lng_proxy_box_table_title());
box->setStyle(st::proxyApplyBox);
box->addTopButton(st::boxTitleClose, [=] {
box->closeBox();
});
if (ProxyDataIsShareable(proxy) && type != Type::Web) {
const auto account = controller
? &controller->session().account()
: &Core::App().activeAccount();
const auto top = box->addTopButton(st::boxTitleMenu);
const auto state = top->lifetime().make_state<
TopButtonMenuState>();
top->setClickedCallback([=] {
state->menu = base::make_unique_q<Ui::PopupMenu>(
top,
st::popupMenuWithIcons);
const auto raw = state->menu.get();
const auto addAction = Ui::Menu::CreateAddActionCallback(raw);
addAction({
.text = tr::lng_proxy_edit_share(tr::now),
.handler = [=] {
ShareProxy(box->uiShow(), account, proxy, false);
},
.icon = &st::menuIconShare,
});
addAction({
.text = tr::lng_group_invite_context_qr(tr::now),
.handler = [=] {
ShareProxy(box->uiShow(), account, proxy, true);
},
.icon = &st::menuIconQrCode,
});
raw->setForcedOrigin(Ui::PanelAnimation::Origin::TopRight);
top->setForceRippled(true);
raw->setDestroyedCallback([=] {
if (!state->closing) {
top->setForceRippled(false);
}
});
raw->popup(top->mapToGlobal(QPoint(
top->width(),
top->height() - st::lineWidth * 3)));
return true;
});
}
const auto table = box->addRow(
object_ptr<Ui::TableLayout>(
box,
st::proxyApplyBoxTable),
st::proxyApplyBoxTableMargin);
const auto addRow = [&](
rpl::producer<QString> label,
object_ptr<Ui::RpWidget> value) {
table->addRow(
object_ptr<Ui::FlatLabel>(
table,
std::move(label),
table->st().defaultLabel),
std::move(value),
st::proxyApplyBoxTableLabelMargin,
st::proxyApplyBoxTableValueMargin);
};
const auto add = [&](
const QString &value,
rpl::producer<QString> label) {
if (!value.isEmpty()) {
constexpr auto kOneLineCount = 20;
const auto oneLine = value.length() <= kOneLineCount;
auto widget = object_ptr<Ui::FlatLabel>(
table,
rpl::single(Ui::Text::Wrapped(
{ value },
EntityType::Code,
{})),
(oneLine
? table->st().defaultValue
: st::proxyApplyBoxValueMultiline),
st::defaultPopupMenu);
addRow(std::move(label), std::move(widget));
}
};
if (!displayServer.isEmpty()) {
add(displayServer, tr::lng_proxy_box_server());
}
if (type != Type::Web) {
add(QString::number(proxy.port), tr::lng_proxy_box_port());
}
if (type == Type::Socks5 || type == Type::Naive) {
add(proxy.user, tr::lng_proxy_box_username());
add(proxy.password, tr::lng_proxy_box_password());
} else if (type == Type::Mtproto || type == Type::Web) {
add(proxy.password, tr::lng_proxy_box_secret());
}
if (type != Type::Web) {
struct ProxyCheckStatusState {
Checker v4;
Checker v6;
rpl::variable<TextWithEntities> statusValue;
MTP::ProxyCheckStatus progressStatus
= MTP::ProxyCheckStatus::Idle;
bool finished = false;
};
const auto state
= box->lifetime().make_state<ProxyCheckStatusState>();
state->statusValue = Ui::Text::Link(
tr::lng_proxy_box_check_status(tr::now));
const auto weak = base::make_weak(box);
auto statusWidget = object_ptr<Ui::FlatLabel>(
table,
state->statusValue.value(),
table->st().defaultValue,
st::defaultPopupMenu);
const auto statusLabel = statusWidget.data();
addRow(tr::lng_proxy_box_status(), std::move(statusWidget));
const auto relayout = [=] {
table->resizeToWidth(table->width());
};
const auto setIdle = [=] {
state->progressStatus = MTP::ProxyCheckStatus::Idle;
state->statusValue = Ui::Text::Link(
tr::lng_proxy_box_check_status(tr::now));
statusLabel->setTextColorOverride(std::nullopt);
relayout();
};
const auto setUnavailable = [=] {
state->statusValue = TextWithEntities{
tr::lng_proxy_box_table_unavailable(tr::now),
};
statusLabel->setTextColorOverride(
st::proxyRowStatusFgOffline->c);
};
const auto setProgress = [=](MTP::ProxyCheckStatus status) {
if (!weak || state->finished) {
return;
}
state->progressStatus = status;
state->statusValue = TextWithEntities{
ProxyCheckStatusText(status),
};
statusLabel->setTextColorOverride(
ProxyCheckStatusColor(status)->c);
if (status == MTP::ProxyCheckStatus::ConnectedByActiveSession) {
state->finished = true;
MTP::ResetProxyCheckers(state->v4, state->v6);
}
relayout();
};
const auto runCheck = [=] {
if (!weak) {
return;
}
const auto account = controller
? &controller->session().account()
: &Core::App().activeAccount();
state->finished = false;
state->progressStatus = MTP::ProxyCheckStatus::Idle;
state->statusValue = TextWithEntities{
tr::lng_proxy_box_table_checking(tr::now),
};
statusLabel->setTextColorOverride(
ProxyCheckStatusColor(state->progressStatus)->c);
relayout();
MTP::StartProxyCheck(
&account->mtp().runtimeEnvironment(),
proxy,
Core::App().settings().proxy().tryIPv6(),
Core::App().settings().proxyStealthOptions(),
state->v4,
state->v6,
[=](Connection *raw, int ping) {
if (!weak || state->finished) {
return;
}
MTP::DropProxyChecker(state->v4, state->v6, raw);
state->finished = true;
MTP::ResetProxyCheckers(state->v4, state->v6);
state->statusValue = TextWithEntities{
tr::lng_proxy_box_table_available(
tr::now,
lt_ping,
QString::number(ping)),
};
statusLabel->setTextColorOverride(
st::proxyRowStatusFgAvailable->c);
},
[=](Connection *raw) {
if (!weak || state->finished) {
return;
}
MTP::DropProxyChecker(state->v4, state->v6, raw);
if (!MTP::HasProxyCheckers(state->v4, state->v6)) {
state->finished = true;
setUnavailable();
}
},
setProgress);
if (!MTP::HasProxyCheckers(state->v4, state->v6)
&& !state->finished
&& state->progressStatus
!= MTP::ProxyCheckStatus::WaitingForConnectionSlot) {
state->finished = true;
setUnavailable();
}
};
statusLabel->setClickHandlerFilter([=](const auto &...) {
auto &proxy = Core::App().settings().proxy();
if (proxy.checkIpWarningShown()) {
runCheck();
} else {
box->uiShow()->showBox(Ui::MakeConfirmBox({
.text = tr::lng_proxy_check_ip_warning(),
.confirmed = [=](Fn<void()> close) {
auto &proxy = Core::App().settings().proxy();
proxy.setCheckIpWarningShown(true);
Local::writeSettings();
close();
runCheck();
},
.confirmText = tr::lng_proxy_check_ip_proceed(),
.title = tr::lng_proxy_check_ip_warning_title(),
}));
}
return false;
});
}
if (type == Type::Mtproto || type == Type::Web) {
table->addRow(
object_ptr<Ui::FlatLabel>(
table,
(type == Type::Web)
? tr::lng_proxy_web_warning()
: tr::lng_proxy_sponsor_warning(),
st::proxyApplyBoxSponsorLabel),
object_ptr<Ui::RpWidget>(nullptr),
st::proxyApplyBoxSponsorMargin,
st::proxyApplyBoxSponsorMargin);
}
const auto enableButton = box->addButton(
tr::lng_proxy_box_table_button(),
[=] {
// Starting a web proxy may run a nested loop closing the box.
const auto weak = base::make_weak(box);
auto &settings = Core::App().settings().proxy();
if (settings.indexInList(proxy) < 0) {
settings.addToList(proxy);
}
Core::App().setCurrentProxy(
proxy,
ProxyData::Settings::Enabled);
Local::writeSettings();
if (weak) {
box->closeBox();
}
});
enableButton->setFullRadius(true);
box->events() | rpl::on_next([=](not_null<QEvent*> e) {
if ((e->type() != QEvent::KeyPress) || !enableButton) {
return;
}
const auto k = static_cast<QKeyEvent*>(e.get());
if (k->key() == Qt::Key_Enter || k->key() == Qt::Key_Return) {
enableButton->clicked({}, Qt::LeftButton);
}
}, box->lifetime());
};
if (controller) {
controller->uiShow()->showBox(Box(box));
} else {
Ui::show(Box(box));
}
}
auto ProxiesBoxController::proxySettingsValue() const
-> rpl::producer<ProxyData::Settings> {
return _proxySettingsChanges.events_starting_with_copy(
_settings.settings()
) | rpl::distinct_until_changed();
}
void ProxiesBoxController::refreshChecker(Item &item) {
if (MTP::HasProxyCheckers(item.checker, item.checkerv6)) {
item.progressStatus = item.checker
? item.checker.state()->progressStatus
: item.checkerv6.state()->progressStatus;
updateView(item);
return;
}
item.state = ItemState::Checking;
item.progressStatus = MTP::ProxyCheckStatus::Idle;
updateView(item);
const auto id = item.id;
MTP::StartProxyCheck(
&_account->mtp().runtimeEnvironment(),
item.data,
Core::App().settings().proxy().tryIPv6(),
Core::App().settings().proxyStealthOptions(),
item.checker,
item.checkerv6,
[=](Connection *raw, int pingTime) {
const auto item = ranges::find(
_list,
id,
[](const Item &item) { return item.id; });
if (item == end(_list)) {
return;
}
MTP::DropProxyChecker(item->checker, item->checkerv6, raw);
MTP::ResetProxyCheckers(item->checker, item->checkerv6);
if (item->state == ItemState::Checking) {
item->state = ItemState::Available;
item->progressStatus
= MTP::ProxyCheckStatus::FirstMtprotoPayload;
item->ping = pingTime;
updateView(*item);
}
},
[=](Connection *raw) {
const auto item = ranges::find(
_list,
id,
[](const Item &item) { return item.id; });
if (item == end(_list)) {
return;
}
MTP::DropProxyChecker(item->checker, item->checkerv6, raw);
if (!MTP::HasProxyCheckers(item->checker, item->checkerv6)
&& item->state == ItemState::Checking) {
item->state = ItemState::Unavailable;
item->progressStatus = MTP::ProxyCheckStatus::Idle;
updateView(*item);
}
},
[=](MTP::ProxyCheckStatus status) {
const auto item = ranges::find(
_list,
id,
[](const Item &item) { return item.id; });
if (item == end(_list) || item->state != ItemState::Checking) {
return;
}
item->progressStatus = status;
updateView(*item);
});
if (!MTP::HasProxyCheckers(item.checker, item.checkerv6)
&& item.progressStatus
!= MTP::ProxyCheckStatus::WaitingForConnectionSlot
&& item.progressStatus
!= MTP::ProxyCheckStatus::ConnectedByActiveSession) {
item.state = ItemState::Unavailable;
updateView(item);
}
}
object_ptr<Ui::BoxContent> ProxiesBoxController::CreateOwningBox(
not_null<Main::Account*> account,
const QString &highlightId) {
auto controller = std::make_unique<ProxiesBoxController>(account);
auto box = controller->create(highlightId);
Ui::AttachAsChild(box, std::move(controller));
return box;
}
object_ptr<Ui::BoxContent> ProxiesBoxController::create(
const QString &highlightId) {
auto result = Box<ProxiesBox>(this, _settings, highlightId);
_show = result->uiShow();
result->beginInitialRows();
for (auto i = _list.rbegin(); i != _list.rend(); ++i) {
updateView(*i);
}
result->finishInitialRows();
return result;
}
auto ProxiesBoxController::findById(int id) -> std::vector<Item>::iterator {
const auto result = ranges::find(
_list,
id,
[](const Item &item) { return item.id; });
Assert(result != end(_list));
return result;
}
auto ProxiesBoxController::findByProxy(const ProxyData &proxy)
->std::vector<Item>::iterator {
return ranges::find(
_list,
proxy,
[](const Item &item) { return item.data; });
}
void ProxiesBoxController::deleteItem(int id) {
setDeleted(id, true);
}
void ProxiesBoxController::deleteItems() {
for (const auto &item : _list) {
setDeleted(item.id, true);
}
}
void ProxiesBoxController::deleteItems(const base::flat_set<int> &ids) {
for (const auto id : ids) {
setDeleted(id, true);
}
}
void ProxiesBoxController::restoreItem(int id) {
setDeleted(id, false);
}
void ProxiesBoxController::shareItem(int id, bool qr) {
share(findById(id)->data, qr);
}
void ProxiesBoxController::shareItems() {
auto ids = base::flat_set<int>();
for (const auto &item : _list) {
ids.emplace(item.id);
}
shareItems(ids);
}
void ProxiesBoxController::shareItems(const base::flat_set<int> &ids) {
auto result = QString();
for (const auto &item : _list) {
if (!ids.contains(item.id)) {
continue;
} else if (!item.deleted && ProxyDataIsShareable(item.data)) {
const auto link = ProxyDataToPublicLink(_account, item.data);
if (!link.isEmpty()) {
result += (result.isEmpty() ? QString() : u"\n\n"_q) + link;
}
}
}
if (result.isEmpty()) {
return;
}
QGuiApplication::clipboard()->setText(result);
_show->showToast({
.text = { tr::lng_proxy_edit_share_list_toast(tr::now) },
.iconLottie = u"toast/copy"_q,
.iconLottieSize = st::toastLottieIconSize,
});
}
void ProxiesBoxController::checkItem(int id) {
auto item = findById(id);
if (item->deleted) {
return;
}
refreshChecker(*item);
}
void ProxiesBoxController::applyItem(int id) {
auto item = findById(id);
if (_settings.isEnabled() && (_settings.selected() == item->data)) {
return;
} else if (item->deleted) {
return;
}
auto old = findByProxy(_settings.selected());
Core::App().setCurrentProxy(
item->data,
ProxyData::Settings::Enabled);
saveDelayed();
if (old != end(_list) && old->id != id) {
updateView(*old);
}
}
void ProxiesBoxController::reorderItems(int oldPosition, int newPosition) {
const auto count = int(_list.size());
const auto listIndexFromRowIndex = [&](int rowIndex) {
return count - 1 - rowIndex;
};
const auto from = listIndexFromRowIndex(oldPosition);
const auto to = listIndexFromRowIndex(newPosition);
if (from < 0 || from >= count || to < 0 || to >= count || from == to) {
return;
}
const auto data = _list[from].data;
const auto deleted = _list[from].deleted;
base::reorder(_list, from, to);
if (!deleted) {
const auto settingsFrom = _settings.indexInList(data);
auto settingsTo = 0;
for (auto i = 0; i != to; ++i) {
if (!_list[i].deleted) {
++settingsTo;
}
}
if (settingsFrom >= 0) {
_settings.moveInList(settingsFrom, settingsTo);
}
}
saveDelayed();
}
void ProxiesBoxController::openBrowser(int id) {
const auto item = findById(id);
if (_settings.isEnabled()
&& _settings.selected() == item->data
&& item->data.type == Type::Web) {
MTP::WebProxy::Transport::OpenBrowser(item->data);
}
}
void ProxiesBoxController::setDeleted(int id, bool deleted) {
auto item = findById(id);
if (item->deleted == deleted) {
return;
}
item->deleted = deleted;
if (deleted) {
const auto removed = _settings.removeFromList(item->data);
Assert(removed);
if (item->data == _settings.selected()) {
_lastSelectedProxy = _settings.selected();
_settings.setSelected(MTP::ProxyData());
if (_settings.isEnabled()) {
_lastSelectedProxyUsed = true;
Core::App().setCurrentProxy(
ProxyData(),
ProxyData::Settings::System);
saveDelayed();
} else {
_lastSelectedProxyUsed = false;
}
}
} else {
if (_settings.indexInList(item->data) < 0) {
const auto &proxies = _settings.list();
auto insertBefore = item + 1;
while (insertBefore != end(_list) && insertBefore->deleted) {
++insertBefore;
}
const auto foundIndex = (insertBefore == end(_list))
? int(proxies.size())
: _settings.indexInList(insertBefore->data);
const auto insertIndex = (foundIndex >= 0)
? foundIndex
: int(proxies.size());
_settings.insertToList(insertIndex, item->data);
}
if (!_settings.selected() && _lastSelectedProxy == item->data) {
Assert(!_settings.isEnabled());
if (base::take(_lastSelectedProxyUsed)) {
Core::App().setCurrentProxy(
base::take(_lastSelectedProxy),
ProxyData::Settings::Enabled);
} else {
_settings.setSelected(base::take(_lastSelectedProxy));
}
}
}
saveDelayed();
updateView(*item);
}
object_ptr<Ui::BoxContent> ProxiesBoxController::editItemBox(int id) {
return Box<ProxyBox>(findById(id)->data, [=](const ProxyData &result) {
auto i = findById(id);
auto j = ranges::find(
_list,
result,
[](const Item &item) { return item.data; });
if (j != end(_list) && j != i) {
replaceItemWith(i, j);
} else {
replaceItemValue(i, result);
}
}, [=](const ProxyData &proxy) {
share(proxy);
});
}
void ProxiesBoxController::replaceItemWith(
std::vector<Item>::iterator which,
std::vector<Item>::iterator with) {
// Read before the erase below: _list is a vector, so erasing `which`
// shifts everything after it and leaves `with` naming the wrong item.
const auto withId = with->id;
const auto withDeleted = with->deleted;
if (which->deleted) {
// A deleted item is not in the settings list at all, so it has to
// go back in before it can be removed - the same restore-first
// order replaceItemValue() uses right below.
restoreItem(which->id);
}
const auto removed = _settings.removeFromList(which->data);
Assert(removed);
_views.fire({ which->id });
_list.erase(which);
if (withDeleted) {
restoreItem(withId);
}
applyItem(withId);
saveDelayed();
}
void ProxiesBoxController::replaceItemValue(
std::vector<Item>::iterator which,
const ProxyData &proxy) {
if (which->deleted) {
restoreItem(which->id);
}
const auto replaced = _settings.replaceInList(which->data, proxy);
Assert(replaced);
which->data = proxy;
refreshChecker(*which);
applyItem(which->id);
saveDelayed();
}
object_ptr<Ui::BoxContent> ProxiesBoxController::addNewItemBox() {
const auto fromClipboard = ProxyDataFromClipboard();
return Box<ProxyBox>(fromClipboard, [=](const ProxyData &result) {
auto j = ranges::find(
_list,
result,
[](const Item &item) { return item.data; });
if (j != end(_list)) {
if (j->deleted) {
restoreItem(j->id);
}
applyItem(j->id);
} else {
addNewItem(result);
}
}, [=](const ProxyData &proxy) {
share(proxy);
});
}
bool ProxiesBoxController::contains(const ProxyData &proxy) const {
const auto j = ranges::find(
_list,
proxy,
[](const Item &item) { return item.data; });
return (j != end(_list));
}
void ProxiesBoxController::addNewItem(const ProxyData &proxy) {
_settings.addToList(proxy);
_list.push_back({ ++_idCounter, proxy });
refreshChecker(_list.back());
applyItem(_list.back().id);
}
bool ProxiesBoxController::setProxySettings(ProxyData::Settings value) {
if (_settings.settings() == value) {
return true;
} else if (value == ProxyData::Settings::Enabled) {
if (_settings.list().empty()) {
return false;
} else if (!_settings.selected()) {
_settings.setSelected(_settings.list().back());
auto j = findByProxy(_settings.selected());
if (j != end(_list)) {
updateView(*j);
}
}
}
Core::App().setCurrentProxy(_settings.selected(), value);
saveDelayed();
return true;
}
void ProxiesBoxController::setTryIPv6(bool enabled) {
if (Core::App().settings().proxy().tryIPv6() == enabled) {
return;
}
Core::App().settings().proxy().setTryIPv6(enabled);
// Restart every account's connections, not only the active one.
Core::App().restartProxyConnections();
_settings.connectionTypeChangesNotify();
saveDelayed();
}
void ProxiesBoxController::setFastWarmup(bool enabled) {
if (Core::App().settings().proxy().fastWarmup() == enabled) {
return;
}
// The flag is read on each admission, no restart is needed.
Core::App().settings().proxy().setFastWarmup(enabled);
saveDelayed();
}
void ProxiesBoxController::saveDelayed() {
_saveTimer.callOnce(kSaveSettingsDelayedTimeout);
}
auto ProxiesBoxController::views() const -> rpl::producer<ItemView> {
return _views.events();
}
rpl::producer<bool> ProxiesBoxController::listShareableChanges() const {
return _views.events_starting_with(ItemView()) | rpl::map([=] {
for (const auto &item : _list) {
if (!item.deleted && ProxyDataIsShareable(item.data)) {
return true;
}
}
return false;
});
}
void ProxiesBoxController::updateView(const Item &item) {
const auto selected = (_settings.selected() == item.data);
const auto deleted = item.deleted;
const auto type = [&] {
switch (item.data.type) {
case Type::Http: return u"HTTP"_q;
case Type::Socks5: return u"SOCKS5"_q;
case Type::Mtproto: return u"MTPROTO"_q;
case Type::Web: return u"WEB"_q;
case Type::Naive: return u"NAIVE"_q;
}
Unexpected("Proxy type in ProxiesBoxController::updateView.");
}();
const auto fallbackState = [&] {
if (!selected || !_settings.isEnabled()) {
return item.state;
} else if (item.data.type == Type::Web) {
switch (MTP::WebProxy::Transport::CurrentState(item.data)) {
case MTP::WebProxy::Transport::State::WaitingForBrowser:
return ItemState::WaitingForBrowser;
case MTP::WebProxy::Transport::State::Failed:
return ItemState::Unavailable;
case MTP::WebProxy::Transport::State::Connected:
return ItemState::Online;
case MTP::WebProxy::Transport::State::Idle:
return ItemState::NotTested;
case MTP::WebProxy::Transport::State::Connecting:
return ItemState::Connecting;
}
Unexpected("Web proxy transport state.");
} else if (_account->mtp().dcstate() == MTP::ConnectedState) {
return ItemState::Online;
}
return ItemState::Connecting;
}();
const auto state = fallbackState;
const auto ping = (state == ItemState::Online)
? int(_account->mtp().connectionStatus().pingTime())
: item.ping;
const auto supportsShare = ProxyDataIsShareable(item.data);
_views.fire({
item.id,
type,
((item.data.type == Type::Web)
? item.data.webAddress()
: item.data.host),
item.data.port,
ping,
!deleted && selected,
deleted,
!deleted && supportsShare,
item.data.type == Type::Web,
!deleted
&& selected
&& _settings.isEnabled()
&& item.data.type == Type::Web
&& (state == ItemState::WaitingForBrowser
|| state == ItemState::Unavailable),
state,
item.progressStatus,
QString(),
});
}
void ProxiesBoxController::share(const ProxyData &proxy, bool qr) {
ShareProxy(_show, _account, proxy, qr);
}
void ProxiesBoxController::Show(
not_null<Window::SessionController*> controller,
const QString &highlightId) {
controller->show(
CreateOwningBox(&controller->session().account(), highlightId));
}
ProxiesBoxController::~ProxiesBoxController() {
if (_saveTimer.isActive()) {
base::call_delayed(
kSaveSettingsDelayedTimeout,
QCoreApplication::instance(),
[] { Local::writeSettings(); });
}
}