#include "dialogs/SpeedLimiterDialog.hpp" #include #include #include #include #include #include #include #include #include "rpc/Protocol.hpp" #include "rpc/RpcClient.hpp" #include "util/Theme.hpp" namespace velox::gui { QJsonObject SpeedLimiterDialog::buildParams(bool enabled, int kibps, bool applyToRunning) { const qint64 bps = enabled ? static_cast(std::max(1, kibps)) * 1024 : 0; return QJsonObject{ {"enabled", enabled}, {"globalBps", bps}, {"applyToRunning", applyToRunning}, }; } SpeedLimiterDialog::SpeedLimiterDialog(rpc::RpcClient *client, QWidget *parent) : QDialog(parent), client_(client), enabled_(new QCheckBox(tr("Limit download speed"), this)), kibps_(new QSpinBox(this)), applyToRunning_(new QCheckBox(tr("Apply to running downloads now"), this)), statusLabel_(new QLabel(this)) { setWindowTitle(tr("Speed Limiter")); kibps_->setRange(1, 1000000); kibps_->setSuffix(tr(" KiB/s")); kibps_->setEnabled(false); connect(enabled_, &QCheckBox::toggled, kibps_, &QWidget::setEnabled); statusLabel_->setStyleSheet(theme::errorLabelStyle()); statusLabel_->hide(); auto *form = new QFormLayout; form->addRow(enabled_); form->addRow(tr("Limit to:"), kibps_); form->addRow(applyToRunning_); auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); connect(buttons, &QDialogButtonBox::accepted, this, &SpeedLimiterDialog::save); connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); auto *layout = new QVBoxLayout(this); layout->addLayout(form); layout->addWidget(statusLabel_); layout->addWidget(buttons); setEnabled(false); QPointer self(this); client_->call(QString::fromLatin1(rpc::method::kLimiterGet), {}, [self](const rpc::RpcReply &reply) { if (!self) { return; } self->setEnabled(true); if (!reply.ok()) { self->statusLabel_->setText( tr("Could not load the limiter: %1").arg(reply.error.message)); self->statusLabel_->show(); return; } self->onLoaded(reply.result.toObject()); }); } void SpeedLimiterDialog::onLoaded(const QJsonObject &limiter) { const bool on = limiter.value("enabled").toBool(); const qint64 bps = static_cast(limiter.value("globalBps").toDouble()); enabled_->setChecked(on); kibps_->setValue(std::max(1, bps / 1024)); kibps_->setEnabled(on); } void SpeedLimiterDialog::save() { const QJsonObject params = buildParams(enabled_->isChecked(), kibps_->value(), applyToRunning_->isChecked()); QPointer self(this); client_->call(QString::fromLatin1(rpc::method::kLimiterSet), params, [self](const rpc::RpcReply &reply) { if (!self) { return; } if (!reply.ok()) { self->statusLabel_->setText( tr("Could not apply the limit: %1").arg(reply.error.message)); self->statusLabel_->show(); return; } self->accept(); }); } } // namespace velox::gui