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/server | |
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/server')
25 files changed, 452 insertions, 533 deletions
diff --git a/src/server/clicklabel/clicklabel.h b/src/server/clicklabel/clicklabel.h index 4c5a898..cea024d 100644 --- a/src/server/clicklabel/clicklabel.h +++ b/src/server/clicklabel/clicklabel.h @@ -1,7 +1,6 @@ -#ifndef _CLICKLABEL_H_ -#define _CLICKLABEL_H_ +#ifndef PVS_CLICKLABEL_H_ +#define PVS_CLICKLABEL_H_ -#include <QtWidgets> #include <QLabel> /** @@ -12,10 +11,10 @@ class ClickLabel : public QLabel Q_OBJECT public: - ClickLabel(QWidget *parent); + explicit ClickLabel(QWidget *parent); protected: - void mouseReleaseEvent(QMouseEvent* e); + void mouseReleaseEvent(QMouseEvent* e) override; signals: diff --git a/src/server/connectionframe/connectionframe.cpp b/src/server/connectionframe/connectionframe.cpp index c2bba70..c6c20b8 100644 --- a/src/server/connectionframe/connectionframe.cpp +++ b/src/server/connectionframe/connectionframe.cpp @@ -16,46 +16,51 @@ #include "connectionframe.h" #include "../mainwindow/mainwindow.h" +#include "../../shared/util.h" #include "../net/client.h" -#include <QImage> -#include <cassert> -#include <cmath> -static QString style_student( - "QLabel{ background-color: #FFF; border-radius: 2px; color: black;} \ - QGroupBox { background-color: #AAA; margin: 2px; border-radius: 4px}" +#include <QImage> +#include <QResizeEvent> +#include <QBoxLayout> +#include <QLabel> +#include <QApplication> +#include <QPainter> + +static const QString style_student( + "QLabel{ background-color: #FFF; border-radius: 2px; color: black;}" + " QGroupBox { background-color: #AAA; margin: 2px; border-radius: 4px}" ); -static QString style_tutor( - "QLabel{ background-color: #FFF; border-radius: 2px; color: black;} \ - QGroupBox { background-color: #70C670; margin: 2px; border-radius: 4px}" +static const QString style_tutor( + "QLabel{ background-color: #FFF; border-radius: 2px; color: black;}" + " QGroupBox { background-color: #70C670; margin: 2px; border-radius: 4px}" ); -static QString style_attention( - "QLabel{ background-color: #FFF; border-radius: 2px; color: black;} \ - QGroupBox { background-color: #C88; margin: 2px; border-radius: 4px}" +static const QString style_attention( + "QLabel{ background-color: #FFF; border-radius: 2px; color: black;}" + " QGroupBox { background-color: #C88; margin: 2px; border-radius: 4px}" ); -static QString style_selectedStudent( - "QLabel{ background-color: #FFF; border-radius: 2px; color: black; } \ - QGroupBox { background-color: #ccebff; margin: 0px; border-radius: 4px; border: 4px solid #6C8CF0;}" +static const QString style_selectedStudent( + "QLabel{ background-color: #FFF; border-radius: 2px; color: black; }" + " QGroupBox { background-color: #ccebff; margin: 0px; border-radius: 4px; border: 4px solid #6C8CF0;}" ); -static QString style_selectedTutor( - "QLabel{ background-color: #FFF; border-radius: 2px; color: black;} \ - QGroupBox { background-color: #9f9; margin: 0px; border-radius: 4px; border: 4px solid #6C8CF0;}" +static const QString style_selectedTutor( + "QLabel{ background-color: #FFF; border-radius: 2px; color: black;}" + " QGroupBox { background-color: #9f9; margin: 0px; border-radius: 4px; border: 4px solid #6C8CF0;}" ); -static QString style_selectedAttention( - "QLabel{ background-color: #FFF; border-radius: 2px; color: black;} \ - QGroupBox { background-color: #E99; margin: 0px; border-radius: 4px; border: 4px solid #6C8CF0;}" +static const QString style_selectedAttention( + "QLabel{ background-color: #FFF; border-radius: 2px; color: black;}" + " QGroupBox { background-color: #E99; margin: 0px; border-radius: 4px; border: 4px solid #6C8CF0;}" ); -static QString style_exam ( - "QLabel{ background-color: #919191; color: black; } \ - QGroupBox { background-color: #d35400; margin: 1px; border-radius: 4px}" +static const QString style_exam ( + "QLabel{ background-color: #919191; color: black; }" + " QGroupBox { background-color: #d35400; margin: 1px; border-radius: 4px}" ); -static QString style_exam_selected ( - "QLabel{ background-color: #919191; color: black; } \ - QGroupBox { background-color: #cc743a; margin: 1px; border-radius: 4px}" +static const QString style_exam_selected ( + "QLabel{ background-color: #919191; color: black; }" + " QGroupBox { background-color: #cc743a; margin: 1px; border-radius: 4px}" ); -static QString style_disconnected( - "QLabel{ background-color: #919191; border-radius: 2px; color: black; } \ - QGroupBox { background-color: #7F7F7F; margin: 1px; border-radius: 4px}" +static const QString style_disconnected( + "QLabel{ background-color: #919191; border-radius: 2px; color: black; }" + " QGroupBox { background-color: #7F7F7F; margin: 1px; border-radius: 4px}" ); static QIcon *term = nullptr, *cam = nullptr, *eye = nullptr, *lock = nullptr; @@ -70,9 +75,10 @@ bool ConnectionFrame::paintDisabled = false; * @param width * @param height */ -ConnectionFrame::ConnectionFrame(MainWindow* main, QWidget *parent, bool fromRoomplan) : - QGroupBox(parent), _client(nullptr), _timerId(0), _timerCounter(0), _isSelected(false), _isTutor(false), - _isFromRoomplan(fromRoomplan), _mainWindow(main) +ConnectionFrame::ConnectionFrame(MainWindow* main, QWidget *parent, bool fromRoomplan) + : QGroupBox(parent) + , _isFromRoomplan(fromRoomplan) + , _mainWindow(main) { //defines the ui-stuff @@ -158,7 +164,7 @@ void ConnectionFrame::updateGeometry() */ QLabel* ConnectionFrame::addIcon(const QIcon* icon) { - QLabel *label = new QLabel(this); + auto *label = new QLabel(this); label->setPixmap(icon->pixmap(24, 24, QIcon::Normal, QIcon::On)); label->setAttribute(Qt::WA_TranslucentBackground); label->hide(); @@ -174,17 +180,17 @@ QLabel* ConnectionFrame::addIcon(const QIcon* icon) void ConnectionFrame::assignClient(Client* client) { assert(_client == nullptr); - connect( client, SIGNAL(disconnected()), this, SLOT(onClientDisconnected()) ); - connect( client, SIGNAL(thumbUpdated(Client*, const QImage&)), this, SLOT(onThumbUpdated(Client*, const QImage&)) ); - connect( client, SIGNAL(vncServerStateChange(Client*)), this, SLOT(updateAppearance())); - connect( client, SIGNAL(vncClientStateChange(Client*)), this, SLOT(updateAppearance())); - connect( client, SIGNAL(stateChanged()), this, SLOT(updateAppearance())); _client = client; + connect(_client, &Client::disconnected, this, &ConnectionFrame::onClientDisconnected ); + connect(_client, &Client::thumbUpdated, this, &ConnectionFrame::onThumbUpdated ); + connect(_client, &Client::vncServerStateChange, this, &ConnectionFrame::updateAppearance); + connect(_client, &Client::vncClientStateChange, this, &ConnectionFrame::updateAppearance); + connect(_client, &Client::stateChanged, this, &ConnectionFrame::updateAppearance); _computerId = client->ip(); updateLabels(); showDefaultThumb(); if (_timerId == 0) - _timerId = startTimer(1000 + qrand() % 150); + _timerId = startTimer(slxrand() % 150 + 1000); this->updateAppearance(); _client->setTutor(_isTutor); } @@ -382,8 +388,8 @@ void ConnectionFrame::updateAppearance() } else { this->setStyleSheet(style_disconnected); } - for (QList<QLabel*>::iterator it(_icons.begin()); it != _icons.end(); ++it) { - (**it).hide(); + for (auto *_icon : _icons) { + _icon->hide(); } return; } @@ -448,3 +454,8 @@ void ConnectionFrame::onThumbUpdated(Client* client, const QImage& thumb) this->update(); } +void ConnectionFrame::resizeEvent(QResizeEvent *event) { + calcDesiredThumbSize(event->size()); + QGroupBox::resizeEvent(event); +} + diff --git a/src/server/connectionframe/connectionframe.h b/src/server/connectionframe/connectionframe.h index 1d004e6..cfebe85 100644 --- a/src/server/connectionframe/connectionframe.h +++ b/src/server/connectionframe/connectionframe.h @@ -1,9 +1,14 @@ -#ifndef _CONNECTIONFRAME_H_ -#define _CONNECTIONFRAME_H_ -#include <QtWidgets> -#include "../net/client.h" +#ifndef PVS_CONNECTIONFRAME_H_ +#define PVS_CONNECTIONFRAME_H_ + +#include <QGroupBox> +#include <utility> + +class QBoxLayout; +class QLabel; class MainWindow; +class Client; /** * Class for representing the clients of current session, with a specific frame @@ -34,11 +39,11 @@ private: QPoint _gridPosition; QSize _desiredThumbSize; - Client *_client; + Client *_client{}; - int _timerId, _timerCounter; - bool _isSelected; - bool _isTutor; + int _timerId{}, _timerCounter{}; + bool _isSelected{}; + bool _isTutor{}; bool _isFromRoomplan; void showDefaultThumb(); @@ -52,35 +57,39 @@ public: static bool paintDisabled; ConnectionFrame(MainWindow* main, QWidget* parent, bool fromRoomplan = false); - virtual ~ConnectionFrame(); + ~ConnectionFrame() override; - const inline QPoint getGridPosition() const { return _gridPosition; } + const QPoint& getGridPosition() const { return _gridPosition; } void setGridPosition(int x, int y); void setGridPosition(const QPoint& pos); void updateGeometry(); void assignClient(Client *client); void setSelection(bool selected); - inline bool isSelected() { return _isSelected; } + bool isSelected() const { return _isSelected; } const QString& computerId() const { return _computerId; } - void setComputerId(QString computerId) { if (_client != nullptr) return; _computerId = computerId; updateLabels(); } + void setComputerId(QString computerId) { + if (_client != nullptr) + return; + _computerId = std::move(computerId); updateLabels(); + } Client* client() const { return _client; } - inline bool isTutor() { return _isTutor; } - inline bool isFromRoomplan() { return _isFromRoomplan; } + bool isTutor() const { return _isTutor; } + bool isFromRoomplan() const { return _isFromRoomplan; } void setTutor(bool b); protected: - void resizeEvent(QResizeEvent* event) { calcDesiredThumbSize(event->size()); } - void mouseDoubleClickEvent(QMouseEvent* event); - void mouseReleaseEvent(QMouseEvent* e); - void enterEvent(QEvent* event); - void leaveEvent(QEvent* event); - void mousePressEvent(QMouseEvent* event); - void mouseMoveEvent(QMouseEvent* event); - void paintEvent(QPaintEvent *event); - void timerEvent(QTimerEvent* event); + void resizeEvent(QResizeEvent* event) override; + void mouseDoubleClickEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent* e) override; + void enterEvent(QEvent* event) override; + void leaveEvent(QEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; + void mouseMoveEvent(QMouseEvent* event) override; + void paintEvent(QPaintEvent *event) override; + void timerEvent(QTimerEvent* event) override; signals: void frameMoving(ConnectionFrame* frame); diff --git a/src/server/helpwindow/helpwindow.cpp b/src/server/helpwindow/helpwindow.cpp index 152cf0d..f6f1f10 100644 --- a/src/server/helpwindow/helpwindow.cpp +++ b/src/server/helpwindow/helpwindow.cpp @@ -22,7 +22,7 @@ HelpWindow::HelpWindow(const QList<QAction*> &actions, QWidget *parent) : break; } } - QGridLayout *layout = new QGridLayout(this); + auto *layout = new QGridLayout(this); layout->setSpacing(2); QSizePolicy sizePol(QSizePolicy::Minimum, QSizePolicy::Preferred); QList<QLabel*> wrapLabels; @@ -31,24 +31,24 @@ HelpWindow::HelpWindow(const QList<QAction*> &actions, QWidget *parent) : for (QAction *action : actions) { if (action->icon().isNull() || action->text().isEmpty()) continue; - QLabel *icon = new QLabel(this); + auto *icon = new QLabel(this); icon->setPixmap(action->icon().pixmap(iconSize, iconSize, QIcon::Normal, QIcon::Off)); icon->setMinimumSize(iconSize + 5, iconSize + 2); layout->addWidget(icon, row, 0, 3, 1, Qt::AlignTop | Qt::AlignLeft); - QLabel *headline = new QLabel(action->toolTip(), this); + auto *headline = new QLabel(action->toolTip(), this); QFont boldFont = headline->font(); boldFont.setBold(true); headline->setFont(boldFont); headline->setAlignment(Qt::AlignTop | Qt::AlignLeft); layout->addWidget(headline, row, 1, Qt::AlignTop); - QLabel *description = new QLabel(action->text(), this); + auto *description = new QLabel(action->text(), this); description->setWordWrap(true); description->setAlignment(Qt::AlignTop | Qt::AlignLeft); description->setSizePolicy(sizePol); wrapLabels.append(description); layout->addWidget(description, row + 1, 1, Qt::AlignTop); layout->setRowStretch(row + 2, 1); - QFrame *line = new QFrame(); + auto *line = new QFrame(); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); layout->addWidget(line, row + 3, 0, 1, 2); @@ -57,12 +57,12 @@ HelpWindow::HelpWindow(const QList<QAction*> &actions, QWidget *parent) : layout->setColumnStretch(1, 1); // Add close button layout->setRowStretch(row++, 1000); - QPushButton *close = new QPushButton(tr("Close"), this); + auto *close = new QPushButton(tr("Close"), this); QFont bigFont = close->font(); bigFont.setPointSize(20); close->setFont(bigFont); close->setDefault(true); - connect(close, SIGNAL(clicked()), this, SLOT(hide())); + connect(close, &QPushButton::clicked, this, &HelpWindow::hide); layout->addWidget(close, row++, 0, 1, 2); this->setFixedWidth(600); this->setSizePolicy(sizePol); diff --git a/src/server/main.cpp b/src/server/main.cpp index f804c1a..d975f80 100644 --- a/src/server/main.cpp +++ b/src/server/main.cpp @@ -1,27 +1,25 @@ -#include <iostream> -#include <stdlib.h> #include "mainwindow/mainwindow.h" #include "serverapp/serverapp.h" -using std::cout; -using std::endl; +#include <QDebug> void usage() { - cout << "USAGE pvsmgr [OPTIONS]" << endl; - cout << "OPTIONS: " << endl; - cout << "--manager-only" << endl; - cout << " pvsmgr terminates if this computer is not a manager of a room" << endl; - cout << "--config=INIFILE" << endl; - cout << " read configuration from INIFILE instead of default path (/opt/openslx/pvs2/pvs2.ini) " << endl; - cout << "--usage" << endl; - cout << " shows this message" << endl; + puts( + "USAGE pvsmgr [OPTIONS]\n" + "OPTIONS: \n" + "--manager-only\n" + " pvsmgr terminates if this computer is not a manager of a room\n" + "--config=INIFILE\n" + " read configuration from INIFILE instead of default path (/opt/openslx/pvs2/pvs2.ini) \n" + "--usage\n" + " shows this message\n" + ); } int main(int argc, char** argv) { - qsrand(uint(QDateTime::currentMSecsSinceEpoch())); ServerApp app(argc, argv); for (QString a : app.arguments()) { diff --git a/src/server/mainwindow/mainwindow.cpp b/src/server/mainwindow/mainwindow.cpp index b63545f..e8247d0 100644 --- a/src/server/mainwindow/mainwindow.cpp +++ b/src/server/mainwindow/mainwindow.cpp @@ -16,11 +16,13 @@ // Self #include "mainwindow.h" // QT stuff -#include <QtWidgets> -#include <QFileDialog> #include <QSvgRenderer> #include <QPainter> #include <QImage> +#include <QMessageBox> +#include <QCloseEvent> +#include <QDialogButtonBox> +#include <QScreen> // Other custom UI elements #include "../serverapp/serverapp.h" #include "../clicklabel/clicklabel.h" @@ -32,16 +34,12 @@ #include "../net/listenserver.h" #include "../net/client.h" #include "../net/discoverylistener.h" -#include "../net/filedownloader.h" // Others #include "../../shared/settings.h" #include "../util/platform/screensaver.h" // Auto-generated ui class #include "ui_mainwindow.h" -#include <iostream> -#include <vector> - #define sStrTutorNdef MainWindow::tr("No tutor defined.") #define sStrTutorOffline MainWindow::tr("Tutor is offline.") #define sStrSourceNdef MainWindow::tr("Please select a projection source.") @@ -49,33 +47,24 @@ #define sStrDestNdef MainWindow::tr("Please select a projection destination.") #define sStrDestOffline MainWindow::tr("The projection destination is offline.") #define sStrSourceDestSame MainWindow::tr("Selected projection target is tutor.") -#define sStrClientOnline MainWindow::tr("Selected client is currently online.") #define sStrNoDestAv MainWindow::tr("No projection destination available.") -using std::vector; -using std::cout; -using std::endl; - /** * Initialize MainWindow and ListenServer. * @param ipListUrl * @param parent */ -MainWindow::MainWindow(QWidget* parent) : - QMainWindow(parent), ui(new Ui::MainWindow), _tbIconSize(24), _tbArea(Qt::LeftToolBarArea), - _lastClientCount(0) +MainWindow::MainWindow(QWidget* parent) + : QMainWindow(parent) + , ui(new Ui::MainWindow) + , _mode(Mode::Multicast) { qDebug() << "MainWindow(parent)"; - _mode = Mode::Multicast; - _streamingSource = 0; /* default value, these will be updated a room is loaded */ _tilesX = 10; _tilesY = 10; - _virtCols = 0; - _virtRows = 0; - _sessionNameWindow = new SessionNameWindow(this); _reloadWindow = new ReloadRoomWindow(this); _reloadWindow->setWindowTitle(tr("Reload Room")); @@ -113,26 +102,26 @@ MainWindow::MainWindow(QWidget* parent) : serverApp->setExam(false); // Close button in tool bar - connect(ui->action_Exit, SIGNAL(triggered()), this, SLOT(onButtonExit())); - connect(ui->action_TutorToAll, SIGNAL(triggered()), this, SLOT(onButtonTutorToAll())); - connect(ui->action_StudentToTutor, SIGNAL(triggered()), this, SLOT(onButtonStudentToTutor())); - connect(ui->action_StudentToTutorExclusive, SIGNAL(triggered()), this, SLOT(onButtonStudentToTutorExclusive())); - connect(ui->action_TutorToStudent, SIGNAL(triggered()), this, SLOT(onButtonTutorToStudent())); - connect(ui->action_StopProjection, SIGNAL(triggered()), this, SLOT(onButtonStopProjection())); - connect(ui->action_SetAsTutor, SIGNAL(triggered()), this, SLOT(onButtonSetAsTutor())); - connect(ui->action_SetAsTutor, SIGNAL(triggered()), this, SLOT(onButtonStopProjection())); - connect(ui->action_Lock, SIGNAL(toggled(bool)), this, SLOT(onButtonLock(bool))); - connect(ui->action_LockSingle, SIGNAL(triggered()), this, SLOT(onButtonLockSingle())); - connect(ui->action_Help, SIGNAL(triggered()), this, SLOT(onButtonHelp())); - connect(ui->actionReload_Room_Configuration, SIGNAL(triggered()), this, SLOT(onButtonReloadRoomConfig())); - connect(ui->action_DeleteClient, SIGNAL(triggered()), this, SLOT(onDeleteClient())); + connect(ui->action_Exit, &QAction::triggered, this, &MainWindow::onButtonExit); + connect(ui->action_TutorToAll, &QAction::triggered, this, &MainWindow::onButtonTutorToAll); + connect(ui->action_StudentToTutor, &QAction::triggered, this, &MainWindow::onButtonStudentToTutor); + connect(ui->action_StudentToTutorExclusive, &QAction::triggered, this, &MainWindow::onButtonStudentToTutorExclusive); + connect(ui->action_TutorToStudent, &QAction::triggered, this, &MainWindow::onButtonTutorToStudent); + connect(ui->action_StopProjection, &QAction::triggered, this, &MainWindow::onButtonStopProjection); + connect(ui->action_SetAsTutor, &QAction::triggered, this, &MainWindow::onButtonSetAsTutor); + connect(ui->action_SetAsTutor, &QAction::triggered, this, &MainWindow::onButtonStopProjection); + connect(ui->action_Lock, &QAction::toggled, this, &MainWindow::onButtonLock); + connect(ui->action_LockSingle, &QAction::triggered, this, &MainWindow::onButtonLockSingle); + connect(ui->action_Help, &QAction::triggered, this, &MainWindow::onButtonHelp); + connect(ui->actionReload_Room_Configuration, &QAction::triggered, this, &MainWindow::onButtonReloadRoomConfig); + connect(ui->action_DeleteClient, &QAction::triggered, this, &MainWindow::onDeleteClient); /* Stuff for the button lock */ //Setup a timeout _buttonLockTimer = new QTimer(this); _buttonLockTimer->setSingleShot(true); _buttonLockTimer->setInterval(BUTTON_BLOCK_TIME); - connect(_buttonLockTimer, SIGNAL(timeout()), this, SLOT(enableButtons())); + connect(_buttonLockTimer, &QTimer::timeout, this, &MainWindow::enableButtons); // Define the locking buttons _lockingButtons << ui->action_DeleteClient @@ -146,18 +135,18 @@ MainWindow::MainWindow(QWidget* parent) : << ui->action_StopProjection; // Clicking the session name label shows the edit field for it - connect(_sessionNameLabel, SIGNAL(clicked()), this, SLOT(onSessionNameClick())); + connect(_sessionNameLabel, &ClickLabel::clicked, this, &MainWindow::onSessionNameClick); // Listen to updates to the session name through the session name window - connect(_sessionNameWindow, SIGNAL(updateSessionName()), this, - SLOT(onSessionNameUpdate())); + connect(_sessionNameWindow, &SessionNameWindow::updateSessionName, + this, &MainWindow::onSessionNameUpdate); setAttribute(Qt::WA_QuitOnClose); setUnifiedTitleAndToolBarOnMac(true); this->showMaximized(); // show the Mainwindow maximized - _listenServer = new ListenServer(CLIENT_PORT); - connect(_listenServer, SIGNAL(newClient(Client*)), this, SLOT(onClientConnected(Client*))); - _discoveryListener = new DiscoveryListener(); + auto *ls = new ListenServer(CLIENT_PORT, this); + connect(ls, &ListenServer::newClient, this, &MainWindow::onClientConnected); + new DiscoveryListener(this); // Finally this->onSessionNameUpdate(); // Just make lable visible. @@ -174,8 +163,8 @@ void MainWindow::clientCountChanged() int clientCount = 0; - for (auto it = _clientFrames.begin(); it != _clientFrames.end(); ++it) { - Client* c = (*it)->client(); + for (auto * frame : _clientFrames) { + Client* c = frame->client(); if (c != nullptr) { bool b = c->isExamMode(); examClientCount += b ? 1 : 0; @@ -240,7 +229,7 @@ static int distance(QPoint a, QPoint b) * @param toIgnore, ignore this connectionframe when considering free slots * @return the free slot */ -QPoint MainWindow::closestFreeSlot(const QPoint preferredPixels, const ConnectionFrame* toIgnore) +QPoint MainWindow::closestFreeSlot(const QPoint &preferredPixels, const ConnectionFrame* toIgnore) { const bool pickFirstOne = ( preferredPixels == QPoint(-1, -1) ); const QSize& clientSize = serverApp->getCurrentRoom()->clientSize; @@ -249,11 +238,11 @@ QPoint MainWindow::closestFreeSlot(const QPoint preferredPixels, const Connectio memset(grid, 0, sizeof(bool) * size_t(_tilesX * _tilesY)); /* set everything to false */ /* fill grid */ - for (auto it = _clientFrames.begin(); it != _clientFrames.end(); ++it) { + for (auto * frame : _clientFrames) { - if (*it == toIgnore) { continue; } + if (frame == toIgnore) { continue; } - const QPoint p = (*it)->getGridPosition(); + const QPoint p = frame->getGridPosition(); for (int x = p.x(); x < p.x() + clientSize.width(); x++) { for (int y = p.y(); y < p.y() + clientSize.height(); y++) { @@ -322,7 +311,7 @@ void MainWindow::placeFrameInFreeSlot(ConnectionFrame* frame, QPoint preferredPi */ ConnectionFrame* MainWindow::createFrame(const QString &computerId, const QPoint* gridPosition, bool fromRoomplan) { - ConnectionFrame *cf = new ConnectionFrame(this, ui->frmRoom, fromRoomplan); + auto *cf = new ConnectionFrame(this, ui->frmRoom, fromRoomplan); if (gridPosition == nullptr) { placeFrameInFreeSlot(cf); } else { @@ -331,9 +320,9 @@ ConnectionFrame* MainWindow::createFrame(const QString &computerId, const QPoint cf->setComputerId(computerId); _clientFrames.append(cf); cf->show(); - connect(cf, SIGNAL(frameMoved(ConnectionFrame *)), this, SLOT(onFrameDropped(ConnectionFrame *))); - connect(cf, SIGNAL(clicked(ConnectionFrame *)), this, SLOT(onFrameClicked(ConnectionFrame *))); - connect(cf, SIGNAL(frameMoving(ConnectionFrame *)), this, SLOT(onFrameMoving(ConnectionFrame *))); + connect(cf, &ConnectionFrame::frameMoved, this, &MainWindow::onFrameDropped); + connect(cf, &ConnectionFrame::clicked, this, &MainWindow::onFrameClicked); + connect(cf, &ConnectionFrame::frameMoving, this, &MainWindow::onFrameMoving); return cf; } @@ -364,10 +353,10 @@ void MainWindow::tellClientCurrentSituation(Client* client) */ Client* MainWindow::getClientFromId(int id) { - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { - if ((*it)->client() != nullptr) { - if ((*it)->client()->id() == id) - return (*it)->client(); + for (auto * frame : _clientFrames) { + if (frame->client() != nullptr) { + if (frame->client()->id() == id) + return frame->client(); } } return nullptr; @@ -381,9 +370,9 @@ Client* MainWindow::getClientFromId(int id) */ ConnectionFrame* MainWindow::getTutorFrame() { - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { - if (((*it) != nullptr) && ((*it)->isTutor())) - return (*it); + for (auto * frame : _clientFrames) { + if ((frame != nullptr) && (frame->isTutor())) + return frame; } return nullptr; } @@ -396,9 +385,9 @@ ConnectionFrame* MainWindow::getTutorFrame() */ ConnectionFrame* MainWindow::getSelectedFrame() { - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { - if (((*it) != nullptr) && ((*it)->isSelected())) - return (*it); + for (auto * frame : _clientFrames) { + if ((frame != nullptr) && (frame->isSelected())) + return frame; } return nullptr; } @@ -469,8 +458,8 @@ void MainWindow::resizeEvent(QResizeEvent* /* e */ ) const QSize& clientSize = room->clientSize; // Check if any frames have been moved beyond the room dimensions - for (auto it = _clientFrames.begin(); it != _clientFrames.end(); ++it) { - QPoint bounds = (*it)->getGridPosition(); + for (auto * frame : _clientFrames) { + QPoint bounds = frame->getGridPosition(); while (bounds.x() + clientSize.width() > newGridSize.width()) { newGridSize += QSize(1, 0); } @@ -498,16 +487,16 @@ void MainWindow::resizeEvent(QResizeEvent* /* e */ ) const int maxY = _tilesY - clientSize.height(); /* Bring back frames which are now out of the screen */ - for (auto it = _clientFrames.begin(); it != _clientFrames.end(); ++it) { - const QPoint gp = (*it)->getGridPosition(); + for (auto * frame : _clientFrames) { + const QPoint gp = frame->getGridPosition(); if ( gp.x() > maxX || gp.y() > maxY ) { - placeFrameInFreeSlot(*it, (*it)->pos()); + placeFrameInFreeSlot(frame, frame->pos()); } } /* Resize all connection windows */ - for (auto it = _clientFrames.begin(); it != _clientFrames.end(); ++it) { - (*it)->updateGeometry(); + for (auto * frame : _clientFrames) { + frame->updateGeometry(); } /* update background image label */ @@ -580,10 +569,10 @@ void MainWindow::reset(bool lock) } // Unlock all clients - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { - if ((*it)->client() != nullptr) { - (*it)->client()->lockScreen(lock); - (*it)->client()->removeAttention(); + for (auto * frame : _clientFrames) { + if (frame->client() != nullptr) { + frame->client()->lockScreen(lock); + frame->client()->removeAttention(); } } @@ -595,6 +584,7 @@ void MainWindow::reset(bool lock) void MainWindow::onFrameMoving(ConnectionFrame* connectionFrame) { + // Get where the frame would be placed, and show a blue shadow in that spot QPoint slot = closestFreeSlot(connectionFrame->pos(), connectionFrame); _dropMarker->setGeometry(slot.x() * getTileWidthPx(), slot.y() * getTileHeightPx(), connectionFrame->width(), connectionFrame->height()); if (!_dropMarker->isVisible()) { @@ -611,11 +601,8 @@ void MainWindow::onFrameMoving(ConnectionFrame* connectionFrame) void MainWindow::onFrameDropped(ConnectionFrame* connectionFrame) { _dropMarker->hide(); - // if (_tilesX <= 0 || _tilesY <= 0) return; const QPoint preferredPixels = connectionFrame->pos(); placeFrameInFreeSlot(connectionFrame, preferredPixels); - - //resizeEvent(nullptr); } /** @@ -626,7 +613,7 @@ void MainWindow::onFrameClicked(ConnectionFrame* frame) { _dropMarker->hide(); ConnectionFrame *current = getSelectedFrame(); - // If same frame is clicked again,, do nothing + // If same frame is clicked again, do nothing if (current == frame) return; @@ -710,19 +697,19 @@ void MainWindow::startVncServerIfNecessary(int from) void MainWindow::onButtonReloadRoomConfig() { - connect(_reloadWindow->buttonBox(), SIGNAL(accepted()), this, SLOT(onReloadRoomOk())); - connect(_reloadWindow->buttonBox(), SIGNAL(rejected()), this, SLOT(onReloadRoomCancel())); + connect(_reloadWindow->buttonBox(), &QDialogButtonBox::accepted, this, &MainWindow::onReloadRoomOk); + connect(_reloadWindow->buttonBox(), &QDialogButtonBox::rejected, this, &MainWindow::onReloadRoomCancel); QList<QString> keyList = serverApp->getRooms().keys(); - for (QList<QString>::iterator it = keyList.begin(); it != keyList.end() ; it++) { - _reloadWindow->addRoom(*it); + for (const auto & it : keyList) { + _reloadWindow->addRoom(it); } _reloadWindow->show(); } void MainWindow::onReloadRoomCancel() { - disconnect(_reloadWindow->buttonBox(), SIGNAL(accepted()), this, SLOT(onReloadRoomOk())); - disconnect(_reloadWindow->buttonBox(), SIGNAL(rejected()), this, SLOT(onReloadRoomCancel())); + disconnect(_reloadWindow->buttonBox(), &QDialogButtonBox::accepted, this, &MainWindow::onReloadRoomOk); + disconnect(_reloadWindow->buttonBox(), &QDialogButtonBox::rejected, this, &MainWindow::onReloadRoomCancel); _reloadWindow->clearRoomList(); _reloadWindow->hide(); } @@ -730,7 +717,7 @@ void MainWindow::onReloadRoomCancel() void MainWindow::reloadCurrentRoom() { /* delete old image */ - if (_backgroundImage != nullptr) {delete _backgroundImage; } + delete _backgroundImage; _backgroundImage = nullptr; const Room *room = serverApp->getCurrentRoom(); @@ -742,8 +729,8 @@ void MainWindow::reloadCurrentRoom() /* place connection frames */ for (auto it = room->clientPositions.begin(); it != room->clientPositions.end(); ++it) { - QString computerId = it.key(); - QPoint pos = it.value(); + const QString& computerId = it.key(); + const QPoint& pos = it.value(); ConnectionFrame *cf = createFrame(computerId, &pos, true); onFrameDropped(cf); @@ -764,7 +751,7 @@ void MainWindow::reloadCurrentRoom() qDebug() << "set background image path: " << imgPath; if (imgPath.endsWith("svg")) { /* render once with maximal screen size */ - const QSize &s = QApplication::desktop()->screenGeometry().size(); // ui->frmRoom->geometry().size(); + QSize s = QGuiApplication::screenAt(geometry().center())->size(); QSvgRenderer renderer(imgPath); _backgroundImage = new QImage(s, QImage::Format_ARGB32); _backgroundImage->fill(Qt::lightGray); /* background color */ @@ -794,12 +781,12 @@ void MainWindow::onReloadRoomOk() "Note that all clients will be deleted."), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if (ret == QMessageBox::Yes) { - disconnect(_reloadWindow->buttonBox(), SIGNAL(accepted()), this, SLOT(onReloadRoomOk())); - disconnect(_reloadWindow->buttonBox(), SIGNAL(rejected()), this, SLOT(onReloadRoomCancel())); + disconnect(_reloadWindow->buttonBox(), &QDialogButtonBox::accepted, this, &MainWindow::onReloadRoomOk); + disconnect(_reloadWindow->buttonBox(), &QDialogButtonBox::rejected, this, &MainWindow::onReloadRoomCancel); // Delete all clients. - for (QList<ConnectionFrame*>::iterator it = _clientFrames.begin(); it != _clientFrames.end(); it++) { - (*it)->hide(); - (*it)->deleteLater(); + for (auto * frame : _clientFrames) { + frame->hide(); + frame->deleteLater(); } _clientFrames.clear(); @@ -864,9 +851,9 @@ void MainWindow::onButtonTutorToAll() } // Set all clients as watchers of tutor. Except for the tutors desired source, which hase to be none - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - if ((*it)->client() != nullptr) - (*it)->client()->setDesiredProjectionSource((*it)->client() == getTutorFrame()->client() ? NO_SOURCE : getTutorFrame()->client()->id()); + for (auto * frame : _clientFrames) + if (frame->client() != nullptr) + frame->client()->setDesiredProjectionSource(frame->client() == getTutorFrame()->client() ? NO_SOURCE : getTutorFrame()->client()->id()); disableButtons(); _mode = Mode::Broadcast; @@ -913,7 +900,7 @@ void MainWindow::onButtonTutorToStudent() disableButtons(); int numClients = 0; - for (auto c : _clientFrames) { + for (auto * c : _clientFrames) { if (c->client() != nullptr && c->client()->desiredProjectionSource() == sourceClient->id()) { numClients++; } @@ -1035,10 +1022,10 @@ void MainWindow::onButtonLockSingle() client->lockScreen(newState); if (!newState) { // If no more clients are locked, reset button - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { - if ((*it)->client() == nullptr) + for (auto * frame : _clientFrames) { + if (frame->client() == nullptr) continue; - if ((*it)->client()->isLocked()) + if (frame->client()->isLocked()) return; } ui->action_Lock->setChecked(false); @@ -1089,8 +1076,8 @@ void MainWindow::onButtonSetAsTutor() */ void MainWindow::onClientConnected(Client* client) { - connect(client, SIGNAL(authenticating(Client*, ClientLogin*)), this, SLOT(onClientAuthenticating(Client*, ClientLogin*))); - connect(client, SIGNAL(authenticated(Client*)), this, SLOT(onClientAuthenticated(Client*))); + connect(client, &Client::authenticating, this, &MainWindow::onClientAuthenticating); + connect(client, &Client::authenticated, this, &MainWindow::onClientAuthenticated); } /** @@ -1105,7 +1092,7 @@ void MainWindow::onClientConnected(Client* client) */ void MainWindow::onClientAuthenticating(Client* client, ClientLogin* request) { - disconnect(client, SIGNAL(authenticating(Client*, ClientLogin*)), this, SLOT(onClientAuthenticating(Client*, ClientLogin*))); + disconnect(client, &Client::authenticating, this, &MainWindow::onClientAuthenticating); /* copy examMode */ client->setExamMode(request->examMode); @@ -1116,8 +1103,8 @@ void MainWindow::onClientAuthenticating(Client* client, ClientLogin* request) int addnum = 1; do { inuse = false; - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { - Client *c = (**it).client(); + for (auto * frame : _clientFrames) { + Client *c = frame->client(); if (c == nullptr) continue; if (!c->isAuthed()) @@ -1133,10 +1120,11 @@ void MainWindow::onClientAuthenticating(Client* client, ClientLogin* request) } } } while (inuse && addnum < 100); - if (inuse) + if (inuse) { request->accept = false; - else + } else { request->name = check; + } } /** @@ -1151,14 +1139,14 @@ void MainWindow::onClientAuthenticating(Client* client, ClientLogin* request) */ void MainWindow::onClientAuthenticated(Client* client) { - disconnect(client, SIGNAL(authenticated(Client*)), this, SLOT(onClientAuthenticated(Client*))); - connect(client, SIGNAL(vncServerStateChange(Client*)), this, SLOT(onVncServerStateChange(Client*))); - connect(client, SIGNAL(vncClientStateChange(Client*)), this, SLOT(onVncClientStateChange(Client*))); + disconnect(client, &Client::authenticated, this, &MainWindow::onClientAuthenticated); + connect(client, &Client::vncServerStateChange, this, &MainWindow::onVncServerStateChange); + connect(client, &Client::vncClientStateChange, this, &MainWindow::onVncClientStateChange); ConnectionFrame *existing = nullptr; ConnectionFrame *cf = nullptr; - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { - if ((*it)->computerId() == client->ip()) { - existing = *it; + for (auto * frame : _clientFrames) { + if (frame->computerId() == client->ip()) { + existing = frame; } } @@ -1170,7 +1158,7 @@ void MainWindow::onClientAuthenticated(Client* client) } cf->assignClient(client); - connect(client, SIGNAL(disconnected()), this, SLOT(clientCountChanged())); + connect(client, &Client::disconnected, this, &MainWindow::clientCountChanged); tellClientCurrentSituation(client); clientCountChanged(); } @@ -1203,13 +1191,13 @@ void MainWindow::onVncServerStateChange(Client* client) client->lockScreen(false); } else { // VNC server stopped on some client or failed to start - reset local pending projection information - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { - if ((*it)->client() != nullptr) { - if ((*it)->client()->desiredProjectionSource() == client->id()) { - (*it)->client()->setDesiredProjectionSource(NO_SOURCE); - (*it)->client()->stopVncClient(); + for (auto * frame : _clientFrames) { + if (frame->client() != nullptr) { + if (frame->client()->desiredProjectionSource() == client->id()) { + frame->client()->setDesiredProjectionSource(NO_SOURCE); + frame->client()->stopVncClient(); if (_mode == Mode::LockedUnicast) - (*it)->client()->lockScreen(true); + frame->client()->lockScreen(true); } } } @@ -1250,14 +1238,14 @@ void MainWindow::onVncClientStateChange(Client* client) * the new connect. */ bool serverHasWatchers = false; - for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - if ((*it)->client() != nullptr) - if ((*it)->client()->desiredProjectionSource() == client->projectionSource()) { + for (auto * frame : _clientFrames) + if (frame->client() != nullptr) + if (frame->client()->desiredProjectionSource() == client->projectionSource()) { serverHasWatchers = true; break; } - if ( !serverHasWatchers ) { + if (!serverHasWatchers) { Client* c = getClientFromId(client->projectionSource()); if (c != nullptr) c->stopVncServer(); diff --git a/src/server/mainwindow/mainwindow.h b/src/server/mainwindow/mainwindow.h index 86499af..d4967f8 100644 --- a/src/server/mainwindow/mainwindow.h +++ b/src/server/mainwindow/mainwindow.h @@ -1,9 +1,7 @@ -#ifndef _MAINWINDOW_H_ -#define _MAINWINDOW_H_ +#ifndef PVS_MAINWINDOW_H_ +#define PVS_MAINWINDOW_H_ -#include <QtWidgets> #include <QMainWindow> -#include "../net/client.h" class SessionNameWindow; class ConnectionFrame; @@ -11,6 +9,11 @@ class ListenServer; class DiscoveryListener; class HelpWindow; class ReloadRoomWindow; +class ClientLogin; +class Client; +class ClickLabel; + +class QLabel; namespace Ui { @@ -27,8 +30,8 @@ class MainWindow : public QMainWindow public: - MainWindow(QWidget *parent = 0); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; QRect calcFrameGeometry(ConnectionFrame* frame) const; @@ -38,24 +41,17 @@ private: Ui::MainWindow *ui; SessionNameWindow *_sessionNameWindow; HelpWindow *_helpWindow; - ReloadRoomWindow *_reloadWindow; - QLabel *_sessionNameLabel; - int _tbIconSize; - Qt::ToolBarArea _tbArea; + ReloadRoomWindow *_reloadWindow; + ClickLabel *_sessionNameLabel; int _tilesX; int _tilesY; QImage* _backgroundImage = nullptr; QLabel* _examModeLabel = nullptr; - - /* virtual columns to preserve the aspect ratio of the loaded room */ - int _virtCols; - int _virtRows; - // Button block stuff QTimer *_buttonLockTimer; QList<QAction*> _lockingButtons; - static const qint64 BUTTON_BLOCK_TIME = 2000; + static const qint64 BUTTON_BLOCK_TIME = 2000; // Management stuff enum class Mode @@ -66,19 +62,16 @@ private: LockedUnicast, None } _mode; - int _streamingSource; + int _streamingSource{}; QList<ConnectionFrame*> _clientFrames; QWidget *_dropMarker; - ListenServer *_listenServer; - DiscoveryListener *_discoveryListener; - int _lastClientCount; + int _lastClientCount{}; - QPoint closestFreeSlot(const QPoint preferredPixels, const ConnectionFrame* toIgnore); + QPoint closestFreeSlot(const QPoint &preferredPixels, const ConnectionFrame* toIgnore); void placeFrameInFreeSlot(ConnectionFrame* frame, QPoint preferred = QPoint(-1, -1)); ConnectionFrame* createFrame(const QString &computerId = QString(), const QPoint *gridPosition = nullptr, bool fromRoomplan = false); - void savePosition(ConnectionFrame *cf); void startVncServerIfNecessary(int from); void tellClientCurrentSituation(Client* client); void reset(bool lock = false); @@ -86,19 +79,19 @@ private: ConnectionFrame* getTutorFrame(); ConnectionFrame* getSelectedFrame(); - void closeEvent(QCloseEvent *e); - void changeEvent(QEvent *e); - void resizeEvent(QResizeEvent *e); - void mouseReleaseEvent(QMouseEvent* e); + void closeEvent(QCloseEvent *e) override; + void changeEvent(QEvent *e) override; + void resizeEvent(QResizeEvent *e) override; + void mouseReleaseEvent(QMouseEvent* e) override; int getTileWidthPx() const; int getTileHeightPx() const; - void updateContextButtonStates(); + void updateContextButtonStates(); void reloadCurrentRoom(); - void vncOneOnOne(bool exclusive); + void vncOneOnOne(bool exclusive); protected slots: void disableButtons(); @@ -126,8 +119,8 @@ protected slots: void onButtonExit(); void onButtonHelp(); // connection frame - void onFrameMoving(ConnectionFrame* frame); - void onFrameDropped(ConnectionFrame* frame); + void onFrameMoving(ConnectionFrame* frame); + void onFrameDropped(ConnectionFrame* frame); void onFrameClicked(ConnectionFrame* frame); // Net void onClientConnected(Client* client); diff --git a/src/server/net/certmanager.cpp b/src/server/net/certmanager.cpp index 5d8d824..968535a 100644 --- a/src/server/net/certmanager.cpp +++ b/src/server/net/certmanager.cpp @@ -18,19 +18,20 @@ #define CERTSTORAGE ".config/openslx/pvs2/" #include "certmanager.h" -#include <QMap> +#include "../../shared/util.h" + +#include <QHash> #include <QDir> #include <QDebug> #include <QFileInfo> -#include <QSettings> #include <QMessageBox> -#include <QApplication> -#include <cstdlib> +#include <QProcess> +#include <QCoreApplication> namespace CertManager { -static QMap<QString, QSslCertificate> _certs; -static QMap<QString, QSslKey> _keys; +static QHash<QString, QSslCertificate> _certs; +static QHash<QString, QSslKey> _keys; static void generateFiles(QString& key, QString& cert); static bool loadFiles(QString& keyFile, QString& certFile, QSslKey &key, QSslCertificate &cert); @@ -44,7 +45,7 @@ bool getPrivateKeyAndCert(const QString &name, QSslKey &key, QSslCertificate &ce } QString certDir = QDir::homePath().append("/").append(CERTSTORAGE); if (!QDir::root().mkpath(certDir)) { - certDir = QString("/tmp/") + QString::number(qrand()) + "-" + QString::number(qrand()) + "/"; + certDir = QString("/tmp/") + QString::number(slxrand()) + "-" + QString::number(slxrand()) + "/"; QDir::root().mkpath(certDir); } QString certFile = certDir.append(name); @@ -66,11 +67,11 @@ bool getPrivateKeyAndCert(const QString &name, QSslKey &key, QSslCertificate &ce void fatal() { - QMessageBox::critical(nullptr, QCoreApplication::trUtf8("OpenSSL error", "CertManager"), - QCoreApplication::trUtf8("Could not generate certificates for secure connections.\n" + QMessageBox::critical(nullptr, QObject::tr("OpenSSL error", "CertManager"), + QObject::tr("Could not generate certificates for secure connections.\n" "PVS will not work.\n\n" "Press OK to quit.", "CertManager")); - qApp->exit(1); + QCoreApplication::exit(1); } static bool loadFiles(QString& keyFile, QString& certFile, QSslKey &key, QSslCertificate &cert) @@ -95,14 +96,18 @@ static bool loadFiles(QString& keyFile, QString& certFile, QSslKey &key, QSslCer static void generateFiles(QString& key, QString& cert) { - char tmp[1000]; - remove(key.toLocal8Bit().data()); - remove(cert.toLocal8Bit().data()); - snprintf(tmp, 1000, - "openssl req -x509 -nodes -days 5000 -newkey rsa:4096 -subj '/C=DE/ST=BaWue/L=Freiburg/CN=openslx.org' -keyout \"%s\" -out \"%s\"", - key.toLocal8Bit().data(), cert.toLocal8Bit().data()); - system(tmp); - snprintf(tmp, 1000, "chmod 0600 \"%s\" \"%s\"", key.toLocal8Bit().data(), cert.toLocal8Bit().data()); - system(tmp); + QProcess p; + QFile::remove(key); + QFile::remove(cert); + p.setProcessChannelMode(QProcess::ForwardedChannels); + p.start(QStringLiteral("openssl"), { + "req", "-x509", "-nodes", "-days", "5000", "-newkey", "rsa:4096", + "-subj", "'/C=DE/ST=BaWue/L=Freiburg/CN=openslx.org'", + "-keyout", key, "-out", cert + }); + p.waitForFinished(); + p.start(QStringLiteral("chmod"), { "0600", key, cert }); + p.waitForFinished(500); } + } diff --git a/src/server/net/client.cpp b/src/server/net/client.cpp index 977eb84..08dfc9a 100644 --- a/src/server/net/client.cpp +++ b/src/server/net/client.cpp @@ -9,46 +9,46 @@ #include "../serverapp/serverapp.h" #include "../../shared/settings.h" #include "../../shared/util.h" + #include <QPixmap> #include <cassert> #include <QNetworkInterface> +#include <QTcpSocket> +#include <QSslSocket> #define CHALLENGE_LEN 20 int Client::_clientIdCounter = 0; -Client::Client(QTcpSocket* socket) : _socket(socket) +Client::Client(QTcpSocket* socket) + : _socket(socket) { assert(socket != nullptr); - _authed = 0; - _projectionSource = 0; _desiredSource = NO_SOURCE; - _isActiveVncClient = false; - _vncPort = 0; - _isTutor = false; - _locked = false; - _wantsAttention = false; - + _socket->setParent(this); _id = ++_clientIdCounter; //_ip = _socket->peerAddress().toString(); qDebug("*** Client %s created.", qPrintable(_socket->peerAddress().toString())); // Connect important signals - connect(_socket, SIGNAL(disconnected()), - this, SLOT(disconnect())); - connect(_socket, SIGNAL(error(QAbstractSocket::SocketError)), - this, SLOT(disconnect())); - connect(_socket, SIGNAL(sslErrors(const QList<QSslError> &)), - this, SLOT(disconnect())); - connect(_socket, SIGNAL(readyRead()), - this, SLOT(onDataArrival())); + connect(_socket, &QTcpSocket::disconnected, + this, &Client::disconnect); + connect(_socket, &QTcpSocket::errorOccurred, + this, &Client::disconnect); + auto *ssl = qobject_cast<QSslSocket*>(_socket); + if (ssl != nullptr) { + connect(ssl, QOverload<const QList<QSslError> &>::of(&QSslSocket::sslErrors), + this, &Client::disconnect); + } + connect(_socket, &QTcpSocket::readyRead, + this, &Client::onDataArrival); // Send challenge _challenge.resize(CHALLENGE_LEN); for (int i = 0; i < CHALLENGE_LEN; ++i) { - _challenge[i] = char(qrand() & 0xff); + _challenge[i] = char(slxrand() & 0xff); } - NetworkMessage msgChlng; - msgChlng.setField(_ID, _CHALLENGE); - msgChlng.setField(_CHALLENGE, _challenge); - msgChlng.writeMessage(_socket); + NetworkMessage msgChallenge; + msgChallenge.setField(_ID, _CHALLENGE); + msgChallenge.setField(_CHALLENGE, _challenge); + msgChallenge.writeMessage(_socket); // give client 3 seconds to complete handshake _timerIdAuthTimeout = startTimer(3000); _timerPingTimeout = startTimer(3000); @@ -58,7 +58,6 @@ Client::Client(QTcpSocket* socket) : _socket(socket) Client::~Client() { qDebug() << "*** Client" << _host << " destroyed."; - _socket->deleteLater(); } void Client::timerEvent(QTimerEvent* event) @@ -302,7 +301,7 @@ void Client::stopVncClient() * Checks if client and manager runs on same machine. * @return Return true, if pvsmanager is running on client. */ -bool Client::isManagerMachine() +bool Client::isManagerMachine() const { foreach (const QHostAddress & address, QNetworkInterface::allAddresses()) if (address != QHostAddress(QHostAddress::LocalHost) @@ -334,3 +333,8 @@ void Client::disconnect() this->deleteLater(); emit disconnected(); } + +QString Client::ip() const +{ + return _socket->peerAddress().toString(); +} diff --git a/src/server/net/client.h b/src/server/net/client.h index 3d5158b..3b95321 100644 --- a/src/server/net/client.h +++ b/src/server/net/client.h @@ -1,13 +1,13 @@ #ifndef CLIENT_H_ #define CLIENT_H_ -#include <QtCore> -#include <QHostAddress> -#include <QAbstractSocket> -#include <QTcpSocket> #include "../../shared/networkmessage.h" +#include <QByteArray> + //class QSslSocket; +class QTcpSocket; +class Client; #define NO_SOURCE 0 @@ -26,32 +26,32 @@ class Client : public QObject public: explicit Client(QTcpSocket* socket); - ~Client(); + ~Client() override; // Getters - inline bool isAuthed() const { return _authed == 2; } - inline const QString& name() const { return _name; } - inline const QString& host() const { return _host; } - inline const QString ip() const { return _socket->peerAddress().toString(); } - inline int id() const { return _id; } - inline bool isActiveVncClient() const { return _isActiveVncClient; } - inline bool isActiveVncServer() const { return _vncPort > 0; } - inline bool isLocked() const { return _locked; } - inline int desiredProjectionSource() const { return _desiredSource; } - inline int projectionSource() const { return _projectionSource; } - inline int isExamMode() const { return _isExamMode; } - inline bool wantsAttention() const { return _wantsAttention; } - inline void removeAttention() { if (!_wantsAttention) return; removeAttentionInternal(); } + bool isAuthed() const { return _authed == 2; } + const QString& name() const { return _name; } + const QString& host() const { return _host; } + QString ip() const; + int id() const { return _id; } + bool isActiveVncClient() const { return _isActiveVncClient; } + bool isActiveVncServer() const { return _vncPort > 0; } + bool isLocked() const { return _locked; } + int desiredProjectionSource() const { return _desiredSource; } + int projectionSource() const { return _projectionSource; } + int isExamMode() const { return _isExamMode; } + bool wantsAttention() const { return _wantsAttention; } + void removeAttention() { if (!_wantsAttention) return; removeAttentionInternal(); } // Setters - inline void setTutor(bool enable) { _isTutor = enable; } - inline void setDesiredProjectionSource(int id) {_desiredSource = id;} - inline void setExamMode(bool mode) { _isExamMode = mode; } + void setTutor(bool enable) { _isTutor = enable; } + void setDesiredProjectionSource(int id) { _desiredSource = id; } + void setExamMode(bool mode) { _isExamMode = mode; } //Send message stuff void startVncServer(); void stopVncServer(); - void startVncClient(Client const * const to ); + void startVncClient(const Client * to); void stopVncClient(); void lockScreen(bool); void requestThumb(const QSize& size); @@ -59,8 +59,8 @@ public: private: QTcpSocket * const _socket; - bool _locked; - int _authed; // 0 = challenge sent, awaiting reply 1 = challenge ok, client challenge replied, awaiting login, 2 = ESTABLISHED + bool _locked{}; + int _authed{}; // 0 = challenge sent, awaiting reply 1 = challenge ok, client challenge replied, awaiting login, 2 = ESTABLISHED QString _name; QString _host; QByteArray _challenge; @@ -69,26 +69,26 @@ private: int _timerIdAuthTimeout, _timerPingTimeout; int _id; // this client's unique id QString _vncRwPass, _vncRoPass; - int _vncPort; // VNCserver state. Greater 0 -> active on this port. Equals 0 -> no server. + int _vncPort{}; // VNCserver state. Greater 0 -> active on this port. Equals 0 -> no server. int _desiredSource; // The source the client shall be connected to - int _projectionSource; // The source the client was or is connected to (depends on _isActiveVncClient) - bool _isActiveVncClient; // VNCclient state. indicating that the client is displaying a remote screen via VNC - bool _isTutor; // Flag indicating that the client has been set as a tutor - bool _isExamMode; - bool _wantsAttention; // Flag telling whether the client activated the "i want attention" button + int _projectionSource{}; // The source the client was or is connected to (depends on _isActiveVncClient) + bool _isActiveVncClient{}; // VNCclient state. indicating that the client is displaying a remote screen via VNC + bool _isTutor{}; // Flag indicating that the client has been set as a tutor + bool _isExamMode{}; + bool _wantsAttention{}; // Flag telling whether the client activated the "i want attention" button QByteArray _rawRemoteScreen; static int _clientIdCounter; - bool isManagerMachine(); + bool isManagerMachine() const; void handleMsg(); void sendMessage(NetworkMessage& message); void removeAttentionInternal(); protected: - void timerEvent(QTimerEvent* event); + void timerEvent(QTimerEvent* event) override; signals: void authenticating(Client* client, ClientLogin* request); diff --git a/src/server/net/discoverylistener.cpp b/src/server/net/discoverylistener.cpp index b0f0df4..d644259 100644 --- a/src/server/net/discoverylistener.cpp +++ b/src/server/net/discoverylistener.cpp @@ -29,23 +29,20 @@ /** * @brief DiscoveryListener::DiscoveryListener */ -DiscoveryListener::DiscoveryListener() : - _socket(this), _counterResetPos(0) +DiscoveryListener::DiscoveryListener(QObject *parent) + : _socket(this) { - if (!_socket.bind(QHostAddress::AnyIPv4, SERVICE_DISCOVERY_PORT)) + if (!_socket.bind(QHostAddress::AnyIPv4, SERVICE_DISCOVERY_PORT)) { qFatal("Could not bind to service discovery port %d", int(SERVICE_DISCOVERY_PORT)); - connect(&_socket, SIGNAL(readyRead()), this, SLOT(onReadyRead())); - for (int i = 0; i < SD_PACKET_TABLE_SIZE; ++i) - _packetCounter[i] = 0; + } + connect(&_socket, &QUdpSocket::readyRead, this, &DiscoveryListener::onReadyRead); startTimer((SPAM_MODERATE_AT_ONCE * SPAM_MODERATE_INTERVAL) / SD_PACKET_TABLE_SIZE + 1); } /** * @brief DiscoveryListener::~DiscoveryListener */ -DiscoveryListener::~DiscoveryListener() -{ -} +DiscoveryListener::~DiscoveryListener() = default; /** * @brief hash @@ -57,8 +54,8 @@ static quint16 hash(const QHostAddress& host) static quint16 seed1 = 0, seed2 = 0; while (seed1 == 0) { // Make sure the algorithm uses different seeds each time the program is // run to prevent hash collision attacks - seed1 = quint16(qrand() & 0xffff); - seed2 = quint16(qrand() & 0xffff); + seed1 = quint16(slxrand() & 0xffff); + seed2 = quint16(slxrand() & 0xffff); } quint8 data[16], len; if (host.protocol() == QAbstractSocket::IPv4Protocol) { @@ -79,8 +76,8 @@ static quint16 hash(const QHostAddress& host) } else { // Durr? len = 2; - data[0] = quint8(qrand()); - data[1] = quint8(qrand()); + data[0] = quint8(slxrand()); + data[1] = quint8(slxrand()); } quint16 result = 0; quint16 mod = seed1; diff --git a/src/server/net/discoverylistener.h b/src/server/net/discoverylistener.h index 64d4351..47a4295 100644 --- a/src/server/net/discoverylistener.h +++ b/src/server/net/discoverylistener.h @@ -8,12 +8,14 @@ #ifndef DISCOVERYLISTENER_H_ #define DISCOVERYLISTENER_H_ -#include <QtCore> +#include <QObject> #include <QUdpSocket> #include "../../shared/networkmessage.h" #define SD_PACKET_TABLE_SIZE 20000 +class QTimerEvent; + class DiscoveryListener : public QObject { Q_OBJECT @@ -21,16 +23,16 @@ class DiscoveryListener : public QObject private: QUdpSocket _socket; NetworkMessage _packet; - int _counterResetPos; + int _counterResetPos{}; - quint8 _packetCounter[SD_PACKET_TABLE_SIZE]; // count packets per source address to ignore spammers + quint8 _packetCounter[SD_PACKET_TABLE_SIZE]{}; // count packets per source address to ignore spammers protected: - void timerEvent(QTimerEvent* event); + void timerEvent(QTimerEvent* event) override; public: - DiscoveryListener(); - virtual ~DiscoveryListener(); + explicit DiscoveryListener(QObject *parent); + ~DiscoveryListener() override; private slots: void onReadyRead(); diff --git a/src/server/net/filedownloader.cpp b/src/server/net/filedownloader.cpp deleted file mode 100644 index b930869..0000000 --- a/src/server/net/filedownloader.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * FileDownloader.cpp - * - * Created on: Mar 7, 2014 - * Author: nils - */ - -#include <QFileInfo> - -#include "filedownloader.h" - -FileDownloader::FileDownloader(QObject *parent) : - QObject(parent) -{ - connect(&m_WebCtrl, SIGNAL(finished(QNetworkReply*)), - SLOT(fileDownloaded(QNetworkReply*))); -} - -FileDownloader::~FileDownloader() -{ - -} - -void FileDownloader::connectSlot(QObject* obj, const char* slot) -{ - QObject::connect(this, SIGNAL(downloaded(QByteArray&)), - obj, slot); -} - -void FileDownloader::fileDownloaded(QNetworkReply* pReply) -{ - QByteArray downloadedData = pReply->readAll(); - //emit a signal - pReply->deleteLater(); - emit downloaded(downloadedData); -} - -void FileDownloader::downloadFile(const QUrl& fileUrl) -{ - m_WebCtrl.get(QNetworkRequest(fileUrl)); -} diff --git a/src/server/net/filedownloader.h b/src/server/net/filedownloader.h deleted file mode 100644 index 227af50..0000000 --- a/src/server/net/filedownloader.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * filedownloader.h - * - * Created on: Mar 7, 2014 - * Author: nils - */ - -#ifndef FILEDOWNLOADER_H_ -#define FILEDOWNLOADER_H_ - -#include <QObject> -#include <QByteArray> -#include <QNetworkAccessManager> -#include <QNetworkRequest> -#include <QNetworkReply> - -class FileDownloader : public QObject -{ - Q_OBJECT -public: - explicit FileDownloader(QObject *parent = 0); - - virtual ~FileDownloader(); - - void downloadFile(const QUrl& fileUrl); - - void connectSlot(QObject* obj, const char* slot); - - QByteArray downloadedData() const; - -signals: - void downloaded(QByteArray& downloadedData); - -private slots: - - void fileDownloaded(QNetworkReply* pReply); - -private: - - QNetworkAccessManager m_WebCtrl; - -}; - -#endif /* FILEDOWNLOADER_H_ */ diff --git a/src/server/net/listenserver.cpp b/src/server/net/listenserver.cpp index 0438fb4..27a1412 100644 --- a/src/server/net/listenserver.cpp +++ b/src/server/net/listenserver.cpp @@ -1,18 +1,20 @@ #include "listenserver.h" #include "client.h" + #include <QSslSocket> -#define MAX_CLIENTS 50 /** * Initialize listenServer to listen on specific port. * And connect Signal newConnection() with Slot newClientConnection(). * @param port */ -ListenServer::ListenServer(quint16 port) +ListenServer::ListenServer(quint16 port, QObject *parent) + : QObject(parent) + , _server(this) { if (!_server.listen(QHostAddress::AnyIPv4, port) || !_server.isListening()) qFatal("Cannot bind to TCP port %d (incoming SSL clients)", int(port)); - connect(&_server, SIGNAL(newConnection()), this, SLOT(newClientConnection())); + connect(&_server, &SslServer::newConnection, this, &ListenServer::newClientConnection); } ListenServer::~ListenServer() @@ -32,7 +34,7 @@ void ListenServer::newClientConnection() { QTcpSocket* sock; while ((sock = _server.nextPendingConnection()) != nullptr) { - Client* client = new Client(sock); // TODO: what happens with disconnected clients + auto* client = new Client(sock); // TODO: what happens with disconnected clients emit newClient(client); } } diff --git a/src/server/net/listenserver.h b/src/server/net/listenserver.h index 640da23..4ad363d 100644 --- a/src/server/net/listenserver.h +++ b/src/server/net/listenserver.h @@ -18,8 +18,8 @@ private: SslServer _server; public: - explicit ListenServer(quint16 port); - virtual ~ListenServer(); + explicit ListenServer(quint16 port, QObject *parent); + ~ListenServer() override; private slots: void newClientConnection(); diff --git a/src/server/net/sslserver.cpp b/src/server/net/sslserver.cpp index b2da034..2dfa84c 100644 --- a/src/server/net/sslserver.cpp +++ b/src/server/net/sslserver.cpp @@ -21,7 +21,9 @@ #include "certmanager.h" #include <unistd.h> -SslServer::SslServer() : QTcpServer(nullptr), _timer(new QTimer(this)) +SslServer::SslServer(QObject *parent) + : QTcpServer(parent) + , _timer(new QTimer(this)) { connect(_timer, &QTimer::timeout, [=]() { if (_pending.empty()) @@ -43,9 +45,11 @@ SslServer::SslServer() : QTcpServer(nullptr), _timer(new QTimer(this)) SslServer::~SslServer() { _timer->stop(); - for (QSslSocket *sock : _pending.keys()) { + auto keys = _pending.keys(); + for (QSslSocket *sock : keys) { sock->deleteLater(); } + _pending.clear(); } /** @@ -64,7 +68,7 @@ void SslServer::incomingConnection(qintptr socketDescriptor) ::close(int(socketDescriptor)); return; } - QSslSocket *serverSocket = new QSslSocket(nullptr); + auto *serverSocket = new QSslSocket(nullptr); connect(serverSocket, QOverload<const QList<QSslError> &>::of(&QSslSocket::sslErrors), this, &SslServer::sslErrors); serverSocket->setPrivateKey(key); serverSocket->setLocalCertificate(cert); @@ -93,8 +97,8 @@ void SslServer::incomingConnection(qintptr socketDescriptor) void SslServer::sslErrors(const QList<QSslError>& errors) { qDebug() << "Client caused sslErrors before connection:"; - for (QList<QSslError>::const_iterator it = errors.begin(); it != errors.end(); it++) { - qDebug() << it->errorString(); + for (const auto & error : errors) { + qDebug() << error.errorString(); } } diff --git a/src/server/net/sslserver.h b/src/server/net/sslserver.h index 03d947a..c74e56c 100644 --- a/src/server/net/sslserver.h +++ b/src/server/net/sslserver.h @@ -35,11 +35,11 @@ private slots: void sslErrors ( const QList<QSslError> & errors ); public: - explicit SslServer(); - virtual ~SslServer(); + explicit SslServer(QObject *parent); + ~SslServer() override; protected: - void incomingConnection(qintptr handle); + void incomingConnection(qintptr handle) override; QHash<QSslSocket*, qint64> _pending; // Queue for connected but unencrypted connections QTimer* _timer; }; diff --git a/src/server/numerickeyboard/numerickeyboard.cpp b/src/server/numerickeyboard/numerickeyboard.cpp index d819a58..e6677aa 100644 --- a/src/server/numerickeyboard/numerickeyboard.cpp +++ b/src/server/numerickeyboard/numerickeyboard.cpp @@ -1,10 +1,5 @@ -#include "src/server/numerickeyboard/numerickeyboard.h" +#include "numerickeyboard.h" #include "ui_numerickeyboard.h" -#include <iostream> - -using std::cout; -using std::endl; - NumericKeyboard::NumericKeyboard(QWidget *parent) : QGroupBox(parent), @@ -12,20 +7,20 @@ NumericKeyboard::NumericKeyboard(QWidget *parent) : { ui->setupUi(this); /* das geht leider nicht ? */ -// connect(ui->button_0, SIGNAL (clicked(bool)), this, SLOT (relayDigit(0))); +// connect(ui->button_0, &QPushButton::clicked, this, &NumericKeyboard::relayDigit); - connect(ui->button_0, SIGNAL (clicked(bool)), this, SLOT (relayDigit0())); - connect(ui->button_1, SIGNAL (clicked(bool)), this, SLOT (relayDigit1())); - connect(ui->button_2, SIGNAL (clicked(bool)), this, SLOT (relayDigit2())); - connect(ui->button_3, SIGNAL (clicked(bool)), this, SLOT (relayDigit3())); - connect(ui->button_4, SIGNAL (clicked(bool)), this, SLOT (relayDigit4())); - connect(ui->button_5, SIGNAL (clicked(bool)), this, SLOT (relayDigit5())); - connect(ui->button_6, SIGNAL (clicked(bool)), this, SLOT (relayDigit6())); - connect(ui->button_7, SIGNAL (clicked(bool)), this, SLOT (relayDigit7())); - connect(ui->button_8, SIGNAL (clicked(bool)), this, SLOT (relayDigit8())); - connect(ui->button_9, SIGNAL (clicked(bool)), this, SLOT (relayDigit9())); + connect(ui->button_0, &QPushButton::clicked, this, &NumericKeyboard::relayDigit0); + connect(ui->button_1, &QPushButton::clicked, this, &NumericKeyboard::relayDigit1); + connect(ui->button_2, &QPushButton::clicked, this, &NumericKeyboard::relayDigit2); + connect(ui->button_3, &QPushButton::clicked, this, &NumericKeyboard::relayDigit3); + connect(ui->button_4, &QPushButton::clicked, this, &NumericKeyboard::relayDigit4); + connect(ui->button_5, &QPushButton::clicked, this, &NumericKeyboard::relayDigit5); + connect(ui->button_6, &QPushButton::clicked, this, &NumericKeyboard::relayDigit6); + connect(ui->button_7, &QPushButton::clicked, this, &NumericKeyboard::relayDigit7); + connect(ui->button_8, &QPushButton::clicked, this, &NumericKeyboard::relayDigit8); + connect(ui->button_9, &QPushButton::clicked, this, &NumericKeyboard::relayDigit9); - connect(ui->button_del, SIGNAL (clicked(bool)), this, SLOT(relayDelete())); + connect(ui->button_del, &QPushButton::clicked, this, &NumericKeyboard::relayDelete); } NumericKeyboard::~NumericKeyboard() diff --git a/src/server/numerickeyboard/numerickeyboard.h b/src/server/numerickeyboard/numerickeyboard.h index 3ece99c..6db3de3 100644 --- a/src/server/numerickeyboard/numerickeyboard.h +++ b/src/server/numerickeyboard/numerickeyboard.h @@ -14,7 +14,7 @@ class NumericKeyboard : public QGroupBox public: explicit NumericKeyboard(QWidget *parent = 0); - ~NumericKeyboard(); + ~NumericKeyboard() override; private: Ui::NumericKeyboard *ui; diff --git a/src/server/reloadroomwindow/reloadroomwindow.h b/src/server/reloadroomwindow/reloadroomwindow.h index 2baf53f..67c2a94 100644 --- a/src/server/reloadroomwindow/reloadroomwindow.h +++ b/src/server/reloadroomwindow/reloadroomwindow.h @@ -16,7 +16,7 @@ class ReloadRoomWindow : public QDialog public: explicit ReloadRoomWindow(QWidget *parent = nullptr); - ~ReloadRoomWindow(); + ~ReloadRoomWindow() override; QDialogButtonBox* buttonBox() const; diff --git a/src/server/serverapp/serverapp.cpp b/src/server/serverapp/serverapp.cpp index 2cc237a..933517b 100644 --- a/src/server/serverapp/serverapp.cpp +++ b/src/server/serverapp/serverapp.cpp @@ -1,15 +1,15 @@ #include <QTranslator> #include <QNetworkInterface> +#include <QSettings> +#include <QLibraryInfo> #include "serverapp.h" +#include "../../shared/util.h" static QSize minimalGridSize(const QMap<QString, QPoint>& clientPositions, QSize& clientSize); ServerApp::ServerApp(int& argc, char** argv) - : QApplication(argc, argv), - _mainWindow(nullptr), - _managerOnly(false), - _isExam(false) + : QApplication(argc, argv) { setOrganizationName("openslx"); setOrganizationDomain("openslx.org"); @@ -22,19 +22,19 @@ ServerApp::ServerApp(int& argc, char** argv) // If started in manager-only mode, and there is no current room // after reading the config, exit right away if (_managerOnly && _currentRoom == "") { - ::exit(0); + QApplication::exit(0); return; } // System strings - QTranslator *qtTranslator = new QTranslator(this); + auto *qtTranslator = new QTranslator(this); if (!qtTranslator->load(QLocale::system(), "qt", "_", QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { qDebug() << "Loading system translations failed" << 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() << "Loading app translations failed"; } else { @@ -43,20 +43,20 @@ ServerApp::ServerApp(int& argc, char** argv) /* Set the global path of the settings */ QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, "/opt/"); - QSharedPointer<QSettings> sys = getSettings(); + QSettings* sys = getSettings(); qDebug() << "System settings are in:" << sys->fileName(); - _mainWindow = new MainWindow(); + new MainWindow(); } QStringList ServerApp::parseParameters() { QStringList rest; - for (QString a : QApplication::arguments()) { - if (a == "--manager-only") { + for (const QString& a : QApplication::arguments()) { + if (a == QStringLiteral("--manager-only")) { _managerOnly = true; break; - } else if (a.startsWith("--config=")) { + } else if (a.startsWith(QStringLiteral("--config="))) { _iniPath = a.mid(9); } else { rest << a; @@ -73,17 +73,20 @@ QStringList ServerApp::arguments() void ServerApp::loadRooms() { - QSharedPointer<QSettings> conf = getSettings(); + QSettings* conf = getSettings(); - if (!conf->contains("rooms")) { qDebug() << "Invalid config file (no rooms are set)!"; return; } + if (!conf->contains(QStringLiteral("rooms"))) { + qDebug() << "Invalid config file (no rooms are set)!"; + return; + } QStringList rooms = conf->value("rooms").toStringList(); - for (QString roomId : rooms) { + for (const QString& roomId : rooms) { conf->beginGroup(roomId); QString roomName = conf->value("name").toString(); /* fallback to the old format where the room id was actually just the name */ - if (roomName == "") { + if (roomName.isEmpty()) { roomName = roomId; } if (!conf->contains("mgrIP")) { @@ -114,8 +117,8 @@ void ServerApp::loadRooms() } foreach (const QHostAddress & address, QNetworkInterface::allAddresses()) { - if (address != QHostAddress(QHostAddress::LocalHost) && mgrIP == address.toString()) { - qDebug("Found this ip in config."); + if (!address.isBroadcast() && !address.isLoopback() && !address.isMulticast() && mgrIP == address.toString()) { + qDebug() << "Found own ip in config."; _currentRoom = roomName; } } @@ -133,18 +136,17 @@ void ServerApp::loadRooms() } } -const Room* ServerApp::getCurrentRoom() +const Room* ServerApp::getCurrentRoom() const { - if (_rooms.contains(_currentRoom)) { - return _rooms[_currentRoom]; - } else { - static Room* defaultRoom = nullptr; - if (defaultRoom == nullptr) { - defaultRoom = new Room(QMap<QString, - QPoint>(), QSize(8, 6), QSize(1, 1), "", ""); - } - return defaultRoom; + auto *room = _rooms.value(_currentRoom); + if (room != nullptr) + return room; + static Room* defaultRoom = nullptr; + if (defaultRoom == nullptr) { + defaultRoom = new Room(QMap<QString, + QPoint>(), QSize(8, 6), QSize(1, 1), "", ""); } + return defaultRoom; } void ServerApp::setSessionName(const QString& name) { @@ -154,20 +156,20 @@ void ServerApp::setSessionName(const QString& name) void ServerApp::setSessionName() { - const QString name = QString::number(qrand() % 9000 + 1000); + const QString name = QString::number(slxrand() % 9000 + 1000); _sessionName = name; _sessionNameArray = name.toUtf8(); } -QSharedPointer<QSettings> ServerApp::getSettings() +QSettings * ServerApp::getSettings() { - QSharedPointer<QSettings> set; - if (_iniPath == "") { + QSettings *set; + if (_iniPath.isEmpty()) { /* default location (system scope) */ - set = QSharedPointer<QSettings>(new QSettings(QSettings::IniFormat, QSettings::SystemScope, "openslx/pvs2", "pvs2")); + set = new QSettings(QSettings::IniFormat, QSettings::SystemScope, "openslx/pvs2", "pvs2", this); } else { /* use _iniPath to find ini file */ - set = QSharedPointer<QSettings>(new QSettings(_iniPath, QSettings::IniFormat)); + set = new QSettings(_iniPath, QSettings::IniFormat, this); } set->setIniCodec("UTF-8"); return set; @@ -182,14 +184,15 @@ static QSize minimalGridSize(const QMap<QString, QPoint>& clientPositions, QSize int x = 0; int y = 0; - for (auto it = clientPositions.begin(); it != clientPositions.end(); ++it) { - QPoint pos = it.value(); - if (pos.x() > x) { x = pos.x(); } - if (pos.y() > y) { y = pos.y(); } - + for (const auto &pos : clientPositions) { + if (pos.x() > x) { + x = pos.x(); + } + if (pos.y() > y) { + y = pos.y(); + } } /* need a little extra space */ - QSize size(x + clientSize.width(), y + clientSize.height()); - return size; + return QSize(x + clientSize.width(), y + clientSize.height()); } diff --git a/src/server/serverapp/serverapp.h b/src/server/serverapp/serverapp.h index e0a1351..b2b16c5 100644 --- a/src/server/serverapp/serverapp.h +++ b/src/server/serverapp/serverapp.h @@ -1,14 +1,16 @@ #ifndef SERVERAPP_H #define SERVERAPP_H +#include "../mainwindow/mainwindow.h" + #include <QApplication> #include <QStringList> #include <QMap> -#include "../mainwindow/mainwindow.h" +class QSettings; struct Room { - Room(QMap<QString, QPoint> cPos, QSize grid, QSize client, QString image, QString tutor) : + Room(const QMap<QString, QPoint> &cPos, const QSize &grid, const QSize &client, const QString &image, const QString &tutor) : clientPositions(cPos), gridSize(grid), clientSize(client), @@ -23,12 +25,12 @@ struct Room { /* define a macro `serverApp` that can be used anywhere in the program and - * returns a reference to the current ClientApp instance */ + * returns a reference to the current ServerApp instance */ #if defined(serverApp) #undef serverApp #endif -#define serverApp (static_cast<ServerApp*>(QCoreApplication::instance())) +#define serverApp (static_cast<ServerApp*>(QCoreApplication::instance())) // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast) /* this class is supposed to (after complete refactoring) to encapsulate all * state of the application. At the moment, the state is distributed within @@ -42,15 +44,14 @@ class ServerApp : public QApplication private: QStringList _arguments; - MainWindow* _mainWindow; QString _sessionName; QByteArray _sessionNameArray; QMap<QString, Room*> _rooms; QString _currentRoom; - bool _managerOnly; - bool _isExam; + bool _managerOnly{}; + bool _isExam{}; QString _iniPath; QStringList parseParameters(); @@ -64,20 +65,16 @@ public: /* getters */ - const QString& sessionName() { return _sessionName; } - const QByteArray& sessionNameArray() { return _sessionNameArray; } - const QMap<QString, Room*> & rooms() { return _rooms; } - const QString& getCurrentRoomName() { return _currentRoom; } - const QMap<QString, Room*>& getRooms() { return _rooms; } - bool isExam() { return _isExam; } - bool isManagerOnly() { return _managerOnly; } - const Room* getCurrentRoom(); - QSharedPointer<QSettings> getSettings(); + const QString &sessionName() const { return _sessionName; } + const QByteArray &sessionNameArray() const { return _sessionNameArray; } + const QMap<QString, Room *> &getRooms() const { return _rooms; } + bool isExam() const { return _isExam; } + const Room* getCurrentRoom() const; + QSettings * getSettings(); /* setters */ void setSessionName(const QString& name); void setSessionName(); - void setIniPath(QString s) { _iniPath = s; }; void setCurrentRoom(const QString& room) { _currentRoom = room; } void setExam(bool exam) { _isExam = exam; } diff --git a/src/server/sessionnamewindow/sessionnamewindow.cpp b/src/server/sessionnamewindow/sessionnamewindow.cpp index f79efbf..74aa05d 100644 --- a/src/server/sessionnamewindow/sessionnamewindow.cpp +++ b/src/server/sessionnamewindow/sessionnamewindow.cpp @@ -9,32 +9,30 @@ # # General information about OpenSLX can be found at http://openslx.org/ # ----------------------------------------------------------------------------- - # mainWindow.cpp - This is the Main class for the pvsManager. The GUI is contructed here. - # ----------------------------------------------------------------------------- */ -#include <QtWidgets> #include "sessionnamewindow.h" +#include "ui_sessionnamewindow.h" #include "../serverapp/serverapp.h" #include "../numerickeyboard/numerickeyboard.h" -#include "ui_sessionnamewindow.h" - +#include "../../shared/util.h" -SessionNameWindow::SessionNameWindow(QWidget *parent) : - QDialog(parent), ui(new Ui::SessionName) +#include <QCloseEvent> +SessionNameWindow::SessionNameWindow(QWidget *parent) + : QDialog(parent) + , ui(new Ui::SessionName) { ui->setupUi(this); - connect(ui->bboxOkCancel, SIGNAL(accepted()), this, SLOT(onOkClicked())); - connect(ui->bboxOkCancel, SIGNAL(rejected()), this, SLOT(close())); - connect(ui->cmdRandom, SIGNAL(clicked(bool)), this, SLOT(onGenerateRandomName())); + connect(ui->bboxOkCancel, &QDialogButtonBox::accepted, this, &SessionNameWindow::onOkClicked); + connect(ui->bboxOkCancel, &QDialogButtonBox::rejected, this, &SessionNameWindow::close); + connect(ui->cmdRandom, &QPushButton::clicked, this, &SessionNameWindow::onGenerateRandomName); /* add a virtual numeric keyboard */ - NumericKeyboard *keyboard = new NumericKeyboard(); + auto *keyboard = new NumericKeyboard(); ui->keyboard_placeholder->addWidget(keyboard); - connect(keyboard, SIGNAL(digitTyped(int)), this, SLOT(onDigitTyped(int))); - connect(keyboard, SIGNAL(digitDelete()), this, SLOT(onDigitDelete())); + connect(keyboard, &NumericKeyboard::digitTyped, this, &SessionNameWindow::onDigitTyped); + connect(keyboard, &NumericKeyboard::digitDelete, this, &SessionNameWindow::onDigitDelete); } @@ -73,7 +71,7 @@ void SessionNameWindow::onOkClicked() void SessionNameWindow::onGenerateRandomName() { - ui->lineEditName->setText(QString::number(qrand() % 9000 + 1000)); + ui->lineEditName->setText(QString::number(slxrand() % 9000 + 1000)); } /** deletes the last digit of the saved sessionname */ diff --git a/src/server/sessionnamewindow/sessionnamewindow.h b/src/server/sessionnamewindow/sessionnamewindow.h index e46b895..024df48 100644 --- a/src/server/sessionnamewindow/sessionnamewindow.h +++ b/src/server/sessionnamewindow/sessionnamewindow.h @@ -1,8 +1,7 @@ -#ifndef _SESSIONNAMEWINDOW_H_ -#define _SESSIONNAMEWINDOW_H_ - -#include <QtWidgets> +#ifndef PVS_SESSIONNAMEWINDOW_H_ +#define PVS_SESSIONNAMEWINDOW_H_ +#include <QDialog> namespace Ui { @@ -17,13 +16,13 @@ private: Ui::SessionName *ui; public: - SessionNameWindow(QWidget *parent = 0); - ~SessionNameWindow(); + explicit SessionNameWindow(QWidget *parent = nullptr); + ~SessionNameWindow() override; void show(const QString& name); protected: - void closeEvent(QCloseEvent *e); + void closeEvent(QCloseEvent *e) override; private slots: void onOkClicked(); |