diff options
author | Simon Rettberg | 2022-10-30 20:34:23 +0100 |
---|---|---|
committer | Simon Rettberg | 2022-10-30 20:34:23 +0100 |
commit | 9f479b8f76238a03bce5d13aee14efd34e659c6e (patch) | |
tree | e320d32838202ac4604032da7a4bc3702cc304da /src/client | |
parent | Update translation files (diff) | |
download | pvs2-9f479b8f76238a03bce5d13aee14efd34e659c6e.tar.gz pvs2-9f479b8f76238a03bce5d13aee14efd34e659c6e.tar.xz pvs2-9f479b8f76238a03bce5d13aee14efd34e659c6e.zip |
Clean up and modernize code
- static "new-style" signal->slot connections
- Fix a lot of things Clang-Tidy complained about
- Move includes to .cpp files and use forward decls in .h
- Don't use <QtWidgets> and <QtCore>, but specific includes instead
Diffstat (limited to 'src/client')
24 files changed, 275 insertions, 302 deletions
diff --git a/src/client/addons/addons.cpp b/src/client/addons/addons.cpp index 43813ee..d39e53c 100644 --- a/src/client/addons/addons.cpp +++ b/src/client/addons/addons.cpp @@ -30,13 +30,12 @@ QList<Addon*> AddonManager::_addons; class Addon { public: - Addon() : button(nullptr), menu(nullptr), wantConnectInfo(false) {} - QPushButton *button; - QAction *menu; + QPushButton *button{}; + QAction *menu{}; QProcess process; - bool wantConnectInfo; - bool wantInit; - bool runAsync; + bool wantConnectInfo{}; + bool wantInit{}; + bool runAsync{}; QList<QPair<QString, QString>> envir; }; @@ -57,7 +56,7 @@ void AddonManager::loadFromPath(const QString &path, QList<QPushButton*> &button QFileInfoList fileInfoList = configDir.entryInfoList(QDir::Files, QDir::Name); QRegularExpression paramRegex("^([A-Z]+)=(.*)$", QRegularExpression::MultilineOption); - for (QFileInfo fileInfo : fileInfoList) { + for (const auto& fileInfo : fileInfoList) { QString filePath = fileInfo.absoluteFilePath(); QSettings setting(filePath, QSettings::IniFormat); setting.setIniCodec("UTF-8"); @@ -77,7 +76,7 @@ void AddonManager::loadFromPath(const QString &path, QList<QPushButton*> &button } // Alloc addon - Addon *addon = new Addon(); + auto *addon = new Addon(); // Toggle/click callback auto toggleFun = [=](bool value) { addon->envir.append(qMakePair(s_EVENT, s_clicked)); @@ -92,7 +91,7 @@ void AddonManager::loadFromPath(const QString &path, QList<QPushButton*> &button addon->menu->setCheckable(checkable); addon->menu->setToolTip(tooltip); menuEntries.append(addon->menu); - addon->menu->connect(addon->menu, &QAction::triggered, toggleFun); + QObject::connect(addon->menu, &QAction::triggered, toggleFun); } else if (type == "button") { addon->button = new QPushButton(caption); if (!icon.isNull()) { @@ -103,7 +102,7 @@ void AddonManager::loadFromPath(const QString &path, QList<QPushButton*> &button addon->button->setCheckable(checkable); addon->button->setToolTip(tooltip); buttons.append(addon->button); - addon->button->connect(addon->button, &QPushButton::clicked, toggleFun); + QObject::connect(addon->button, &QPushButton::clicked, toggleFun); } else { qDebug() << "Ignoring unknown addon type" << type; delete addon; @@ -117,13 +116,13 @@ void AddonManager::loadFromPath(const QString &path, QList<QPushButton*> &button // Setup process addon->process.setProgram(exec); // Stdin for status updates - addon->process.connect(&addon->process, &QProcess::readyReadStandardOutput, [=]() { + QObject::connect(&addon->process, &QProcess::readyReadStandardOutput, [=]() { auto lines = addon->process.readAllStandardOutput(); auto matches = paramRegex.globalMatch(lines); handleAddonOutput(addon, matches); }); // Stderr just for debugging - addon->process.connect(&addon->process, &QProcess::readyReadStandardError, [=]() { + QObject::connect(&addon->process, &QProcess::readyReadStandardError, [=]() { qDebug() << exec << "stderr:" << QString::fromLocal8Bit(addon->process.readAllStandardError()); }); } @@ -144,7 +143,7 @@ void AddonManager::initControls() void AddonManager::connectEvent(bool isLocal, const QString &address) { - for (auto addon : _addons) { + for (auto *addon : _addons) { if (!addon->wantConnectInfo) continue; addon->envir.append(qMakePair(s_EVENT, s_connected)); @@ -168,7 +167,7 @@ static void executeAddon(Addon *addon) { // Set up environment auto env = QProcessEnvironment::systemEnvironment(); - for (auto e : addon->envir) { + for (const auto& e : addon->envir) { env.insert(e.first, e.second); } addon->envir.clear(); @@ -184,26 +183,26 @@ static void executeAddon(Addon *addon) addon->process.setProcessEnvironment(env); // Run if (addon->runAsync) { - addon->process.startDetached(addon->process.program(), QStringList()); + QProcess::startDetached(addon->process.program(), QStringList()); } else { addon->process.start(); addon->process.closeWriteChannel(); } } -static void setAddonVisible(Addon *addon, bool newValue) +static void setAddonVisible(Addon *addon, bool visible) { if (addon->button != nullptr) { QWidget *p = addon->button->parentWidget(); bool wasVisible = p != nullptr && addon->button->isVisibleTo(p); - addon->button->setVisible(newValue); - if (p != nullptr && wasVisible != newValue) { + addon->button->setVisible(visible); + if (p != nullptr && wasVisible != visible) { // Visibility changed -- adjust size of toolbar - int size = (addon->button->width() + 2) * (newValue ? 1 : -1); + int size = (addon->button->width() + 2) * (visible ? 1 : -1); p->setFixedWidth(p->width() + size); } } else { - addon->menu->setVisible(newValue); + addon->menu->setVisible(visible); } } diff --git a/src/client/addons/addons.h b/src/client/addons/addons.h index 185c399..6f39087 100644 --- a/src/client/addons/addons.h +++ b/src/client/addons/addons.h @@ -1,5 +1,5 @@ -#ifndef _ADDONS_H_ -#define _ADDONS_H_ +#ifndef PVS_ADDONS_H_ +#define PVS_ADDONS_H_ #include <QString> #include <QList> diff --git a/src/client/clientapp/clientapp.cpp b/src/client/clientapp/clientapp.cpp index 8131e6f..2bc8fac 100644 --- a/src/client/clientapp/clientapp.cpp +++ b/src/client/clientapp/clientapp.cpp @@ -1,11 +1,18 @@ #include "clientapp.h" -#include <QNetworkInterface> + #include "../connectwindow/connectwindow.h" #include "../toolbar/toolbar.h" #include "../net/serverconnection.h" +#include <QNetworkInterface> +#include <QTranslator> +#include <QLibraryInfo> + ClientApp::ClientApp(int& argc, char** argv) - : QApplication(argc, argv), _connectionMode(ConnectionMode::None), _examMode(false), _connection(nullptr), _isManagerPc(false) + : QApplication(argc, argv) + , _connectionMode(ConnectionMode::None) + , _examMode(false) + , _connection(nullptr) { /* some values */ setOrganizationName("openslx"); @@ -21,24 +28,22 @@ ClientApp::ClientApp(int& argc, char** argv) /* set translator */ // System strings - QTranslator *qtTranslator = new QTranslator(this); + auto *qtTranslator = new QTranslator(this); if (!qtTranslator->load(QLocale::system(), "qt", "_", QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { qDebug() << "Could not load system string translations" << QLocale::system() << QLibraryInfo::location(QLibraryInfo::TranslationsPath); } else { installTranslator(qtTranslator); } // App specific - QTranslator *translator = new QTranslator(this); + auto *translator = new QTranslator(this); if (!translator->load(QLocale::system(), ":/", "l_")) { qDebug() << "Could not load app translations" << QLocale::system(); } else { installTranslator(translator); } - readIsManagerPc(); - _connectWindow = new ConnectWindow(nullptr); - connect(_connectWindow, SIGNAL(connected(ServerConnection*)), this, SLOT(connected(ServerConnection*))); + connect(_connectWindow, &ConnectWindow::connected, this, &ClientApp::connected); if (_connectionMode == ConnectionMode::Auto) { _toolbar = new Toolbar(true); // auto connect client without session ID. } else if (_connectionMode == ConnectionMode::Session) { @@ -54,7 +59,7 @@ ClientApp::ClientApp(int& argc, char** argv) QStringList ClientApp::parseParameters() { QStringList rest; - for (QString a : QApplication::arguments()) { + for (const QString &a : QApplication::arguments()) { if (a == "--exam-mode") { _examMode = true; } else if (a == "--auto") { @@ -79,7 +84,7 @@ QStringList ClientApp::arguments() QSharedPointer<QSettings> ClientApp::getSettings() { QSharedPointer<QSettings> set; - if (_iniPath == "") { + if (_iniPath.isEmpty()) { /* default location (system scope) */ set = QSharedPointer<QSettings>(new QSettings(QSettings::IniFormat, QSettings::SystemScope, "openslx/pvs2", "pvs2")); } else { @@ -90,32 +95,10 @@ QSharedPointer<QSettings> ClientApp::getSettings() return set; } -/* returns true when the pc of this client is also eligible to be a manager */ -void ClientApp::readIsManagerPc() -{ - QList<Room> myRooms; - auto conf = clientApp->getSettings(); - QStringList roomNames = conf->value("rooms").toStringList(); - - /* go through all rooms and check if this client is a manager of the room. */ - for (auto roomName : roomNames) { - conf->beginGroup(roomName); - const QString mgrIP = conf->value("mgrIP").toString(); - - foreach (const QHostAddress & address, QNetworkInterface::allAddresses()) { - if (address.toString() == mgrIP) { - _isManagerPc = true; - return; - } - } - conf->endGroup(); - } -} - void ClientApp::connected(ServerConnection* connection) { _connection = connection; - connect(connection, SIGNAL(disconnected(ServerConnection*)), this, SLOT(disconnected(ServerConnection*))); + connect(_connection, &ServerConnection::disconnected, this, &ClientApp::disconnected); } void ClientApp::disconnected(ServerConnection* connection) diff --git a/src/client/clientapp/clientapp.h b/src/client/clientapp/clientapp.h index 91dccf3..0824683 100644 --- a/src/client/clientapp/clientapp.h +++ b/src/client/clientapp/clientapp.h @@ -9,7 +9,7 @@ #if defined(clientApp) #undef clientApp #endif -#define clientApp (static_cast<ClientApp*>(QCoreApplication::instance())) +#define clientApp (static_cast<ClientApp*>(QCoreApplication::instance())) // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast) class Toolbar; class ConnectWindow; @@ -36,12 +36,9 @@ private: ServerConnection* _connection; QStringList _arguments; QString _iniPath; - bool _isManagerPc; QStringList parseParameters(); - void readIsManagerPc(); - public: ClientApp(int& argc, char** argv); @@ -56,9 +53,7 @@ public: ConnectWindow* connectWindow() const { return _connectWindow; } - bool isConfiguredAsManager() { return _isManagerPc; } - - bool isConnectedToLocalManager() { return _connection != nullptr && _connection->isLocalConnection(); } + bool isConnectedToLocalManager() const { return _connection != nullptr && _connection->isLocalConnection(); } private slots: diff --git a/src/client/connectwindow/connectwindow.cpp b/src/client/connectwindow/connectwindow.cpp index 8c47eea..0bc6835 100644 --- a/src/client/connectwindow/connectwindow.cpp +++ b/src/client/connectwindow/connectwindow.cpp @@ -7,13 +7,14 @@ #include <QNetworkInterface> #include "../../shared/settings.h" -#include "../../shared/network.h" #include "../../shared/util.h" #include "../net/serverconnection.h" #include "../clientapp/clientapp.h" #include "connectwindow.h" #include "ui_connectwindow.h" +#include <QCloseEvent> + #define UDPBUFSIZ 9000 #define SALT_LEN 18 @@ -43,17 +44,16 @@ ConnectWindow::ConnectWindow(QWidget *parent) : QWidget(parent) _ui->stackedWidget->setCurrentIndex(0); // Set actions of buttons - connect(_ui->btn_connection, SIGNAL(clicked()), this, SLOT(onBtnConnection())); - connect(_ui->btn_hide, SIGNAL(clicked()), this, SLOT(onBtnHide())); + connect(_ui->btn_connection, &QPushButton::clicked, this, &ConnectWindow::onBtnConnection); + connect(_ui->btn_hide, &QPushButton::clicked, this, &ConnectWindow::onBtnHide); - connect(_ui->comboBox_rooms, SIGNAL(currentIndexChanged(int)), this, SLOT(onRoomSelection(int))); + connect(_ui->comboBox_rooms, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ConnectWindow::onRoomSelection); // React on discovery signal - connect(&_serverDiscovery, SIGNAL(serverDetected(QString, quint16, QByteArray, QByteArray, bool)), - this, SLOT(onServerDetected(QString, quint16, QByteArray, QByteArray, bool))); + connect(&_serverDiscovery, &ServerDiscovery::serverDetected, this, &ConnectWindow::onServerDetected); /* finally the most requested feature: connect on press of the enter key */ - connect(_ui->lineEditName, SIGNAL(returnPressed()), _ui->btn_connection, SIGNAL(clicked())); + connect(_ui->lineEditName, &QLineEdit::returnPressed, this, &ConnectWindow::onBtnConnection); /* by default don't show the manual connection box */ _ui->box_manual->setVisible(false); @@ -64,7 +64,7 @@ ConnectWindow::ConnectWindow(QWidget *parent) : QWidget(parent) /** * @brief ConnectWindow::~ConnectWindow */ -ConnectWindow::~ConnectWindow() {} +ConnectWindow::~ConnectWindow() = default; @@ -181,7 +181,7 @@ void ConnectWindow::showEvent(QShowEvent* /* event */ ) * if not --> connect to given sessionName. * @param sessionName */ -void ConnectWindow::connectToSession(const QByteArray sessionName, QString mgrIP) +void ConnectWindow::connectToSession(const QByteArray& sessionName, const QString &mgrIP) { if (_state != Idle) return; @@ -254,7 +254,7 @@ void ConnectWindow::onBtnConnection() /** set the available rooms. * If the list of rooms is empty, switches automatically to the "manual * connection" page */ -void ConnectWindow::setAvailableRooms(QList<Room> m) +void ConnectWindow::setAvailableRooms(const QList<Room>& m) { _ui->comboBox_rooms->clear(); foreach (Room r, m) { @@ -298,9 +298,9 @@ void ConnectWindow::onRoomSelection(int index) void ConnectWindow::onServerDetected(const QString& host, const quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect) { _pendingConnection = new ServerConnection(host, port, sessionName, certHash, autoConnect); - connect(_pendingConnection, SIGNAL(stateChange(ConnectWindow::ConnectionState)), this, SLOT(onConnectionStateChange(ConnectWindow::ConnectionState))); - connect(_pendingConnection, SIGNAL(destroyed(QObject*)), this, SLOT(onConnectionClosed(QObject*))); - connect(_pendingConnection, SIGNAL(disconnected(ServerConnection*)), this, SLOT(onConnectionDisconnected(ServerConnection*))); + connect(_pendingConnection, &ServerConnection::stateChange, this, &ConnectWindow::onConnectionStateChange); + connect(_pendingConnection, &ServerConnection::destroyed, this, &ConnectWindow::onConnectionClosed); + connect(_pendingConnection, &ServerConnection::disconnected, this, &ConnectWindow::onConnectionDisconnected); } @@ -321,8 +321,8 @@ void ConnectWindow::onConnectionStateChange(ConnectWindow::ConnectionState state _state = Scanning; } if (state == Connected) { - QObject::disconnect(_pendingConnection, SIGNAL(stateChange(ConnectWindow::ConnectionState)), this, SLOT(onConnectionStateChange(ConnectWindow::ConnectionState))); - QObject::disconnect(_pendingConnection, SIGNAL(destroyed(QObject*)), this, SLOT(onConnectionClosed(QObject*))); + QObject::disconnect(_pendingConnection, &ServerConnection::stateChange, this, &ConnectWindow::onConnectionStateChange); + QObject::disconnect(_pendingConnection, &ServerConnection::destroyed, this, &ConnectWindow::onConnectionClosed); emit connected(_pendingConnection); _pendingConnection = nullptr; _timerHide = startTimer(2000); diff --git a/src/client/connectwindow/connectwindow.h b/src/client/connectwindow/connectwindow.h index 2df672d..4a0ae7d 100644 --- a/src/client/connectwindow/connectwindow.h +++ b/src/client/connectwindow/connectwindow.h @@ -16,7 +16,7 @@ #ifndef PVSCONNECTWINDOW_H_ #define PVSCONNECTWINDOW_H_ -#include <QtWidgets> +#include <QWidget> #include <QMap> #include <QUdpSocket> #include <QSslSocket> @@ -56,10 +56,10 @@ public: }; explicit ConnectWindow(QWidget *parent = nullptr); - virtual ~ConnectWindow(); + ~ConnectWindow() override; - void connectToSession(const QByteArray sessionName, QString mgrIP); - void setAvailableRooms(QList<Room> m); + void connectToSession(const QByteArray& sessionName, const QString &mgrIP); + void setAvailableRooms(const QList<Room>& m); private: Ui::ConnectWindow *_ui; @@ -71,18 +71,17 @@ private: QString _currentIp; QString _defaultSessionName; NetworkMessage _packet; - bool _tryReconnect; + bool _tryReconnect{}; int _timerHide; void updateUserInterface(); protected: - void timerEvent(QTimerEvent* event); - void closeEvent(QCloseEvent *e); - void showEvent(QShowEvent* event); + void timerEvent(QTimerEvent* event) override; + void closeEvent(QCloseEvent *e) override; + void showEvent(QShowEvent* event) override; protected slots: - void doShow(); void onBtnConnection(); void onBtnHide(); @@ -92,13 +91,15 @@ protected slots: void onConnectionClosed(QObject* connection); void onConnectionDisconnected(ServerConnection* connection); // void onUdpReadyRead(); - void onServerDetected(const QString& host, const quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect); + void onServerDetected(const QString& host, quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect); public slots: /** actually connects the connection **/ void DoConnect(); /** actually disconnects the connection **/ void DoDisconnect(); + + void doShow(); signals: void disconnect(); void connected(ServerConnection* connection); diff --git a/src/client/informationdialog/informationdialog.cpp b/src/client/informationdialog/informationdialog.cpp index fb3e87c..ff96641 100644 --- a/src/client/informationdialog/informationdialog.cpp +++ b/src/client/informationdialog/informationdialog.cpp @@ -1,19 +1,23 @@ #include "informationdialog.h" + #include <QNetworkInterface> #include <QHostInfo> #include <QDir> #include <QDirIterator> +#include <QLayout> +#include <QFormLayout> +#include <QLabel> InformationDialog::InformationDialog() : QDialog() { /* widgets */ - _lblTitle = new QLabel(tr("<h1>system information</h1>")); - _tableWidget = new QWidget(); + _lblTitle = new QLabel(tr("<h1>system information</h1>"), this); + _tableWidget = new QWidget(this); /* layouts */ - _layout = new QVBoxLayout(); - _tableLayout = new QFormLayout(); + _layout = new QVBoxLayout(this); + _tableLayout = new QFormLayout(this); /* */ _tableWidget->setLayout(_tableLayout); @@ -30,11 +34,12 @@ void InformationDialog::initTable() { /* NETWORK*/ /* hostnames */ - _tableLayout->addRow(new QLabel("<b>" + tr("hostname") + "</b>"), new QLabel(QHostInfo::localHostName())); + _tableLayout->addRow(new QLabel("<b>" + tr("hostname") + "</b>", this), + new QLabel(QHostInfo::localHostName(), this)); /* ips */ QStringList interfaceFilter; QString bridgeDevicePath("/sys/devices/virtual/net/"); - QDirIterator it(bridgeDevicePath, QStringList() << "brif", QDir::Dirs, QDirIterator::Subdirectories); + QDirIterator it(bridgeDevicePath, QStringList("brif"), QDir::Dirs, QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); QDir dir = it.filePath(); @@ -42,16 +47,16 @@ void InformationDialog::initTable() interfaceFilter += dir.entryList(); } - for (QNetworkInterface interface : QNetworkInterface::allInterfaces()) { + for (const auto& interface : QNetworkInterface::allInterfaces()) { if (interfaceFilter.contains(interface.name()) || interface.flags().testFlag(QNetworkInterface::IsLoopBack)) { qDebug() << "interface filtered: " << interface.name(); continue; } - _tableLayout->addRow("<u><b>" + interface.name() + "</b></u>", new QLabel("")); + _tableLayout->addRow("<u><b>" + interface.name() + "</b></u>", new QLabel(this)); - for (QNetworkAddressEntry entry : interface.addressEntries()) { + for (const auto &entry : interface.addressEntries()) { QLabel* label; QLabel* value; QHostAddress hostAddr = entry.ip(); @@ -61,18 +66,17 @@ void InformationDialog::initTable() continue; if (hostAddr.protocol() == QAbstractSocket::IPv6Protocol) { - label = new QLabel("IPv6"); - value = new QLabel(hostAddr.toString().split("%").first()); + label = new QLabel("IPv6", this); + value = new QLabel(hostAddr.toString().split("%").first(), this); } else { - label = new QLabel("IPv4"); - value = new QLabel(hostAddr.toString()); + label = new QLabel("IPv4", this); + value = new QLabel(hostAddr.toString(), this); } _tableLayout->addRow(label, value); } - _tableLayout->addRow("MAC", new QLabel(interface.hardwareAddress())); + _tableLayout->addRow("MAC", new QLabel(interface.hardwareAddress(), this)); } /* TODO: Add other information */ -} - +}
\ No newline at end of file diff --git a/src/client/informationdialog/informationdialog.h b/src/client/informationdialog/informationdialog.h index 42aaa7b..f210dd8 100644 --- a/src/client/informationdialog/informationdialog.h +++ b/src/client/informationdialog/informationdialog.h @@ -1,12 +1,11 @@ #ifndef INFORMATION_DIALOG_H #define INFORMATION_DIALOG_H + #include <QDialog> -#include <QLayout> -#include <QFormLayout> -#include <QLabel> -#include <QDebug> -#include <QStringList> +class QLayout; +class QFormLayout; +class QLabel; class InformationDialog : public QDialog { @@ -21,7 +20,7 @@ private: void initTable(); public: - InformationDialog(); + explicit InformationDialog(); }; diff --git a/src/client/main.cpp b/src/client/main.cpp index eefd0d8..cb7aea6 100644 --- a/src/client/main.cpp +++ b/src/client/main.cpp @@ -9,19 +9,18 @@ int main(int argc, char** argv) { ClientApp app(argc, argv); - qsrand(uint(QDateTime::currentMSecsSinceEpoch())); /* here we handle the arguments that were not handled by ClientApp */ - for (QString a : app.arguments()) { + for (const auto &a : app.arguments()) { if (a == "--usage" || a == "--help") { - qStdout() << "Usage: pvsclient [--exam-mode] [--auto|--session=xxx|\"\"]" << endl; + qStdout() << "Usage: pvsclient [--exam-mode] [--auto|--session=xxx|\"\"]" << Qt::endl; exit(0); } else if (a.contains("pvsclient")) { /* do nothing */ } else { - qStdout() << "Unknown argument: " << a << endl; + qStdout() << "Unknown argument: " << a << Qt::endl; exit(1); } } - return app.exec(); + return ClientApp::exec(); } diff --git a/src/client/net/serverconnection.cpp b/src/client/net/serverconnection.cpp index ca19c76..e500528 100644 --- a/src/client/net/serverconnection.cpp +++ b/src/client/net/serverconnection.cpp @@ -1,21 +1,20 @@ #include "serverconnection.h" -#include <QtCore> -#include <QPixmap> -#include <QGuiApplication> -#include <QHostInfo> -#include <unistd.h> -#include <cstdlib> -#include <sys/types.h> -#include <pwd.h> -//#define verbose #include "../vnc/vncserver.h" - #include "../../shared/util.h" #include "../../shared/settings.h" #include "../util/platform/blankscreen.h" #include "../clientapp/clientapp.h" +#include <QPixmap> +#include <QGuiApplication> +#include <QHostInfo> +#include <QScreen> +// For getting logged-in username +#include <sys/types.h> +#include <pwd.h> +#include <unistd.h> + #define CHALLENGE_LEN 20 ServerConnection::ServerConnection(const QString& host, const quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect) : @@ -23,16 +22,13 @@ ServerConnection::ServerConnection(const QString& host, const quint16 port, cons { _socket = new QSslSocket(); _blank = new BlankScreen(); - connect(_socket, SIGNAL(encrypted()), this, SLOT(sock_connected())); - connect(_socket, SIGNAL(readyRead()), this, SLOT(sock_dataArrival())); - connect(_socket, SIGNAL(disconnected()), this, SLOT(sock_closed())); - connect(_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(sock_error(QAbstractSocket::SocketError))); - connect(_socket, - SIGNAL(sslErrors(const QList<QSslError> &)), - this, - SLOT(sslErrors(const QList<QSslError> &)) + connect(_socket, &QSslSocket::encrypted, this, &ServerConnection::sock_connected); + connect(_socket, &QSslSocket::readyRead, this, &ServerConnection::sock_dataArrival); + connect(_socket, &QSslSocket::disconnected, this, &ServerConnection::sock_closed); + connect(_socket, &QSslSocket::errorOccurred, this, &ServerConnection::sock_error); + connect(_socket, QOverload<const QList<QSslError> &>::of(&QSslSocket::sslErrors), + this, &ServerConnection::sslErrors ); - connect(_socket, &QSslSocket::peerVerifyError, [=](const QSslError &error) { qDebug() << "PVE:" << error.errorString(); }); qDebug("Connecting to %s on port %d", host.toUtf8().data(), int(port)); _socket->ignoreSslErrors(); _socket->connectToHostEncrypted(host, port); @@ -40,7 +36,7 @@ ServerConnection::ServerConnection(const QString& host, const quint16 port, cons _lastData = QDateTime::currentMSecsSinceEpoch() + PING_TIMEOUT_MS; _timerConnectionCheck = startTimer(5000); // Connect the vnc start/stop signal to this class, so we can tell the server about successful vnc server startup - connect(VncServer::instance(), SIGNAL(started(int, QString&, QString&)), this, SLOT(onVncServerStartStop(int, QString&, QString&))); + connect(VncServer::instance(), &VncServer::started, this, &ServerConnection::onVncServerStartStop); } ServerConnection::~ServerConnection() @@ -112,7 +108,7 @@ void ServerConnection::handleMsg() emit stateChange(ConnectWindow::AwaitingChallengeResponse); _myChallenge.resize(CHALLENGE_LEN); for (int i = 0; i < CHALLENGE_LEN; ++i) { - _myChallenge[i] = char(qrand() & 0xff); + _myChallenge[i] = char(slxrand() & 0xff); } QByteArray serverChallenge(_fromServer.getFieldBytes(_CHALLENGE)); _toServer.reset(); @@ -320,7 +316,7 @@ void ServerConnection::timerEvent(QTimerEvent *event) * server was succesfully started, or was terminated (either planned or * crashed). */ -void ServerConnection::onVncServerStartStop(int port, QString& ropass, QString& rwpass) +void ServerConnection::onVncServerStartStop(int port, const QString &ropass, const QString &rwpass) { _toServer.reset(); _toServer.setField(_ID, _VNCSERVER); @@ -357,9 +353,8 @@ void ServerConnection::onVncViewerStartStop(const bool started, const int client void ServerConnection::sslErrors(const QList<QSslError> & errors) { _socket->ignoreSslErrors(); - for (QList<QSslError>::const_iterator it = errors.begin(); it != errors.end(); it++) { - const QSslError &err = *it; - qDebug("Connect SSL: %s", qPrintable(err.errorString())); + for (const auto &err : errors) { + qDebug("Connect SSL: %s", qPrintable(err.errorString())); if (err.error() == QSslError::HostNameMismatch) continue; // We don't pay attention to hostnames for validation if (err.error() == QSslError::SelfSignedCertificate) diff --git a/src/client/net/serverconnection.h b/src/client/net/serverconnection.h index f5f6264..f434f0b 100644 --- a/src/client/net/serverconnection.h +++ b/src/client/net/serverconnection.h @@ -33,18 +33,15 @@ private: void checkLocalConnection(); public: - ServerConnection(const QString& host, const quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect); + ServerConnection(const QString& host, quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect); void disconnectFromServer(); - ~ServerConnection(); + ~ServerConnection() override; inline bool isConnected() const { return _socket != nullptr && _socket->state() == QAbstractSocket::ConnectedState; } - const inline QString getPeerAdress() const - { - return _socket->peerAddress().toString(); - } + QString getPeerAdress() const { return _socket->peerAddress().toString(); } bool isLocalConnection() { if (_isLocalConnection == -1) { @@ -57,7 +54,7 @@ public: void sendAttention(bool on); protected: - void timerEvent(QTimerEvent *event); + void timerEvent(QTimerEvent *event) override; private slots: void sslErrors(const QList<QSslError> & errors); // triggered for errors that occur during SSL negotiation @@ -66,9 +63,10 @@ private slots: void sock_error(QAbstractSocket::SocketError errcode); // triggered if an error occurs on the socket void sock_connected(); // triggered if the connection is established and ready to use - void onVncServerStartStop(int port, QString& ropass, QString& rwpass); // triggered if the local vnc server was started + void onVncServerStartStop(int port, const QString &ropass, const QString &rwpass); // triggered if the local vnc server was started - void onVncViewerStartStop(const bool started, const int clientId); +public slots: + void onVncViewerStartStop(bool started, int clientId); signals: void openVnc(const QString& host, int port, const QString& passwd, bool ro, bool fullscreen, const QString& caption, const int clientId, const QByteArray& rawThumb); diff --git a/src/client/net/serverdiscovery.cpp b/src/client/net/serverdiscovery.cpp index b2d7605..efae165 100644 --- a/src/client/net/serverdiscovery.cpp +++ b/src/client/net/serverdiscovery.cpp @@ -4,8 +4,7 @@ #include "../../shared/network.h" #include "../../shared/util.h" #include "serverdiscovery.h" -#include <assert.h> - +#include "../util/util.h" /** * Ctor @@ -21,33 +20,31 @@ ServerDiscovery::ServerDiscovery(QObject *parent) /* Try to get a UDP port for server discovery */ int tries = 10; while (tries-- != 0) { - quint16 port = quint16(16384 + qrand() % 32768); + quint16 port = quint16(16384 + slxrand() % 32768); if (_discoverySocket.bind(QHostAddress::AnyIPv4, port)) break; if (tries == 0) qFatal("Could not bind to any UDP port for server discovery."); } // Handle incoming messages - connect(&_discoverySocket, SIGNAL(readyRead()), this, SLOT(onUdpReadyRead())); + connect(&_discoverySocket, &QUdpSocket::readyRead, this, &ServerDiscovery::onUdpReadyRead); /* Setup the discovery timer */ _discoveryTimer.setInterval(_minDiscoveryInterval); _discoveryTimer.setSingleShot(true); // - connect(&_discoveryTimer, SIGNAL(timeout()), this, SLOT(doDiscovery())); + connect(&_discoveryTimer, &QTimer::timeout, this, &ServerDiscovery::doDiscovery); } /** * Dtor */ -ServerDiscovery::~ServerDiscovery() -{ -} +ServerDiscovery::~ServerDiscovery() = default; /** * @brief start */ -void ServerDiscovery::start(const QByteArray& sessionName, QString mgrIP) +void ServerDiscovery::start(const QByteArray& sessionName, const QString& mgrIP) { if (!mgrIP.isEmpty()) { _mgrIP.setAddress(mgrIP); @@ -98,8 +95,8 @@ void ServerDiscovery::doDiscovery() if (_salt2.size() < SALT_LEN) _salt2.resize(SALT_LEN); for (int i = 0; i < SALT_LEN; ++i) { - salt1[i] = char(qrand() & 0xff); - _salt2[i] = char(qrand() & 0xff); + salt1[i] = char(slxrand() & 0xff); + _salt2[i] = char(slxrand() & 0xff); } _packet.reset(); _packet.setField(_HASH, genSha1(&_nameBytes, &salt1, &iplist)); @@ -141,7 +138,7 @@ void ServerDiscovery::onUdpReadyRead() { char data[UDPBUFSIZ]; QHostAddress addr; - quint16 port; + quint16 peerPort; while (_discoverySocket.hasPendingDatagrams()) { // Discard any packets if discovery is stopped if (!this->isActive()) { @@ -149,7 +146,7 @@ void ServerDiscovery::onUdpReadyRead() continue; } - const qint64 size = _discoverySocket.readDatagram(data, UDPBUFSIZ, &addr, &port); + const qint64 size = _discoverySocket.readDatagram(data, UDPBUFSIZ, &addr, &peerPort); if (size <= 0) //|| clientApp->connection() != nullptr) // TODO CHECK continue; diff --git a/src/client/net/serverdiscovery.h b/src/client/net/serverdiscovery.h index d7d6010..21f9bf9 100644 --- a/src/client/net/serverdiscovery.h +++ b/src/client/net/serverdiscovery.h @@ -17,10 +17,10 @@ public: InvalidHash }; - explicit ServerDiscovery(QObject *parent = 0); - ~ServerDiscovery(); + explicit ServerDiscovery(QObject *parent = nullptr); + ~ServerDiscovery() override; - void start(const QByteArray& sessionName, QString mgrIP); + void start(const QByteArray& sessionName, const QString& mgrIP); void stop(); inline bool isActive() { return _discoveryTimer.isActive(); } diff --git a/src/client/toolbar/toolbar.cpp b/src/client/toolbar/toolbar.cpp index 880e24f..bd5d689 100644 --- a/src/client/toolbar/toolbar.cpp +++ b/src/client/toolbar/toolbar.cpp @@ -2,7 +2,6 @@ #include "../net/serverconnection.h" #include "../vnc/vncwindow.h" #include "../vnc/vncserver.h" -#include "../util/util.h" #include "../informationdialog/informationdialog.h" #include "../clientapp/clientapp.h" #include "../addons/addons.h" @@ -10,9 +9,11 @@ #include "toolbar.h" #include "ui_toolbar.h" -#include <QtAlgorithms> #include <QNetworkInterface> -#include <QProcess> +#include <QScreen> +#include <QMenu> +#include <QMouseEvent> +#include <QMessageBox> /** * @brief @@ -24,8 +25,13 @@ * another widget, this widget becomes a child window inside parent. The new * widget is deleted when its parent is deleted. */ -Toolbar::Toolbar(const QByteArray sessionName, QWidget *parent) - : QWidget(parent), _showTimer(this), _hideTimer(this), _hideCountdown(10), _blinkTimer(this), _beWatchedEye(":eye") +Toolbar::Toolbar(const QByteArray& sessionName, QWidget *parent) + : QWidget(parent) + , _showTimer(this) + , _hideTimer(this) + , _hideCountdown(10) + , _blinkTimer(this) + , _beWatchedEye(":eye") { qDebug() << "sessionName - constructor"; init(); @@ -44,7 +50,12 @@ Toolbar::Toolbar(const QByteArray sessionName, QWidget *parent) * widget is deleted when its parent is deleted. */ Toolbar::Toolbar(const bool autoConnect, QWidget *parent) - : QWidget(parent), _showTimer(this), _hideTimer(this), _hideCountdown(10), _blinkTimer(this), _beWatchedEye(":eye") + : QWidget(parent) + , _showTimer(this) + , _hideTimer(this) + , _hideCountdown(10) + , _blinkTimer(this) + , _beWatchedEye(":eye") { qDebug() << "auto - constructor!"; init(); @@ -100,9 +111,9 @@ void Toolbar::init() /* Create the connect window */ clientApp->connectWindow()->setAvailableRooms(myRooms()); // Connect the signals - connect(clientApp->connectWindow(), SIGNAL(disconnect()), this, SLOT(onDoDisconnect())); - connect(clientApp->connectWindow(), SIGNAL(connected(ServerConnection*)), this, SLOT(onConnected(ServerConnection*))); - connect(_ui->btnAttention, SIGNAL(toggled(bool)), this, SLOT(onBtnAttention())); + connect(clientApp->connectWindow(), &ConnectWindow::disconnect, this, &Toolbar::onDoDisconnect); + connect(clientApp->connectWindow(), &ConnectWindow::connected, this, &Toolbar::onConnected); + connect(_ui->btnAttention, &QToolButton::toggled, this, &Toolbar::onBtnAttention); /* Setup menu */ initButtonsAndMenus(); @@ -112,7 +123,7 @@ void Toolbar::init() _ui->btnAttention->setMaximumWidth(30); /* Connect the signals from vnc server */ - connect(VncServer::instance(), SIGNAL(started(int, QString&, QString&)), this, SLOT(onVncServerIsRunning(int))); + connect(VncServer::instance(), &VncServer::started, this, &Toolbar::onVncServerIsRunning); /* React to screen geometry change */ connect(QGuiApplication::primaryScreen(), &QScreen::availableGeometryChanged, this, &Toolbar::setToolbarPosition); @@ -124,10 +135,10 @@ void Toolbar::init() /* Setup show & hide timer */ _showTimer.setInterval(500); _showTimer.setSingleShot(true); - connect(&_showTimer, SIGNAL(timeout()), this, SLOT(showBar())); + connect(&_showTimer, &QTimer::timeout, this, &Toolbar::showBar); _hideTimer.setInterval(50); _hideTimer.setSingleShot(false); - connect(&_hideTimer, SIGNAL(timeout()), this, SLOT(hideBar())); + connect(&_hideTimer, &QTimer::timeout, this, &Toolbar::hideBar); setVisible(true); raise(); @@ -135,11 +146,11 @@ void Toolbar::init() /* Setup blink timer */ _blinkTimer.setInterval(500); - connect(&_blinkTimer, SIGNAL(timeout()), this, SLOT(cameraBlink())); + connect(&_blinkTimer, &QTimer::timeout, this, &Toolbar::cameraBlink); } static QFrame* makeVerticalLine() { - QFrame *f = new QFrame(); + auto *f = new QFrame(); f->setFrameShape(QFrame::HLine); f->setFrameShadow(QFrame::Sunken); return f; @@ -191,12 +202,12 @@ void Toolbar::initButtonsAndMenus() _acnQuit->setVisible(allow); // Connect the signals - connect(_menu, SIGNAL(aboutToHide()), this, SLOT(delayedHideBar())); - connect(_acnConnect, SIGNAL(triggered()), clientApp->connectWindow(), SLOT(doShow())); - connect(_acnDisconnect, SIGNAL(triggered()), clientApp->connectWindow(), SLOT(DoDisconnect())); - connect(_acnInformation, SIGNAL(triggered()), this, SLOT(showInformationDialog())); - connect(_acnAbout, SIGNAL(triggered()), this, SLOT(showAboutDialog())); - connect(_acnQuit, SIGNAL(triggered()), this, SLOT(exit())); + connect(_menu, &QMenu::aboutToHide, this, &Toolbar::delayedHideBar); + connect(_acnConnect, &QAction::triggered, clientApp->connectWindow(), &ConnectWindow::doShow); + connect(_acnDisconnect, &QAction::triggered, clientApp->connectWindow(), &ConnectWindow::DoDisconnect); + connect(_acnInformation, &QAction::triggered, this, &Toolbar::showInformationDialog); + connect(_acnAbout, &QAction::triggered, this, &Toolbar::showAboutDialog); + connect(_acnQuit, &QAction::triggered, this, &Toolbar::exit); // Delay until bar is visible QTimer::singleShot(10, [=]() { @@ -363,7 +374,7 @@ void Toolbar::onVncServerIsRunning(int port) void Toolbar::onDisconnected(ServerConnection* connection) { if (connection != nullptr) { - disconnect(connection, SIGNAL(disconnected(ServerConnection*)), this, SLOT(onDisconnected(ServerConnection*))); + disconnect(connection, &ServerConnection::disconnected, this, &Toolbar::onDisconnected); } _ui->lblStatus->setStyleSheet("color:red"); _ui->lblStatus->setText(tr("Offline")); @@ -394,12 +405,12 @@ void Toolbar::onConnected(ServerConnection* connection) _ui->btnAttention->setVisible(true); AddonManager::connectEvent(connection->isLocalConnection(), connection->getPeerAdress()); // - connect(connection, SIGNAL(disconnected(ServerConnection*)), this, SLOT(onDisconnected(ServerConnection*))); - connect(connection, SIGNAL(openVnc(const QString&, int, const QString&, bool, bool, const QString&, const int, const QByteArray&)), - _vnc, SLOT(open(const QString&, int, const QString&, bool, bool, const QString&, const int, const QByteArray&))); - connect(connection, SIGNAL(closeVnc()), _vnc, SLOT(close())); - connect(connection, SIGNAL(attentionChanged(const bool)), this, SLOT(onServerAttentionChanged(const bool))); - connect(_vnc, SIGNAL(running(const bool, const int)), connection, SLOT(onVncViewerStartStop(const bool, const int))); + connect(connection, &ServerConnection::disconnected, this, &Toolbar::onDisconnected); + connect(connection, &ServerConnection::openVnc, + _vnc, &VncWindow::open); + connect(connection, &ServerConnection::closeVnc, _vnc, &VncWindow::close); + connect(connection, &ServerConnection::attentionChanged, this, &Toolbar::onServerAttentionChanged); + connect(_vnc, &VncWindow::running, connection, &ServerConnection::onVncViewerStartStop); } /** @@ -489,7 +500,7 @@ void Toolbar::showAboutDialog() void Toolbar::showInformationDialog() { - InformationDialog* d = new InformationDialog(); + auto* d = new InformationDialog(); d->exec(); d->deleteLater(); } diff --git a/src/client/toolbar/toolbar.h b/src/client/toolbar/toolbar.h index 48fbf03..702bae2 100644 --- a/src/client/toolbar/toolbar.h +++ b/src/client/toolbar/toolbar.h @@ -14,13 +14,15 @@ #ifndef PVSCLIENTGUI_H_ #define PVSCLIENTGUI_H_ -#include <QtWidgets> +#include <QWidget> +#include <QTimer> #include "../util/room.h" class ServerConnection; class VncWindow; class BlankScreen; +class QMenu; namespace Ui { @@ -32,47 +34,43 @@ class Toolbar : public QWidget Q_OBJECT public: - Toolbar(QWidget *parent = 0); - Toolbar(const QByteArray sessionName, QWidget *parent = 0); - Toolbar(const bool autoConnect, QWidget *parent = 0); - virtual ~Toolbar(); + explicit Toolbar(QWidget *parent = nullptr); + explicit Toolbar(const QByteArray& sessionName, QWidget *parent = nullptr); + explicit Toolbar(bool autoConnect, QWidget *parent = nullptr); + ~Toolbar() override; private: - Ui::Toolbar *_ui; - QMenu *_menu; - QAction *_acnDisconnect; - QAction *_acnConnect; - QAction *_acnInformation; - QAction *_acnAbout; - QAction *_acnQuit; + Ui::Toolbar *_ui{}; + QMenu *_menu{}; + QAction *_acnDisconnect{}; + QAction *_acnConnect{}; + QAction *_acnInformation{}; + QAction *_acnAbout{}; + QAction *_acnQuit{}; QTimer _showTimer; QTimer _hideTimer; int _hideCountdown; QTimer _blinkTimer; - VncWindow *_vnc; - bool _isManagerPc; + VncWindow *_vnc{}; const QPixmap _cam32, _beWatchedEye; QPoint _lastDragPos; - int _yPos; - int _yPosHidden; + int _yPos{}; + int _yPosHidden{}; void enterEvent(QEvent* e) override; void mousePressEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; - QList<Room> myRooms(); - bool isManagerPc(); - QString identifyMgrIP(); + static QList<Room> myRooms(); + static QString identifyMgrIP(); void init(); void initButtonsAndMenus(); - QProcess lockDesktopP; - private slots: void onVncServerIsRunning(int port); void onDisconnected(ServerConnection* connection); void onConnected(ServerConnection* connection); - void onServerAttentionChanged(const bool on); + void onServerAttentionChanged(bool on); void onDoDisconnect(); void onBtnAttention(); void exit(); diff --git a/src/client/util/platform/blankscreen.cpp b/src/client/util/platform/blankscreen.cpp index 5f9b04b..a4c7d30 100644 --- a/src/client/util/platform/blankscreen.cpp +++ b/src/client/util/platform/blankscreen.cpp @@ -7,10 +7,6 @@ #include <QTimer> #include <X11/Xlib.h> -#include <X11/cursorfont.h> - -#include <cassert> -#include <cstring> struct BlankScreen_Sysdep { Display *dpy; @@ -27,8 +23,8 @@ BlankScreen::BlankScreen() : QDialog(nullptr) setStyleSheet("background-color:#000"); _locked = false; - QTimer *upper = new QTimer(this); - connect(upper, SIGNAL(timeout()), this, SLOT(timer_moveToTop())); + auto *upper = new QTimer(this); + connect(upper, &QTimer::timeout, this, &BlankScreen::timer_moveToTop); upper->start(1111); } diff --git a/src/client/util/room.h b/src/client/util/room.h index 86939f7..46f8c02 100644 --- a/src/client/util/room.h +++ b/src/client/util/room.h @@ -1,11 +1,13 @@ #ifndef ROOM_H #define ROOM_H +#include <QDebug> + struct Room { QString mgr; QString name; int priority; - Room (QString _name, QString _mgr, int _priority) + Room (const QString &_name, const QString &_mgr, int _priority) { mgr = _mgr; name = _name; @@ -13,7 +15,7 @@ struct Room { }; }; -inline QDebug operator<<(QDebug debug, const Room& r) +inline QDebug& operator<<(QDebug& debug, const Room& r) { debug << r.name << "{mgr=" << r.mgr << ",prio=" << r.priority << "}"; return debug; diff --git a/src/client/util/util.h b/src/client/util/util.h index 89b19f4..e7a5ac9 100644 --- a/src/client/util/util.h +++ b/src/client/util/util.h @@ -1,10 +1,9 @@ -#ifndef UTIL_H_ -#define UTIL_H_ +#ifndef PVS_UTIL_H_ +#define PVS_UTIL_H_ #include <QDir> #include <QTextStream> - namespace Util { //# @@ -22,4 +21,4 @@ inline QTextStream& qStdout() } -#endif /* UTIL_H_ */ +#endif /* PVS_UTIL_H_ */ diff --git a/src/client/vnc/vncserver.cpp b/src/client/vnc/vncserver.cpp index d819668..4c2363e 100644 --- a/src/client/vnc/vncserver.cpp +++ b/src/client/vnc/vncserver.cpp @@ -6,11 +6,12 @@ */ -#include <QApplication> +#include <QGuiApplication> #include <QProcess> -#include <QDesktopWidget> +#include <QScreen> #include "vncserver.h" #include "../util/util.h" +#include "../../shared/util.h" VncServer* VncServer::me = nullptr; @@ -34,7 +35,7 @@ static QString makePassword(int len = 10) { QString ret(len, Qt::Uninitialized); for (int i = 0; i < len; ++i) - ret[i] = QChar(43 + qrand() % 80); + ret[i] = QChar(43 + slxrand() % 80); return ret; } @@ -53,7 +54,7 @@ VncServer::VncServer() : _process(nullptr), _port(0), _timerId(0) {} /** * @brief VncServer::~VncServer */ -VncServer::~VncServer() {} +VncServer::~VncServer() = default; QSharedPointer<QFile> VncServer::createPwFile(const QDir& dir) { @@ -74,8 +75,8 @@ void VncServer::start() { // Keep things clean if (_process != nullptr) { - disconnect(_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onError(QProcess::ProcessError))); - disconnect(_process, SIGNAL(finished(int)), this, SLOT(onFinished(int))); + _process->blockSignals(true); + _process->kill(); } this->stop(); // Generate passwords @@ -99,22 +100,22 @@ void VncServer::start() pwhandle->close(); // Create new process _process = new QProcess(this); - connect(_process, SIGNAL(readyReadStandardOutput()), this, SLOT(onStdOut())); - connect(_process, SIGNAL(readyReadStandardError()), this, SLOT(onStdErr())); - connect(_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onError(QProcess::ProcessError))); - connect(_process, SIGNAL(finished(int)), this, SLOT(onFinished(int))); + connect(_process, &QProcess::readyReadStandardOutput, this, &VncServer::onStdOut); + connect(_process, &QProcess::readyReadStandardError, this, &VncServer::onStdErr); + connect(_process, &QProcess::errorOccurred, this, &VncServer::onError); + connect(_process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), + this, &VncServer::onFinished); _timerId = startTimer(4000); QStringList args; args << "-forever"; args << "-display" << ":0"; - args << "-passwdfile" << (QString("rm:" + pwhandle->fileName())); + args << "-passwdfile" << (QStringLiteral("rm:") + pwhandle->fileName()); args << "-shared"; args << "-repeat"; args << "-autoport" << QString::number(54112); // Get rect of primary screen - const QDesktopWidget desktop; - const QRect primaryRect = desktop.screenGeometry(); + const QRect primaryRect = QGuiApplication::primaryScreen()->geometry(); // Tell x11vnc to just use primary screen args << "-clip"; @@ -141,8 +142,8 @@ void VncServer::stop() if (_process == nullptr) return; qDebug("Stopping old VNC server."); - disconnect(_process, SIGNAL(readyReadStandardOutput()), this, SLOT(onStdOut())); - disconnect(_process, SIGNAL(readyReadStandardError()), this, SLOT(onStdErr())); + disconnect(_process, &QProcess::readyReadStandardOutput, this, &VncServer::onStdOut); + disconnect(_process, &QProcess::readyReadStandardError, this, &VncServer::onStdErr); QProcess *process = _process; _process = nullptr; _port = 0; @@ -215,7 +216,7 @@ void VncServer::onStdErr() qDebug("VncServer::onStdErr() called in bad state."); return; } - QByteArray data(_process->readAllStandardError()); + _process->readAllStandardError(); // Throw away } /** @@ -232,7 +233,7 @@ void VncServer::onError(QProcess::ProcessError /* error */ ) * @brief VncServer::onFinished * @param exitCode */ -void VncServer::onFinished(int /* exitCode */ ) +void VncServer::onFinished(int /* exitCode */, QProcess::ExitStatus /* exitStatus */) { this->stop(); emit started(0, _ropass, _rwpass); diff --git a/src/client/vnc/vncserver.h b/src/client/vnc/vncserver.h index 4974946..1e71e2e 100644 --- a/src/client/vnc/vncserver.h +++ b/src/client/vnc/vncserver.h @@ -25,29 +25,29 @@ private: int _timerId; VncServer(); - virtual ~VncServer(); - QSharedPointer<QFile> createPwFile(const QDir& dir); + ~VncServer() override; + static QSharedPointer<QFile> createPwFile(const QDir& dir); static VncServer *me; public: static VncServer *instance(); - inline bool isVncServerRunning() { return _port > 0; } + inline bool isVncServerRunning() const { return _port > 0; } void start(); void stop(); protected: - void timerEvent(QTimerEvent *event); + void timerEvent(QTimerEvent *event) override; signals: // Emited when started succesfully, or if startup failed. port will be <= 0 if it failed. - void started(int port, QString& ropass, QString& rwpass); + void started(int port, const QString& ropass, const QString& rwpass); private slots: void onStdOut(); void onStdErr(); - void onFinished(int exitCode); + void onFinished(int exitCode, QProcess::ExitStatus exitStatus); void onError(QProcess::ProcessError error); }; diff --git a/src/client/vnc/vncthread.cpp b/src/client/vnc/vncthread.cpp index 1a903d5..0e98cfe 100644 --- a/src/client/vnc/vncthread.cpp +++ b/src/client/vnc/vncthread.cpp @@ -17,8 +17,10 @@ */ #include "vncthread.h" -#include <QPainter> +#include "../../shared/util.h" +#include <QPainter> +#include <utility> #include <netinet/tcp.h> /** @@ -29,15 +31,15 @@ * @param passwd The password of the VNC server * @param quality The desired quality level for the VNC stream */ -VncThread::VncThread(QString host, int port, QString passwd, int quality) : - QThread(), _run(true), _started(false) +VncThread::VncThread(QString host, int port, QString passwd, int quality) + : QThread() + , _host(std::move(host)) + , _port(port) + , _passwd(std::move(passwd)) + , _quality(quality) + , _run(true) + , _started(false) { - _host = host; - _port = port; - _passwd = passwd; - _quality = quality; - _client = nullptr; - _connected = false; moveToThread(this); } @@ -74,7 +76,7 @@ void VncThread::run() // setup network for (int retry = 0; retry < 5 && _run; ++retry) { - this->msleep(1 + qrand() % 60); + msleep(1 + slxrand() % 60); if (!_run) break; _client = rfbGetClient(8, 3, 4); @@ -100,7 +102,7 @@ void VncThread::run() if (!_run) break; // error, let's try again - this->msleep(10 + qrand() % 50); + msleep(10 + slxrand() % 50); } if (_client != nullptr) { qDebug("[%s] Connection successful!", metaObject()->className()); @@ -125,7 +127,7 @@ void VncThread::run() _connected = false; emit projectionStopped(); while (_run) - this->msleep(100); + msleep(100); qDebug("[%s] VNC client stopped.", metaObject()->className()); } @@ -134,10 +136,10 @@ void VncThread::run() * * @return Name of the remote desktop */ -const QString VncThread::getDesktopName() const +QString VncThread::getDesktopName() const { if (_client == nullptr || _client->desktopName == nullptr) - return QString(); + return {}; return QString(_client->desktopName); } @@ -172,7 +174,7 @@ void VncThread::emitStarted() */ char* VncThread::passwdHandler(rfbClient *client) { - VncThread* t = reinterpret_cast<VncThread*>(rfbClientGetClientData(client, nullptr)); + auto* t = reinterpret_cast<VncThread*>(rfbClientGetClientData(client, nullptr)); return strdup(t->_passwd.toUtf8()); } @@ -185,7 +187,7 @@ char* VncThread::passwdHandler(rfbClient *client) */ rfbBool VncThread::frameBufferHandler(rfbClient *client) { - VncThread *t = reinterpret_cast<VncThread*>(rfbClientGetClientData(client, nullptr)); + auto *t = reinterpret_cast<VncThread*>(rfbClientGetClientData(client, nullptr)); const int width = client->width, height = client->height, depth = 32; const int size = width * height * (depth / 8); qDebug("[%s] Remote desktop: %ix%ix%i", t->metaObject()->className(), width, height, depth); @@ -196,8 +198,8 @@ rfbBool VncThread::frameBufferHandler(rfbClient *client) } t->_img = QSharedPointer<QImage>(new QImage(width, height, QImage::Format_RGB32)); - if (size > t->_img->byteCount()) { - qDebug() << "Fatal: Created image too small:" << t->_img->byteCount() << "<" << size; + if (size > t->_img->sizeInBytes()) { + qDebug() << "Fatal: Created image too small:" << t->_img->sizeInBytes() << "<" << size; ::exit(1); } client->frameBuffer = t->_img->bits(); @@ -260,6 +262,6 @@ rfbBool VncThread::frameBufferHandler(rfbClient *client) */ void VncThread::updateImage(rfbClient* client, int x, int y, int w, int h) { - VncThread* t = (VncThread*)rfbClientGetClientData(client, 0); + auto* t = (VncThread*)rfbClientGetClientData(client, 0); t->processImageUpdate(x, y, w, h); } diff --git a/src/client/vnc/vncthread.h b/src/client/vnc/vncthread.h index 16491fe..f7a020b 100644 --- a/src/client/vnc/vncthread.h +++ b/src/client/vnc/vncthread.h @@ -38,7 +38,7 @@ class VncThread : public QThread Q_OBJECT private: - rfbClient *_client; + rfbClient *_client{}; QString _host; int _port; @@ -47,7 +47,7 @@ private: QSharedPointer<QImage> _img; - volatile bool _connected; + volatile bool _connected{}; volatile bool _run; bool _started; @@ -63,13 +63,13 @@ private: public: VncThread(QString host, int port, QString passwd, int quality); - ~VncThread(); + ~VncThread() override; - const QString getDesktopName() const; - bool isConnected() { return _connected; } + QString getDesktopName() const; + bool isConnected() const { return _connected; } void stop() { _run = false; } const QSharedPointer<QImage>& getFrameBuffer() { return _img; } - void run(); + void run() override; int const static HIGH = 0; int const static MEDIUM = 1; diff --git a/src/client/vnc/vncwindow.cpp b/src/client/vnc/vncwindow.cpp index f7b6a3e..0947112 100644 --- a/src/client/vnc/vncwindow.cpp +++ b/src/client/vnc/vncwindow.cpp @@ -19,7 +19,11 @@ #include "vncthread.h" #include "../clientapp/clientapp.h" +#include <QGuiApplication> #include <QTimer> +#include <QPainter> +#include <QScreen> +#include <QKeyEvent> /** * Calc greatest common divisor. @@ -39,15 +43,12 @@ VncWindow::VncWindow(QWidget *parent) : QWidget(parent), _srcStepX(1), _srcStepY(1), _dstStepX(1), _dstStepY(1), _vncWorker(nullptr), _viewOnly(true), _multiScreen(false), _clientId(0), _redrawTimer(0), _tcpTimeoutTimer(0) { - QTimer *upper = new QTimer(this); - connect(upper, SIGNAL(timeout()), this, SLOT(timer_moveToTop())); + auto *upper = new QTimer(this); + connect(upper, &QTimer::timeout, this, &VncWindow::timer_moveToTop); upper->start(1111); } -VncWindow::~VncWindow() -{ - // -} +VncWindow::~VncWindow() = default; //////////////////////////////////////////////////////////////////////////////// // Private @@ -64,10 +65,9 @@ void VncWindow::terminateVncThread() if (_vncWorker == nullptr) return; - disconnect(_vncWorker, SIGNAL(projectionStopped()), this, SLOT(onProjectionStopped())); - disconnect(_vncWorker, SIGNAL(projectionStarted()), this, SLOT(onProjectionStarted())); - disconnect(_vncWorker, SIGNAL(imageUpdated(const int, const int, const int, const int)), this, - SLOT(onUpdateImage(const int, const int, const int, const int))); + disconnect(_vncWorker, &VncThread::projectionStopped, this, &VncWindow::onProjectionStopped); + disconnect(_vncWorker, &VncThread::projectionStarted, this, &VncWindow::onProjectionStarted); + disconnect(_vncWorker, &VncThread::imageUpdated, this, &VncWindow::onUpdateImage); _vncWorker->stop(); _vncWorker = nullptr; if (_redrawTimer != 0) { @@ -188,12 +188,10 @@ void VncWindow::open(const QString& host, int port, const QString& passwd, bool this->terminateVncThread(); _clientId = clientId; _vncWorker = new VncThread(host, port, passwd, 1); - connect(_vncWorker, SIGNAL(projectionStopped()), this, SLOT(onProjectionStopped()), Qt::QueuedConnection); - connect(_vncWorker, SIGNAL(projectionStarted()), this, SLOT(onProjectionStarted()), Qt::QueuedConnection); - connect(_vncWorker, SIGNAL(imageUpdated(const int, const int, const int, const int)), this, - SLOT(onUpdateImage(const int, const int, const int, const int)), - Qt::QueuedConnection); - connect(_vncWorker, SIGNAL(finished()), this, SLOT(deleteVncThread()), Qt::QueuedConnection); + connect(_vncWorker, &VncThread::projectionStopped, this, &VncWindow::onProjectionStopped, Qt::QueuedConnection); + connect(_vncWorker, &VncThread::projectionStarted, this, &VncWindow::onProjectionStarted, Qt::QueuedConnection); + connect(_vncWorker, &VncThread::imageUpdated, this, &VncWindow::onUpdateImage, Qt::QueuedConnection); + connect(_vncWorker, &VncThread::finished, this, &VncWindow::deleteVncThread, Qt::QueuedConnection); setWindowTitle(caption); @@ -201,22 +199,18 @@ void VncWindow::open(const QString& host, int port, const QString& passwd, bool _remoteThumb.loadFromData(rawThumb); - QSize size; if (fullscreen) { setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Tool); // | Qt::X11BypassWindowManagerHint); <- better, but window won't get any keyboard input // Show projection on rightmost screen - QDesktopWidget *desktop = QApplication::desktop(); - int ns = desktop->numScreens(); QRect best; - for (int i = 0; i < ns; ++i) { - QRect r = desktop->screenGeometry(i); + for (auto *screen : QGuiApplication::screens()) { + QRect r = screen->geometry(); if (best.isNull() || r.left() > best.left()) { best = r; } } - _multiScreen = ns > 1; - qDebug() << "Spawning at" << best; - size = best.size(); + _multiScreen = QGuiApplication::screens().size() > 1; + qDebug() << "Spawning VNC viewer at" << best; show(); setGeometry(best); raise(); @@ -226,8 +220,7 @@ void VncWindow::open(const QString& host, int port, const QString& passwd, bool move(best.topLeft()); } else { setWindowFlags(Qt::Tool | Qt::WindowMaximizeButtonHint); - size = QSize(800, 600); - resize(size); + resize(800, 600); showNormal(); } diff --git a/src/client/vnc/vncwindow.h b/src/client/vnc/vncwindow.h index 7124ddc..0e50ff9 100644 --- a/src/client/vnc/vncwindow.h +++ b/src/client/vnc/vncwindow.h @@ -14,12 +14,13 @@ #ifndef CLIENTVNCVIEWER_H_ #define CLIENTVNCVIEWER_H_ -#include <QtWidgets> #include <QSharedPointer> -#include <QImage> +#include <QWidget> +#include <QPixmap> class VncThread; class QPainter; +class QImage; class VncWindow : public QWidget { @@ -36,8 +37,8 @@ protected slots: void timer_moveToTop(); void deleteVncThread(); +public slots: void open(const QString& host, int port, const QString& passwd, bool ro, bool fullscreen, const QString& caption, const int clientId, const QByteArray& rawThumb); -// bool close(); signals: void running(const bool isRunning, const int clientId); |