From 3d82bfc698165bb20f3c38d42f2b77ab855c1edf Mon Sep 17 00:00:00 2001 From: Christian Klinger Date: Thu, 29 Sep 2016 15:40:18 +0200 Subject: astyle. --- .astylerc | 14 + src/client/clientapp/clientapp.cpp | 91 +-- src/client/clientapp/clientapp.h | 31 +- src/client/connectwindow/connectwindow.cpp | 140 ++-- src/client/connectwindow/connectwindow.h | 23 +- src/client/informationdialog/informationdialog.cpp | 8 +- src/client/informationdialog/informationdialog.h | 7 +- src/client/main.cpp | 30 +- src/client/net/serverconnection.cpp | 171 ++--- src/client/net/serverconnection.h | 2 +- src/client/net/serverdiscovery.cpp | 35 +- src/client/net/serverdiscovery.h | 81 +-- src/client/toolbar/toolbar.cpp | 194 ++--- src/client/toolbar/toolbar.h | 17 +- src/client/util/platform/blankscreen.h | 16 +- src/client/util/platform/blankscreen_Win32.cpp | 82 +-- src/client/util/platform/blankscreen_X11.cpp | 17 +- src/client/util/room.h | 29 +- src/client/util/util.h | 4 +- src/client/vnc/vncserver.cpp | 37 +- src/client/vnc/vncserver.h | 2 +- src/client/vnc/vncthread.cpp | 32 +- src/client/vnc/vncthread.h | 2 +- src/client/vnc/vncwindow.cpp | 49 +- src/client/vnc/vncwindow.h | 2 +- src/server/connectionframe/connectionframe.cpp | 161 ++--- src/server/connectionframe/connectionframe.h | 8 +- src/server/helpwindow/helpwindow.h | 3 +- src/server/main.cpp | 5 +- src/server/mainwindow/mainwindow.cpp | 786 ++++++++++----------- src/server/mainwindow/mainwindow.h | 48 +- src/server/net/certmanager.cpp | 184 +++-- src/server/net/certmanager.h | 58 +- src/server/net/client.cpp | 116 ++- src/server/net/client.h | 9 +- src/server/net/discoverylistener.cpp | 30 +- src/server/net/filedownloader.cpp | 19 +- src/server/net/listenserver.cpp | 3 +- src/server/net/sslserver.cpp | 25 +- src/server/numerickeyboard/numerickeyboard.cpp | 34 +- src/server/numerickeyboard/numerickeyboard.h | 37 +- src/server/reloadroomwindow/reloadroomwindow.h | 3 +- src/server/sessionnamewindow/sessionnamewindow.cpp | 24 +- src/server/sessionnamewindow/sessionnamewindow.h | 9 +- src/server/util/global.cpp | 46 +- src/server/util/global.h | 54 +- src/shared/network.cpp | 3 +- src/shared/networkmessage.cpp | 80 +-- 48 files changed, 1340 insertions(+), 1521 deletions(-) create mode 100644 .astylerc mode change 100755 => 100644 src/client/util/platform/blankscreen.h mode change 100755 => 100644 src/client/util/platform/blankscreen_Win32.cpp mode change 100755 => 100644 src/client/util/platform/blankscreen_X11.cpp diff --git a/.astylerc b/.astylerc new file mode 100644 index 0000000..b792a5f --- /dev/null +++ b/.astylerc @@ -0,0 +1,14 @@ +style=kr +indent=tab +#max-code-length=120 + +# spaces +pad-oper +pad-header + +# line endings +lineend=linux + +# keep some things +keep-one-line-statements +keep-one-line-blocks diff --git a/src/client/clientapp/clientapp.cpp b/src/client/clientapp/clientapp.cpp index 6e1a555..18ef0de 100644 --- a/src/client/clientapp/clientapp.cpp +++ b/src/client/clientapp/clientapp.cpp @@ -1,54 +1,57 @@ #include "clientapp.h" ClientApp::ClientApp(int& argc, char** argv) - : QApplication(argc, argv), _connectionMode(ConnectionMode::None), _examMode(false) { - /* some values */ - setOrganizationName("openslx"); - setOrganizationDomain("openslx.org"); - setApplicationName("pvsclient"); - - /* configuration */ - QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, "/opt/"); - - _arguments = parseParameters(); - - - /* TODO: Move the connection handling to ClientApp */ - if (_connectionMode == ConnectionMode::Auto) { - _toolbar = new Toolbar(true); // auto connect client without session ID. - } else if (_connectionMode == ConnectionMode::Session) { - _toolbar = new Toolbar(_sessionName.toUtf8()); // connect client with given session ID. - } else { - _toolbar = new Toolbar(); // create normal client. - } - _toolbar->setVisible(!_examMode); - - /* set translator */ - /* use system locale as language to translate gui */ - QTranslator translator; - translator.load(":pvsclient"); - installTranslator(&translator); + : QApplication(argc, argv), _connectionMode(ConnectionMode::None), _examMode(false) +{ + /* some values */ + setOrganizationName("openslx"); + setOrganizationDomain("openslx.org"); + setApplicationName("pvsclient"); + + /* configuration */ + QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, "/opt/"); + + _arguments = parseParameters(); + + + /* TODO: Move the connection handling to ClientApp */ + if (_connectionMode == ConnectionMode::Auto) { + _toolbar = new Toolbar(true); // auto connect client without session ID. + } else if (_connectionMode == ConnectionMode::Session) { + _toolbar = new Toolbar(_sessionName.toUtf8()); // connect client with given session ID. + } else { + _toolbar = new Toolbar(); // create normal client. + } + _toolbar->setVisible(!_examMode); + + /* set translator */ + /* use system locale as language to translate gui */ + QTranslator translator; + translator.load(":pvsclient"); + installTranslator(&translator); }; /* parse arguments and return a list with the unused arguments */ -QStringList ClientApp::parseParameters() { - QStringList rest; - for (QString a : QApplication::arguments()) { - if (a == "--exam-mode") { - _examMode = true; - } else if (a == "--auto") { - _connectionMode = ConnectionMode::Auto; - } else if (a.startsWith("--session=")) { - _connectionMode = ConnectionMode::Session; - _sessionName = a.replace("--session=", ""); - } else { - rest << a; - } - } - return rest; +QStringList ClientApp::parseParameters() +{ + QStringList rest; + for (QString a : QApplication::arguments()) { + if (a == "--exam-mode") { + _examMode = true; + } else if (a == "--auto") { + _connectionMode = ConnectionMode::Auto; + } else if (a.startsWith("--session=")) { + _connectionMode = ConnectionMode::Session; + _sessionName = a.replace("--session=", ""); + } else { + rest << a; + } + } + return rest; } -QStringList ClientApp::arguments() { - return _arguments; +QStringList ClientApp::arguments() +{ + return _arguments; } diff --git a/src/client/clientapp/clientapp.h b/src/client/clientapp/clientapp.h index 996d48d..910eba2 100644 --- a/src/client/clientapp/clientapp.h +++ b/src/client/clientapp/clientapp.h @@ -14,27 +14,28 @@ * several widgets. With this class information access will also be easier as * it is possible to access the current ClientApp instance from anywhere with * the clientApp macro (like qApp) macro */ -class ClientApp : public QApplication { +class ClientApp : public QApplication +{ - Q_OBJECT + Q_OBJECT - public: - enum ConnectionMode { None, Auto, Session }; +public: + enum ConnectionMode { None, Auto, Session }; - private: - bool _examMode; - ConnectionMode _connectionMode; /* way of automatically connection to a session on startup*/ - QString _sessionName; /* only set when _connectionMode == Session */ - Toolbar* _toolbar; - QStringList _arguments; +private: + bool _examMode; + ConnectionMode _connectionMode; /* way of automatically connection to a session on startup*/ + QString _sessionName; /* only set when _connectionMode == Session */ + Toolbar* _toolbar; + QStringList _arguments; - QStringList parseParameters(); + QStringList parseParameters(); - public: +public: - ClientApp(int& argc, char** argv); + ClientApp(int& argc, char** argv); - bool isExamMode() const { return _examMode; }; + bool isExamMode() const { return _examMode; }; - virtual QStringList arguments(); + virtual QStringList arguments(); }; diff --git a/src/client/connectwindow/connectwindow.cpp b/src/client/connectwindow/connectwindow.cpp index 712691e..fed4256 100644 --- a/src/client/connectwindow/connectwindow.cpp +++ b/src/client/connectwindow/connectwindow.cpp @@ -21,7 +21,7 @@ * @param parent */ ConnectWindow::ConnectWindow(QWidget *parent) : QWidget(parent) -{ +{ _ui = new Ui::ConnectWindow; _timerHide = 0; _connection = NULL; @@ -41,17 +41,17 @@ ConnectWindow::ConnectWindow(QWidget *parent) : QWidget(parent) connect(_ui->btn_connection, SIGNAL(clicked()), this, SLOT(onBtnConnection())); connect(_ui->btn_hide, SIGNAL(clicked()), this, SLOT(onBtnCancel())); - connect(_ui->comboBox_rooms, SIGNAL(currentIndexChanged(int)), this, SLOT(onRoomSelection(int))); + connect(_ui->comboBox_rooms, SIGNAL(currentIndexChanged(int)), this, SLOT(onRoomSelection(int))); // React on discovery signal - connect(&_serverDiscovery, SIGNAL(serverDetected(QString,quint16,QByteArray,QByteArray,bool)), - this, SLOT(onServerDetected(QString,quint16,QByteArray,QByteArray,bool))); + connect(&_serverDiscovery, SIGNAL(serverDetected(QString, quint16, QByteArray, QByteArray, bool)), + this, SLOT(onServerDetected(QString, quint16, QByteArray, QByteArray, bool))); - /* finally the most requested feature: connect on press of the enter key */ - connect(_ui->lineEditName, SIGNAL(returnPressed()),_ui->btn_connection, SIGNAL(clicked())); + /* finally the most requested feature: connect on press of the enter key */ + connect(_ui->lineEditName, SIGNAL(returnPressed()), _ui->btn_connection, SIGNAL(clicked())); - /* by default don't show the manual connection box */ - _ui->box_manual->setVisible(false); + /* by default don't show the manual connection box */ + _ui->box_manual->setVisible(false); this->updateUserInterface(); } @@ -59,7 +59,7 @@ ConnectWindow::ConnectWindow(QWidget *parent) : QWidget(parent) /***************************************************************************//** * @brief ConnectWindow::~ConnectWindow */ -ConnectWindow::~ConnectWindow(){} +ConnectWindow::~ConnectWindow() {} @@ -71,8 +71,7 @@ void ConnectWindow::updateUserInterface() { _ui->lineEditName->setEnabled(_state == Idle); - if (_state == Connected) - { + if (_state == Connected) { _ui->btn_connection->setEnabled(true); _ui->btn_connection->setText(tr("&Disconnect")); _ui->lblStatus->setText(tr("Connected to %1").arg(_connection->getPeerAdress())); @@ -86,8 +85,7 @@ void ConnectWindow::updateUserInterface() else _ui->btn_connection->setText(tr("&Connect")); - switch (_state) - { + switch (_state) { case Idle: _ui->lblStatus->setText(tr("Ready to connect.")); break; @@ -128,14 +126,12 @@ void ConnectWindow::updateUserInterface() */ void ConnectWindow::timerEvent(QTimerEvent* event) { - if(event->timerId() == _timerHide) - { + if (event->timerId() == _timerHide) { killTimer(_timerHide); _timerHide = 0; this->hide(); _ui->stackedWidget->setCurrentIndex(0); - } - else + } else // Unknown/Old timer id, kill it ??? PALM -> FACE killTimer(event->timerId()); } @@ -152,9 +148,9 @@ void ConnectWindow::closeEvent(QCloseEvent *e) void ConnectWindow::doShow() { - /* reset to automatic connect window */ - _ui->stackedWidget->setCurrentIndex(0); - _ui->comboBox_rooms->setCurrentIndex(0); + /* reset to automatic connect window */ + _ui->stackedWidget->setCurrentIndex(0); + _ui->comboBox_rooms->setCurrentIndex(0); show(); showNormal(); activateWindow(); @@ -196,29 +192,31 @@ void ConnectWindow::connectToSession(const QByteArray sessionName, QString mgrIP -void ConnectWindow::DoConnect() { - qDebug() << "DoConnect()"; - // Connect (scan for session) - // qDebug() << _ui->lineEditName->text().toUtf8(); - int index = _ui->comboBox_rooms->currentIndex(); - QString selectedMgrIP =_ui->comboBox_rooms->itemData(index).toString(); - - if (selectedMgrIP == "manual_connection") { - qDebug() << "connect to sessionName by manual connection"; - QByteArray sessionName = _ui->lineEditName->text().toUtf8(); - connectToSession(sessionName, ""); - } else { - qDebug() << "connect to mgrIP (through room selection) " << selectedMgrIP; - connectToSession("", selectedMgrIP); - } +void ConnectWindow::DoConnect() +{ + qDebug() << "DoConnect()"; + // Connect (scan for session) + // qDebug() << _ui->lineEditName->text().toUtf8(); + int index = _ui->comboBox_rooms->currentIndex(); + QString selectedMgrIP = _ui->comboBox_rooms->itemData(index).toString(); + + if (selectedMgrIP == "manual_connection") { + qDebug() << "connect to sessionName by manual connection"; + QByteArray sessionName = _ui->lineEditName->text().toUtf8(); + connectToSession(sessionName, ""); + } else { + qDebug() << "connect to mgrIP (through room selection) " << selectedMgrIP; + connectToSession("", selectedMgrIP); + } } -void ConnectWindow::DoDisconnect() { - qDebug() << "DoDisconnect()"; - _tryReconnect = false; - // Stop or disconnect - emit disconnect(); - _state = Idle; +void ConnectWindow::DoDisconnect() +{ + qDebug() << "DoDisconnect()"; + _tryReconnect = false; + // Stop or disconnect + emit disconnect(); + _state = Idle; } @@ -229,7 +227,7 @@ void ConnectWindow::DoDisconnect() { */ void ConnectWindow::onBtnConnection() { - if (_timerHide){ + if (_timerHide) { killTimer(_timerHide); _timerHide = 0; _ui->stackedWidget->setCurrentIndex(0); @@ -239,23 +237,24 @@ void ConnectWindow::onBtnConnection() _serverDiscovery.stop(); if (_state != Idle) { - DoDisconnect(); + DoDisconnect(); } else { - DoConnect(); + DoConnect(); } - this->updateUserInterface(); + this->updateUserInterface(); } /** set the available rooms. * If the list of rooms is empty, switches automatically to the "manual * connection" page */ -void ConnectWindow::setAvailableRooms(QList m) { - _ui->comboBox_rooms->clear(); - foreach (Room r, m) { - _ui->comboBox_rooms->addItem(tr("Room ") + r.name, r.mgr); - } - /* also add a pseudo-room "manual choice" */ - _ui->comboBox_rooms->addItem(tr("Session Name..."), "manual_connection"); +void ConnectWindow::setAvailableRooms(QList m) +{ + _ui->comboBox_rooms->clear(); + foreach (Room r, m) { + _ui->comboBox_rooms->addItem(tr("Room ") + r.name, r.mgr); + } + /* also add a pseudo-room "manual choice" */ + _ui->comboBox_rooms->addItem(tr("Session Name..."), "manual_connection"); } /***************************************************************************//** * Handle click on Cancel/Hide Button. @@ -268,17 +267,18 @@ void ConnectWindow::onBtnCancel() /** check if "manual_connection" is selected, then switch to manual * connection page */ -void ConnectWindow::onRoomSelection(int index) { - QString sessionName = _ui->comboBox_rooms->itemData(index).toString(); - if (sessionName == "manual_connection") { - qDebug() << "switch to manual connection"; - _ui->box_manual->setVisible(true); - //this->setSize(QSize(300,200)); - this->resize(300, 200); - } else { - _ui->box_manual->setVisible(false); - this->resize(300, 140); - } +void ConnectWindow::onRoomSelection(int index) +{ + QString sessionName = _ui->comboBox_rooms->itemData(index).toString(); + if (sessionName == "manual_connection") { + qDebug() << "switch to manual connection"; + _ui->box_manual->setVisible(true); + //this->setSize(QSize(300,200)); + this->resize(300, 200); + } else { + _ui->box_manual->setVisible(false); + this->resize(300, 140); + } } /***************************************************************************//** @@ -313,8 +313,7 @@ void ConnectWindow::onConnectionStateChange(ConnectWindow::ConnectionState state if (reset) { _state = Scanning; } - if (state == Connected) - { + if (state == Connected) { QObject::disconnect(_connection, SIGNAL(stateChange(ConnectWindow::ConnectionState)), this, SLOT(onConnectionStateChange(ConnectWindow::ConnectionState))); QObject::disconnect(_connection, SIGNAL(destroyed(QObject*)), this, SLOT(onConnectionClosed(QObject*))); emit connected(_connection); @@ -326,11 +325,12 @@ void ConnectWindow::onConnectionStateChange(ConnectWindow::ConnectionState state } } -void ConnectWindow::onComboBox_keyPressed(QKeyEvent* e) { - qDebug() << "key released"; - if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return ) { - qDebug() << "enter pressed"; - } +void ConnectWindow::onComboBox_keyPressed(QKeyEvent* e) +{ + qDebug() << "key released"; + if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return ) { + qDebug() << "enter pressed"; + } } diff --git a/src/client/connectwindow/connectwindow.h b/src/client/connectwindow/connectwindow.h index 3eed6e0..aa89094 100644 --- a/src/client/connectwindow/connectwindow.h +++ b/src/client/connectwindow/connectwindow.h @@ -24,7 +24,8 @@ #include "../net/serverdiscovery.h" #include "../util/room.h" -namespace Ui{ +namespace Ui +{ class ConnectWindow; } class ServerConnection; @@ -38,7 +39,7 @@ class ServerConnection; */ class ConnectWindow : public QWidget { -Q_OBJECT + Q_OBJECT public: enum ConnectionState { @@ -55,9 +56,9 @@ public: explicit ConnectWindow(QWidget *parent = NULL); virtual ~ConnectWindow(); - + void connectToSession(const QByteArray sessionName, QString mgrIP); - void setAvailableRooms(QList m); + void setAvailableRooms(QList m); private: Ui::ConnectWindow *_ui; @@ -67,7 +68,7 @@ private: ConnectionState _state; QByteArray _currentSession; QString _currentIp; - QString _defaultSessionName; + QString _defaultSessionName; NetworkMessage _packet; bool _tryReconnect; int _timerHide; @@ -84,7 +85,7 @@ protected slots: void onBtnConnection(); void onBtnCancel(); - void onRoomSelection(int index); + void onRoomSelection(int index); void onConnectionStateChange(ConnectWindow::ConnectionState state); void onConnectionClosed(QObject* connection); @@ -92,13 +93,13 @@ protected slots: // void onUdpReadyRead(); void onServerDetected(const QString& host, const quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect); - void onComboBox_keyPressed(QKeyEvent* e); + void onComboBox_keyPressed(QKeyEvent* e); public slots: - /** actually connects the connection **/ - void DoConnect(); - /** actually disconnects the connection **/ - void DoDisconnect(); + /** actually connects the connection **/ + void DoConnect(); + /** actually disconnects the connection **/ + void DoDisconnect(); signals: void disconnect(); void connected(ServerConnection* connection); diff --git a/src/client/informationdialog/informationdialog.cpp b/src/client/informationdialog/informationdialog.cpp index bc53ee9..6a8a6b7 100644 --- a/src/client/informationdialog/informationdialog.cpp +++ b/src/client/informationdialog/informationdialog.cpp @@ -2,7 +2,8 @@ #include #include -InformationDialog::InformationDialog() : QDialog() { +InformationDialog::InformationDialog() : QDialog() +{ /* widgets */ _lblTitle = new QLabel(tr("

system information

")); @@ -23,12 +24,13 @@ InformationDialog::InformationDialog() : QDialog() { qDebug() << "create information dialog"; } -void InformationDialog::initTable() { +void InformationDialog::initTable() +{ /* NETWORK*/ /* hostnames */ _tableLayout->addRow(new QLabel(tr("hostname")), new QLabel(QHostInfo::localHostName())); /* ips */ - for (QHostAddress a: QNetworkInterface::allAddresses()) { + for (QHostAddress a : QNetworkInterface::allAddresses()) { QString ip = a.toString(); if (ip == "::1" || ip == "127.0.0.1") { continue;} diff --git a/src/client/informationdialog/informationdialog.h b/src/client/informationdialog/informationdialog.h index 6bbf41c..f1a32a5 100644 --- a/src/client/informationdialog/informationdialog.h +++ b/src/client/informationdialog/informationdialog.h @@ -8,9 +8,10 @@ #include -class InformationDialog : public QDialog { +class InformationDialog : public QDialog +{ - private: +private: QLayout* _layout; QFormLayout* _tableLayout; QLabel* _lblTitle; @@ -18,7 +19,7 @@ class InformationDialog : public QDialog { void initTable(); - public: +public: InformationDialog(); }; diff --git a/src/client/main.cpp b/src/client/main.cpp index d0c6bd9..61ca0e9 100644 --- a/src/client/main.cpp +++ b/src/client/main.cpp @@ -8,20 +8,20 @@ int main(int argc, char** argv) { - ClientApp app(argc, argv); - qsrand((uint)QDateTime::currentMSecsSinceEpoch()); + ClientApp app(argc, argv); + qsrand((uint)QDateTime::currentMSecsSinceEpoch()); - /* here we handle the arguments that were not handled by ClientApp */ - for (QString a : app.arguments()) { - if (a == "--usage" || a == "--help") { - qStdout() << "Usage: pvsclient [--exam-mode] [--auto|--session=xxx|\"\"]" << endl; - exit(0); - } else if (a.contains("pvsclient")) { - /* do nothing */ - } else { - qStdout() << "Unknown argument: " << a << endl; - exit(1); - } - } - return app.exec(); + /* here we handle the arguments that were not handled by ClientApp */ + for (QString a : app.arguments()) { + if (a == "--usage" || a == "--help") { + qStdout() << "Usage: pvsclient [--exam-mode] [--auto|--session=xxx|\"\"]" << endl; + exit(0); + } else if (a.contains("pvsclient")) { + /* do nothing */ + } else { + qStdout() << "Unknown argument: " << a << endl; + exit(1); + } + } + return app.exec(); } diff --git a/src/client/net/serverconnection.cpp b/src/client/net/serverconnection.cpp index f4a6fd6..5c812d5 100644 --- a/src/client/net/serverconnection.cpp +++ b/src/client/net/serverconnection.cpp @@ -24,17 +24,17 @@ 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 &)), - this, - SLOT(sslErrors(const QList &)) - ); - qDebug("Connecting to %s on port %d", host.toUtf8().data(), (int)port); - _socket->connectToHostEncrypted(host, port); + 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 &)), + this, + SLOT(sslErrors(const QList &)) + ); + qDebug("Connecting to %s on port %d", host.toUtf8().data(), (int)port); + _socket->connectToHostEncrypted(host, port); _timerId = startTimer(4000); _lastData = QDateTime::currentMSecsSinceEpoch() + PING_TIMEOUT_MS; _timerConnectionCheck = startTimer(5000); @@ -44,8 +44,7 @@ ServerConnection::ServerConnection(const QString& host, const quint16 port, cons ServerConnection::~ServerConnection() { - if (_socket != NULL) - { + if (_socket != NULL) { qCritical("**** SOCKET DELETE IN DESTRUCTOR"); _socket->deleteLater(); } @@ -62,8 +61,7 @@ void ServerConnection::sendMessage(NetworkMessage& message) if (_socket == NULL || _socket->state() != QAbstractSocket::ConnectedState) return; message.writeMessage(_socket); - if (!message.writeComplete()) - { + if (!message.writeComplete()) { qCritical() << "SendMessage to server failed!"; } } @@ -75,15 +73,13 @@ void ServerConnection::sendMessage(NetworkMessage& message) */ void ServerConnection::disconnectFromServer() { - if (_timerDelete == 0) - { + if (_timerDelete == 0) { VncServer::instance()->stop(); emit closeVnc(); emit disconnected(); _timerDelete = startTimer(500); qDebug("Closing connection to server"); - if (_socket != NULL) - { + if (_socket != NULL) { _socket->blockSignals(true); _socket->abort(); } @@ -100,10 +96,8 @@ void ServerConnection::handleMsg() _lastData = QDateTime::currentMSecsSinceEpoch() + PING_TIMEOUT_MS; const QString &id = _fromServer.getFieldString(_ID); - if (_authed == 0) - { - if (id == _CHALLENGE) - { + if (_authed == 0) { + if (id == _CHALLENGE) { // Initial challenge request by server emit stateChange(ConnectWindow::AwaitingChallengeResponse); _myChallenge.resize(CHALLENGE_LEN); @@ -121,21 +115,17 @@ void ServerConnection::handleMsg() return; } - if (_authed == 1) - { - if (id == _CHALLENGE) - { + if (_authed == 1) { + if (id == _CHALLENGE) { qDebug("Received challenge reply"); - if (_timerId != 0) - { + if (_timerId != 0) { killTimer(_timerId); _timerId = 0; } // Check challenge response QByteArray serverhash(_fromServer.getFieldBytes(_HASH)); if (serverhash != genSha1(&_sessionName, &_myChallenge) - && !_autoConnect) - { + && !_autoConnect) { qDebug("invalid. STOP."); emit stateChange(ConnectWindow::InvalidSslHash); this->disconnectFromServer(); @@ -157,23 +147,18 @@ void ServerConnection::handleMsg() _toServer.setField(_EXAMMODE, clientApp->isExamMode() ? __TRUE : __FALSE); /* TODO: (Question) Why is this here not using sendMessage() ? */ qDebug("Sending login request!"); - if (_toServer.writeMessage(_socket)) - { + if (_toServer.writeMessage(_socket)) { _authed = 2; qDebug("valid, step <- 2"); - } - else - { + } else { this->disconnectFromServer(); } } return; } - if (_authed == 2) - { - if (id == _LOGIN) - { + if (_authed == 2) { + if (id == _LOGIN) { qDebug("login accepted, step <- 3"); _authed = 3; emit stateChange(ConnectWindow::Connected); @@ -182,8 +167,7 @@ void ServerConnection::handleMsg() } // message THUMB - server requests screenshot as thumbnail - if (id == _THUMB) - { + if (id == _THUMB) { if (clientApp->isExamMode()) { QByteArray emptyArray; _toServer.setField(_ID, _THUMB); @@ -207,34 +191,31 @@ void ServerConnection::handleMsg() const QRect primaryRect = primary.screenGeometry(); QPixmap desktop( - QPixmap::grabWindow( - QApplication::desktop()->winId(), - primaryRect.x(), - primaryRect.y(), - primaryRect.width(), - primaryRect.height() - ).scaled( - x, y, - Qt::KeepAspectRatio, - Qt::SmoothTransformation)); + QPixmap::grabWindow( + QApplication::desktop()->winId(), + primaryRect.x(), + primaryRect.y(), + primaryRect.width(), + primaryRect.height() + ).scaled( + x, y, + Qt::KeepAspectRatio, + Qt::SmoothTransformation)); QByteArray bytes; QBuffer jpgBuffer(&bytes); jpgBuffer.open(QIODevice::WriteOnly); - if (desktop.save(&jpgBuffer, "JPG", _jpegQuality)) // writes pixmap into bytes in JPG format - { + if (desktop.save(&jpgBuffer, "JPG", _jpegQuality)) { // writes pixmap into bytes in JPG format // Try to adjust quality so we stay between 3 and 4.5 KB if (_jpegQuality < 90 && bytes.size() < 3000) _jpegQuality += 7; else if (_jpegQuality > 40 && bytes.size() > 4500) _jpegQuality -= 7; - } - else - { // FALLBACK + } else { + // FALLBACK bytes.clear(); QBuffer pngBuffer(&bytes); pngBuffer.open(QIODevice::WriteOnly); - if (!desktop.save(&pngBuffer, "PNG")) // writes pixmap into bytes in PNG format - { + if (!desktop.save(&pngBuffer, "PNG")) { // writes pixmap into bytes in PNG format qDebug("Could not convert screenshot to PNG nor JPG"); return; // Failed :-( } @@ -244,42 +225,31 @@ void ServerConnection::handleMsg() _toServer.setField(_IMG, bytes); sendMessage(_toServer); } // message VNCSERVER - start local vncserver - else if (id == _VNCSERVER) - { + else if (id == _VNCSERVER) { if (clientApp->isExamMode()) { qDebug() << "denied request for vnc server (exam mode)"; return; } const bool enable = (_fromServer.getFieldString("ENABLE").toInt() != 0); - if (enable) - { + if (enable) { emit closeVnc(); // In case we are watching some other client, stop doing so VncServer::instance()->start(); - } - else - { + } else { VncServer::instance()->stop(); } - } - else if (id == _VNCCLIENT) - { + } else if (id == _VNCCLIENT) { if (clientApp->isExamMode()) { qDebug() << "denied request for vnc projection (exam mode)"; return; } const QString host(_fromServer.getFieldString("HOST")); const int port = _fromServer.getFieldString("PORT").toInt(); - if (host.isEmpty() || port <= 0) - { + if (host.isEmpty() || port <= 0) { emit closeVnc(); - } - else - { + } else { emit openVnc(host, port, _fromServer.getFieldString("ROPASS"), true, true, _fromServer.getFieldString("CAPTION"), _fromServer.getFieldString("CLIENTID").toInt(), _fromServer.getFieldBytes(_THUMB)); } - } - else if (id == _LOCK) - { + } else if (id == _LOCK) { const bool enable = (_fromServer.getFieldString("ENABLE").toInt() != 0); if (enable) _blank->lock(_fromServer.getFieldString("MESSAGE")); @@ -294,24 +264,17 @@ void ServerConnection::handleMsg() void ServerConnection::timerEvent(QTimerEvent *event) { - if (event->timerId() == _timerConnectionCheck) - { - if (_lastData < QDateTime::currentMSecsSinceEpoch()) - { + if (event->timerId() == _timerConnectionCheck) { + if (_lastData < QDateTime::currentMSecsSinceEpoch()) { this->disconnectFromServer(); killTimer(_timerConnectionCheck); } - } - else if (event->timerId() == _timerId) - { + } else if (event->timerId() == _timerId) { killTimer(_timerId); _timerId = 0; this->disconnectFromServer(); - } - else if (event->timerId() == _timerDelete) - { - if (_socket == NULL || _socket->state() == QAbstractSocket::UnconnectedState) - { + } else if (event->timerId() == _timerDelete) { + if (_socket == NULL || _socket->state() == QAbstractSocket::UnconnectedState) { if (_socket != NULL) _socket->deleteLater(); _socket = NULL; @@ -321,8 +284,7 @@ void ServerConnection::timerEvent(QTimerEvent *event) } _socket->abort(); qDebug("A socket is still pending..."); - } - else + } else killTimer(event->timerId()); } @@ -339,12 +301,9 @@ void ServerConnection::onVncServerStartStop(int port, QString& ropass, QString& { _toServer.reset(); _toServer.setField(_ID, _VNCSERVER); - if (port <= 0) - { + if (port <= 0) { _toServer.setField("PORT", QByteArray("0")); - } - else - { + } else { _toServer.setField("PORT", QString::number(port)); _toServer.setField("ROPASS", ropass); _toServer.setField("RWPASS", rwpass); @@ -374,8 +333,7 @@ void ServerConnection::onVncViewerStartStop(const bool started, const int client */ void ServerConnection::sslErrors(const QList & errors) { - for (QList::const_iterator it = errors.begin(); it != errors.end(); it++) - { + for (QList::const_iterator it = errors.begin(); it != errors.end(); it++) { QSslError err = *it; qDebug("Connect SSL: %s", qPrintable(err.errorString())); if (err.error() == QSslError::HostNameMismatch) @@ -392,25 +350,21 @@ void ServerConnection::sslErrors(const QList & errors) void ServerConnection::sock_dataArrival() { - if (_socket == NULL || _socket->state() != QAbstractSocket::ConnectedState) - { + if (_socket == NULL || _socket->state() != QAbstractSocket::ConnectedState) { qDebug("dataArrival called in bad state"); return; } - while (_socket->bytesAvailable() > 0) - { + while (_socket->bytesAvailable() > 0) { bool retval; retval = _fromServer.readMessage(_socket); // let the message read data from socket - if (retval == NM_READ_FAILED) // error parsing msg, disconnect client! - { + if (retval == NM_READ_FAILED) { // error parsing msg, disconnect client! this->disconnectFromServer(); return; } if (retval == NM_READ_INCOMPLETE) return; - if (_fromServer.readComplete()) // message is complete - { + if (_fromServer.readComplete()) { // message is complete this->handleMsg(); if (_socket == NULL) return; @@ -435,9 +389,8 @@ void ServerConnection::sock_error(QAbstractSocket::SocketError errcode) void ServerConnection::sock_connected() { - QByteArray cert(_socket->peerCertificate().digest(QCryptographicHash::Sha1)); - if (_certHash != cert) - { + QByteArray cert(_socket->peerCertificate().digest(QCryptographicHash::Sha1)); + if (_certHash != cert) { emit stateChange(ConnectWindow::InvalidCert); this->disconnectFromServer(); return; diff --git a/src/client/net/serverconnection.h b/src/client/net/serverconnection.h index 5e2631f..aa1d0b4 100644 --- a/src/client/net/serverconnection.h +++ b/src/client/net/serverconnection.h @@ -9,7 +9,7 @@ class BlankScreen; class ServerConnection : public QObject { -Q_OBJECT + Q_OBJECT private: QSslSocket *_socket; diff --git a/src/client/net/serverdiscovery.cpp b/src/client/net/serverdiscovery.cpp index 1d1e891..4a69e91 100644 --- a/src/client/net/serverdiscovery.cpp +++ b/src/client/net/serverdiscovery.cpp @@ -12,16 +12,15 @@ */ ServerDiscovery::ServerDiscovery(QObject *parent) : QObject(parent), - _minDiscoveryInterval(500), - _maxDiscoveryInterval(5000) + _minDiscoveryInterval(500), + _maxDiscoveryInterval(5000) { _hashErrorCount = 0; _ipErrorCount = 0; /* Try to get a UDP port for server discovery */ int tries = 10; - while (tries-- != 0) - { + while (tries-- != 0) { const quint16 port = (quint16)(qrand() % 10000) + 10000; if (_discoverySocket.bind(QHostAddress::Any, port)) break; @@ -109,19 +108,14 @@ void ServerDiscovery::doDiscovery() _packet.setField(_IPLIST, iplist); // Check if specifig manager IP is given. If not broadcast in whole network. - if (_mgrIP != QHostAddress::Null) - { + if (_mgrIP != QHostAddress::Null) { qDebug() << "Broadcasting to " << _mgrIP.toString(); if (!_packet.writeMessage(&_discoverySocket, _mgrIP, SERVICE_DISCOVERY_PORT)) qDebug("Failed"); - } else - { - foreach (QNetworkInterface interface, QNetworkInterface::allInterfaces()) - { - foreach (QNetworkAddressEntry entry, interface.addressEntries()) - { - if (!entry.broadcast().isNull() && entry.ip() != QHostAddress::LocalHost && entry.ip() != QHostAddress::LocalHostIPv6) - { + } else { + foreach (QNetworkInterface interface, QNetworkInterface::allInterfaces()) { + foreach (QNetworkAddressEntry entry, interface.addressEntries()) { + if (!entry.broadcast().isNull() && entry.ip() != QHostAddress::LocalHost && entry.ip() != QHostAddress::LocalHostIPv6) { qDebug() << "Broadcasting to " << entry.broadcast().toString(); if (!_packet.writeMessage(&_discoverySocket, entry.broadcast(), SERVICE_DISCOVERY_PORT)) qDebug("FAILED"); @@ -148,10 +142,9 @@ void ServerDiscovery::onUdpReadyRead() char data[UDPBUFSIZ]; QHostAddress addr; quint16 port; - while (_discoverySocket.hasPendingDatagrams()) - { + while (_discoverySocket.hasPendingDatagrams()) { // Discard any packets if discovery is stopped - if (!this->isActive()){ + if (!this->isActive()) { _discoverySocket.readDatagram(NULL, 0); continue; } @@ -171,16 +164,14 @@ void ServerDiscovery::onUdpReadyRead() const QByteArray cert(_packet.getFieldBytes(_CERT)); // Check if the source IP of the packet matches any of the addresses given in the IP list - if (!Network::isAddressInList(QString::fromUtf8(iplist), addr.toString())) - { + if (!Network::isAddressInList(QString::fromUtf8(iplist), addr.toString())) { ++_ipErrorCount; emit error(ErrorType::InvalidIpList, _hashErrorCount); continue; } // If so, check if the submitted hash seems valid - if (genSha1(&_nameBytes, &_salt2, &iplist, &port, &cert) != hash && _mgrIP != addr) - { + if (genSha1(&_nameBytes, &_salt2, &iplist, &port, &cert) != hash && _mgrIP != addr) { // did not match local session name, or other data was spoofed ++_hashErrorCount; emit error(ErrorType::InvalidHash, _ipErrorCount); @@ -189,7 +180,7 @@ void ServerDiscovery::onUdpReadyRead() /* Otherwise it's a valid reply */ qDebug() << "Server detected:" - << addr.toString() + ":" + QString::fromUtf8(port) + "/" + _nameBytes; + << addr.toString() + ":" + QString::fromUtf8(port) + "/" + _nameBytes; // Tell that a server hs been found emit serverDetected(addr.toString(), (quint16)QString::fromUtf8(port).toInt(), _nameBytes, cert, (_mgrIP == addr)); diff --git a/src/client/net/serverdiscovery.h b/src/client/net/serverdiscovery.h index a41c946..d7d6010 100644 --- a/src/client/net/serverdiscovery.h +++ b/src/client/net/serverdiscovery.h @@ -8,46 +8,47 @@ class ServerDiscovery : public QObject { - Q_OBJECT - - public: - enum class ErrorType{ - InvalidIpList, - InvalidHash - }; - - explicit ServerDiscovery(QObject *parent = 0); - ~ServerDiscovery(); - - void start(const QByteArray& sessionName, QString mgrIP); - void stop(); - inline bool isActive(){ return _discoveryTimer.isActive(); } - - private: - QTimer _discoveryTimer; - const int _minDiscoveryInterval; - const int _maxDiscoveryInterval; - int _hashErrorCount; - int _ipErrorCount; - QByteArray _nameBytes; - QByteArray _salt2; - QUdpSocket _discoverySocket; - NetworkMessage _packet; - - QHostAddress _mgrIP; - - static const int UDPBUFSIZ = 9000; - static const int SALT_LEN = 18; - - signals: - void serverDetected(const QString& host, const quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect); - void error(ErrorType e, int count); - - public slots: - - private slots: - void doDiscovery(); - void onUdpReadyRead(); + Q_OBJECT + +public: + enum class ErrorType + { + InvalidIpList, + InvalidHash + }; + + explicit ServerDiscovery(QObject *parent = 0); + ~ServerDiscovery(); + + void start(const QByteArray& sessionName, QString mgrIP); + void stop(); + inline bool isActive() { return _discoveryTimer.isActive(); } + +private: + QTimer _discoveryTimer; + const int _minDiscoveryInterval; + const int _maxDiscoveryInterval; + int _hashErrorCount; + int _ipErrorCount; + QByteArray _nameBytes; + QByteArray _salt2; + QUdpSocket _discoverySocket; + NetworkMessage _packet; + + QHostAddress _mgrIP; + + static const int UDPBUFSIZ = 9000; + static const int SALT_LEN = 18; + +signals: + void serverDetected(const QString& host, const quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect); + void error(ErrorType e, int count); + +public slots: + +private slots: + void doDiscovery(); + void onUdpReadyRead(); }; diff --git a/src/client/toolbar/toolbar.cpp b/src/client/toolbar/toolbar.cpp index 0b97f31..724836f 100644 --- a/src/client/toolbar/toolbar.cpp +++ b/src/client/toolbar/toolbar.cpp @@ -78,7 +78,8 @@ Toolbar::Toolbar(QWidget *parent) { init(); } -void Toolbar::exit() { +void Toolbar::exit() +{ this->close(); this->deleteLater(); qApp->quit(); @@ -90,7 +91,7 @@ void Toolbar::init() /* Initialize the GUI */ _ui->setupUi(this); - _onWorkspace2 = false; + _onWorkspace2 = false; /* Set window properties */ setWindowFlags(Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint | Qt::FramelessWindowHint); @@ -102,27 +103,27 @@ void Toolbar::init() /* Create the connect window */ _connectWindow = new ConnectWindow(NULL); - _connectWindow->setAvailableRooms(myRooms()); + _connectWindow->setAvailableRooms(myRooms()); // Connect the signals connect(_connectWindow, SIGNAL(disconnect()), this, SLOT(onDoDisconnect())); connect(_connectWindow, SIGNAL(connected(ServerConnection*)), this, SLOT(onConnected(ServerConnection*))); - /* Setup menu */ - initMenu(); + /* Setup menu */ + initMenu(); - /* setup manager button */ - _isManagerPc = isManagerPc(); - _ui->btnManager->setVisible(_isManagerPc); - connect(_ui->btnManager, SIGNAL(clicked()), this, SLOT(onBtnManager())); + /* setup manager button */ + _isManagerPc = isManagerPc(); + _ui->btnManager->setVisible(_isManagerPc); + connect(_ui->btnManager, SIGNAL(clicked()), this, SLOT(onBtnManager())); - /* setup lock desktop button*/ + /* setup lock desktop button*/ SYSTEM_SETTINGS(conf); - bool showLock = conf.value("showLockDesktopButton").toBool(); - if (showLock) { - connect(_ui->btnLockDesktop, SIGNAL(clicked()), this, SLOT(onBtnLockDesktop())); - } else { - _ui->btnLockDesktop->setVisible(false); - } + bool showLock = conf.value("showLockDesktopButton").toBool(); + if (showLock) { + connect(_ui->btnLockDesktop, SIGNAL(clicked()), this, SLOT(onBtnLockDesktop())); + } else { + _ui->btnLockDesktop->setVisible(false); + } /* Connect the signals from vnc server */ connect(VncServer::instance(), SIGNAL(started(int, QString&, QString&)), this, SLOT(onVncServerIsRunning(int))); @@ -130,7 +131,7 @@ void Toolbar::init() /* Set position */ const QDesktopWidget desktop; const QRect primaryScreen = desktop.screenGeometry(); - move(primaryScreen.left() + (primaryScreen.width() - this->width())/2 , primaryScreen.top()); + move(primaryScreen.left() + (primaryScreen.width() - this->width()) / 2 , primaryScreen.top()); /* Setup hide timer */ _hideTimer.setInterval(500); @@ -149,16 +150,17 @@ void Toolbar::init() * This function should be called once from the main init() function which in * turn should only be called by the constructor. **/ -void Toolbar::initMenu() { +void Toolbar::initMenu() +{ _menu = new QMenu(this); _acnConnect = new QAction(tr("&Connect..."), this); - _acnDisconnect = new QAction(tr("&Disconnect"), this); - _acnDisconnect->setEnabled(false); + _acnDisconnect = new QAction(tr("&Disconnect"), this); + _acnDisconnect->setEnabled(false); _acnInformation = new QAction(tr("&Information..."), this); - _acnAbout= new QAction(tr("&What's this?"), this); + _acnAbout = new QAction(tr("&What's this?"), this); _acnQuit = new QAction(tr("&Quit"), this); - _menu->addAction(_acnConnect); + _menu->addAction(_acnConnect); _menu->addAction(_acnDisconnect); _menu->addSeparator(); _menu->addAction(_acnInformation); @@ -167,16 +169,16 @@ void Toolbar::initMenu() { _menu->addAction(_acnQuit); _ui->cmdMenu->setMenu(_menu); - /* only add a "quit"-button when the configuration allows it. */ + /* only add a "quit"-button when the configuration allows it. */ SYSTEM_SETTINGS(conf); - bool allow = conf.value("allowClientQuit").toBool(); - _acnQuit->setVisible(allow); + bool allow = conf.value("allowClientQuit").toBool(); + _acnQuit->setVisible(allow); // Connect the signals connect(_menu, SIGNAL(aboutToHide()), this, SLOT(hideBar())); connect(_acnConnect, SIGNAL(triggered()), _connectWindow, SLOT(doShow())); - connect(_acnDisconnect, SIGNAL(triggered()), _connectWindow, SLOT(DoDisconnect())); + connect(_acnDisconnect, SIGNAL(triggered()), _connectWindow, SLOT(DoDisconnect())); connect(_acnInformation, SIGNAL(triggered()), this, SLOT(showInformationDialog())); connect(_acnAbout, SIGNAL(triggered()), this, SLOT(showAboutDialog())); connect(_acnQuit, SIGNAL(triggered()), this, SLOT(exit())); @@ -232,82 +234,85 @@ void Toolbar::enterEvent(QEvent* e) /* returns true when the pc of this client is also eligible to be a manager */ -bool Toolbar::isManagerPc(){ - QList myRooms; +bool Toolbar::isManagerPc() +{ + QList myRooms; SYSTEM_SETTINGS(conf); QStringList roomNames = conf.value("rooms").toStringList(); - /* go through all rooms and check if this client is a manager of the room. */ + /* go through all rooms and check if this client is a manager of the room. */ for (auto roomName : roomNames) { conf.beginGroup(roomName); - QString mgrIP = conf.value("mgrIP").toString(); + QString mgrIP = conf.value("mgrIP").toString(); - foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { - QString ip = conf.value("ip").toString(); - if (address.toString() == mgrIP) { - return true; - } + foreach (const QHostAddress & address, QNetworkInterface::allAddresses()) { + QString ip = conf.value("ip").toString(); + if (address.toString() == mgrIP) { + return true; + } } conf.endGroup(); } - return false; + return false; } /* returns a sorted list of available rooms. * (Available means that this client is configured to be in that room) */ -QList Toolbar::myRooms() { +QList Toolbar::myRooms() +{ - QList myRooms; + QList myRooms; SYSTEM_SETTINGS(conf); if (!conf.contains("rooms")) { qDebug() << "Invalid config file!"; - return myRooms; + return myRooms; } QStringList roomNames = conf.value("rooms").toStringList(); - /* go through all rooms and check if this client is a member of the room. */ + /* go through all rooms and check if this client is a member of the room. */ for (auto roomName : roomNames) { conf.beginGroup(roomName); if (!conf.contains("mgrIP")) { qDebug() << "Invalid config file!"; return myRooms; } - QString mgrIP = conf.value("mgrIP").toString(); - int priority = conf.value("priority").toInt(); + QString mgrIP = conf.value("mgrIP").toString(); + int priority = conf.value("priority").toInt(); - foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { + foreach (const QHostAddress & address, QNetworkInterface::allAddresses()) { int size = conf.beginReadArray("client"); for (int j = 0; j < size; ++j) { conf.setArrayIndex(j); QString ip = conf.value("ip").toString(); if (address != QHostAddress(QHostAddress::LocalHost) - && ip == address.toString() ) { - /* add this room to the list */ - Room r(roomName, mgrIP, priority); - myRooms << r; - break; + && ip == address.toString() ) { + /* add this room to the list */ + Room r(roomName, mgrIP, priority); + myRooms << r; + break; } } conf.endArray(); } conf.endGroup(); } - /* sort */ - qStableSort(myRooms.begin(), myRooms.end(), qGreater()); - return myRooms; + /* sort */ + qStableSort(myRooms.begin(), myRooms.end(), qGreater()); + return myRooms; } /** Identifies the responsible manager for this client by searching through the * configuration file. The manager whose room has the highest priority is chosen. */ -QString Toolbar::identifyMgrIP() { - QList rooms = myRooms(); - if (!rooms.empty()) { - return rooms.first().mgr; - } else { - return ""; - } +QString Toolbar::identifyMgrIP() +{ + QList rooms = myRooms(); + if (!rooms.empty()) { + return rooms.first().mgr; + } else { + return ""; + } } /* @@ -321,13 +326,10 @@ QString Toolbar::identifyMgrIP() { void Toolbar::cameraBlink() { static bool showEye = false; - if (!showEye) - { + if (!showEye) { _ui->icon_cam->setPixmap(_beWatchedEye); showEye = true; - } - else - { + } else { _ui->icon_cam->setPixmap(QPixmap()); // set empty pixmap for blinking effect showEye = false; } @@ -358,15 +360,16 @@ void Toolbar::onVncServerIsRunning(int port) * A slot for the onDisconnected signal of the ConnectWindow. This slot will * change the UI according to the state fo the connection. */ -void Toolbar::onDisconnected() { +void Toolbar::onDisconnected() +{ if (_connection != NULL) _connection->blockSignals(true); _connection = NULL; _ui->lblStatus->setStyleSheet("color:red"); _ui->lblStatus->setText(tr("Offline")); - this->_acnConnect->setEnabled(true); - this->_acnDisconnect->setEnabled(false); + this->_acnConnect->setEnabled(true); + this->_acnDisconnect->setEnabled(false); } /***************************************************************************//** @@ -377,15 +380,14 @@ void Toolbar::onDisconnected() { */ void Toolbar::onConnected(ServerConnection* connection) { - this->_acnConnect->setEnabled(false); - this->_acnDisconnect->setEnabled(true); + this->_acnConnect->setEnabled(false); + this->_acnDisconnect->setEnabled(true); _ui->lblStatus->setStyleSheet("color:green"); _ui->lblStatus->setText(tr("Online")); // - if (_connection != NULL) - { + if (_connection != NULL) { disconnect(_connection, SIGNAL(disconnected()), this, SLOT(onDisconnected())); _connection->blockSignals(true); _connection->disconnectFromServer(); @@ -393,7 +395,7 @@ void Toolbar::onConnected(ServerConnection* connection) _connection = connection; connect(_connection, SIGNAL(disconnected()), this, SLOT(onDisconnected())); 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&))); + _vnc, SLOT(open(const QString&, int, const QString&, bool, bool, const QString&, const int, const QByteArray&))); connect(_connection, SIGNAL(closeVnc()), _vnc, SLOT(close())); connect(_vnc, SIGNAL(running(const bool, const int)), _connection, SLOT(onVncViewerStartStop(const bool, const int))); } @@ -427,20 +429,21 @@ void Toolbar::hideBar() void Toolbar::showAboutDialog() { QMessageBox msgBox( - QMessageBox::NoIcon, - tr("About PVS Client"), - tr("The PVS - client is part of a software system for managing the "\ - "virtual data traffic within the computer pools, between the tutor's "\ - "and student's PCs. It has been developed to simplify the information "\ - "traffic in seminars and general eLearning."), - QMessageBox::NoButton, - this, - Qt::Dialog|Qt::MSWindowsFixedSizeDialogHint|Qt::WindowStaysOnTopHint); - msgBox.setIconPixmap(QIcon(":cam32.svg").pixmap(64,64)); + QMessageBox::NoIcon, + tr("About PVS Client"), + tr("The PVS - client is part of a software system for managing the "\ + "virtual data traffic within the computer pools, between the tutor's "\ + "and student's PCs. It has been developed to simplify the information "\ + "traffic in seminars and general eLearning."), + QMessageBox::NoButton, + this, + Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint); + msgBox.setIconPixmap(QIcon(":cam32.svg").pixmap(64, 64)); msgBox.exec(); } -void Toolbar::showInformationDialog() { +void Toolbar::showInformationDialog() +{ InformationDialog* d = new InformationDialog(); d->exec(); } @@ -454,19 +457,21 @@ void Toolbar::showBar() move(x(), primaryScreen.top()); } /** call script to switch to workspace of the manager */ -void Toolbar::onBtnManager() { - QProcess switchP; - if (_onWorkspace2) { - switchP.start("/bin/sh", QStringList() << "/opt/openslx/pvs2/switchBack.sh"); - } else { - switchP.start("/bin/sh", QStringList() << "/opt/openslx/pvs2/switchToManager.sh"); - } - _ui->btnManager->setDown(_onWorkspace2); - _onWorkspace2 = !_onWorkspace2; - switchP.waitForFinished(); +void Toolbar::onBtnManager() +{ + QProcess switchP; + if (_onWorkspace2) { + switchP.start("/bin/sh", QStringList() << "/opt/openslx/pvs2/switchBack.sh"); + } else { + switchP.start("/bin/sh", QStringList() << "/opt/openslx/pvs2/switchToManager.sh"); + } + _ui->btnManager->setDown(_onWorkspace2); + _onWorkspace2 = !_onWorkspace2; + switchP.waitForFinished(); } -void Toolbar::onBtnLockDesktop() { +void Toolbar::onBtnLockDesktop() +{ qDebug() << "onBtnLockDesktop()"; if (this->lockDesktopP.state() == QProcess::NotRunning) { _ui->btnLockDesktop->setEnabled(false); @@ -479,7 +484,8 @@ void Toolbar::onBtnLockDesktop() { } } -void Toolbar::enableLockBtn() { +void Toolbar::enableLockBtn() +{ _ui->btnLockDesktop->setEnabled(true); } diff --git a/src/client/toolbar/toolbar.h b/src/client/toolbar/toolbar.h index fe2eb0b..eb05f5f 100644 --- a/src/client/toolbar/toolbar.h +++ b/src/client/toolbar/toolbar.h @@ -23,7 +23,8 @@ class ConnectWindow; class BlankScreen; -namespace Ui{ +namespace Ui +{ class Toolbar; } @@ -50,17 +51,17 @@ private: ServerConnection *_connection; QTimer _blinkTimer; VncWindow *_vnc; - bool _onWorkspace2; - bool _isManagerPc; + bool _onWorkspace2; + bool _isManagerPc; const QPixmap _cam32, _beWatchedEye; void leaveEvent(QEvent* e); void enterEvent(QEvent* e); - QList myRooms(); - bool isManagerPc(); + QList myRooms(); + bool isManagerPc(); QString identifyMgrIP(); void init(); - void initMenu(); + void initMenu(); QProcess lockDesktopP; @@ -69,8 +70,8 @@ private slots: void onDisconnected(); void onConnected(ServerConnection* connection); void onDoDisconnect(); - void onBtnManager(); - void onBtnLockDesktop(); + void onBtnManager(); + void onBtnLockDesktop(); void exit(); void cameraBlink(); void showBar(); diff --git a/src/client/util/platform/blankscreen.h b/src/client/util/platform/blankscreen.h old mode 100755 new mode 100644 index e42043c..35cf297 --- a/src/client/util/platform/blankscreen.h +++ b/src/client/util/platform/blankscreen.h @@ -11,16 +11,16 @@ class BlankScreen : public QDialog { Q_OBJECT public: - BlankScreen(); - virtual ~BlankScreen(); - void draw(bool force = false); - bool lock(const QString& message); - bool unlock(); + BlankScreen(); + virtual ~BlankScreen(); + void draw(bool force = false); + bool lock(const QString& message); + bool unlock(); private: - bool _locked; - QString _message; - BlankScreen_Sysdep* _sysdep; + bool _locked; + QString _message; + BlankScreen_Sysdep* _sysdep; }; #endif diff --git a/src/client/util/platform/blankscreen_Win32.cpp b/src/client/util/platform/blankscreen_Win32.cpp old mode 100755 new mode 100644 index 2bba1cf..1d1dd12 --- a/src/client/util/platform/blankscreen_Win32.cpp +++ b/src/client/util/platform/blankscreen_Win32.cpp @@ -1,41 +1,41 @@ - -#include "blankscreen.h" -#include - -struct BlankScreen_Sysdep { - - bool locked; - QWidget* blankwin; - - QString lockMsg; - int blackColor, whiteColor; - int offX, offY; -}; - -BlankScreen::BlankScreen() -{ - _sysdep = new BlankScreen_Sysdep; - _sysdep->blankwin = new QWidget(0, Qt::X11BypassWindowManagerHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); - _sysdep->blankwin->setWindowState(Qt::WindowFullScreen); - _sysdep->blankwin->show(); -} - -BlankScreen::~BlankScreen() -{ - delete _sysdep; -} - -void BlankScreen::draw(bool force) -{ - -} - -bool BlankScreen::lock(const QString& message) -{ - return true; -} - -bool BlankScreen::unlock() -{ - return true; -} + +#include "blankscreen.h" +#include + +struct BlankScreen_Sysdep { + + bool locked; + QWidget* blankwin; + + QString lockMsg; + int blackColor, whiteColor; + int offX, offY; +}; + +BlankScreen::BlankScreen() +{ + _sysdep = new BlankScreen_Sysdep; + _sysdep->blankwin = new QWidget(0, Qt::X11BypassWindowManagerHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); + _sysdep->blankwin->setWindowState(Qt::WindowFullScreen); + _sysdep->blankwin->show(); +} + +BlankScreen::~BlankScreen() +{ + delete _sysdep; +} + +void BlankScreen::draw(bool force) +{ + +} + +bool BlankScreen::lock(const QString& message) +{ + return true; +} + +bool BlankScreen::unlock() +{ + return true; +} diff --git a/src/client/util/platform/blankscreen_X11.cpp b/src/client/util/platform/blankscreen_X11.cpp old mode 100755 new mode 100644 index db8873b..66c9f1f --- a/src/client/util/platform/blankscreen_X11.cpp +++ b/src/client/util/platform/blankscreen_X11.cpp @@ -11,8 +11,7 @@ #include #include -struct BlankScreen_Sysdep -{ +struct BlankScreen_Sysdep { Display *dpy; }; @@ -55,9 +54,9 @@ bool BlankScreen::lock(const QString& message) XGrabPointer(_sysdep->dpy, DefaultRootWindow(_sysdep->dpy) , false, 0, GrabModeAsync, GrabModeAsync, None, 0, CurrentTime); - QProcess ungrabP; - ungrabP.start("/bin/bash", QStringList() << "/opt/openslx/pvs2/kb-lock.sh"); - ungrabP.waitForFinished(); + QProcess ungrabP; + ungrabP.start("/bin/bash", QStringList() << "/opt/openslx/pvs2/kb-lock.sh"); + ungrabP.waitForFinished(); _locked = true; return true; @@ -77,10 +76,10 @@ bool BlankScreen::unlock() XFlush(_sysdep->dpy); - /* start the kb-unlock.sh script */ - QProcess regrabP; - regrabP.start("/bin/bash", QStringList() << "/opt/openslx/pvs2/kb-unlock.sh"); - regrabP.waitForFinished(); + /* start the kb-unlock.sh script */ + QProcess regrabP; + regrabP.start("/bin/bash", QStringList() << "/opt/openslx/pvs2/kb-unlock.sh"); + regrabP.waitForFinished(); _locked = false; return true; diff --git a/src/client/util/room.h b/src/client/util/room.h index bfc70d0..86939f7 100644 --- a/src/client/util/room.h +++ b/src/client/util/room.h @@ -2,22 +2,25 @@ #define ROOM_H struct Room { - QString mgr; - QString name; - int priority; - Room (QString _name, QString _mgr, int _priority) { - mgr = _mgr; - name = _name; - priority = _priority; - }; + QString mgr; + QString name; + int priority; + Room (QString _name, QString _mgr, int _priority) + { + mgr = _mgr; + name = _name; + priority = _priority; + }; }; -inline QDebug operator<<(QDebug debug, const Room& r) { - debug << r.name << "{mgr=" << r.mgr << ",prio=" << r.priority << "}"; - return debug; +inline QDebug operator<<(QDebug debug, const Room& r) +{ + debug << r.name << "{mgr=" << r.mgr << ",prio=" << r.priority << "}"; + return debug; } -inline bool operator<(const Room& a, const Room& b) { - return a.priority < b.priority; +inline bool operator<(const Room& a, const Room& b) +{ + return a.priority < b.priority; } #endif diff --git a/src/client/util/util.h b/src/client/util/util.h index b47d3b1..dc604e8 100644 --- a/src/client/util/util.h +++ b/src/client/util/util.h @@ -26,8 +26,8 @@ QDir settingsDir(); inline QTextStream& qStdout() { - static QTextStream r{stdout}; - return r; + static QTextStream r {stdout}; + return r; } diff --git a/src/client/vnc/vncserver.cpp b/src/client/vnc/vncserver.cpp index aa7a89e..9d647f0 100644 --- a/src/client/vnc/vncserver.cpp +++ b/src/client/vnc/vncserver.cpp @@ -41,20 +41,19 @@ static QString makePassword(int len = 10) /***************************************************************************//** * @brief Ugly hack to get an el-cheapo platform independent sleep */ -struct Sleeper : public QThread -{ +struct Sleeper : public QThread { static void msleep(unsigned long msecs) { QThread::msleep(msecs); } }; /***************************************************************************//** * @brief VncServer::VncServer */ -VncServer::VncServer() : _process(NULL), _port(0), _timerId(0){} +VncServer::VncServer() : _process(NULL), _port(0), _timerId(0) {} /***************************************************************************//** * @brief VncServer::~VncServer */ -VncServer::~VncServer(){} +VncServer::~VncServer() {} /***************************************************************************//** * @brief VncServer::start @@ -62,8 +61,7 @@ VncServer::~VncServer(){} void VncServer::start() { // Keep things clean - if (_process != NULL) - { + if (_process != NULL) { disconnect(_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onError(QProcess::ProcessError))); disconnect(_process, SIGNAL(finished(int)), this, SLOT(onFinished(int))); } @@ -77,8 +75,7 @@ void VncServer::start() QFile pwhandle(pwfile); if (pwhandle.exists()) pwhandle.remove(); - if (!pwhandle.open(QIODevice::WriteOnly)) - { + if (!pwhandle.open(QIODevice::WriteOnly)) { qDebug() << "Could not open " << pwfile << " for writing"; emit started(0, _ropass, _rwpass); return; @@ -112,9 +109,9 @@ void VncServer::start() args << "-clip"; QString rect; rect = QString::number(primaryRect.width()) - + "x" + QString::number(primaryRect.height()) - + "+" + QString::number(primaryRect.x()) - + "+" + QString::number(primaryRect.y()); + + "x" + QString::number(primaryRect.height()) + + "+" + QString::number(primaryRect.x()) + + "+" + QString::number(primaryRect.y()); args << rect; qDebug() << "Arguments are: " << args; @@ -126,8 +123,7 @@ void VncServer::start() */ void VncServer::stop() { - if (_timerId != 0) - { + if (_timerId != 0) { killTimer(_timerId); _timerId = 0; } @@ -178,24 +174,20 @@ void VncServer::timerEvent(QTimerEvent *event) */ void VncServer::onStdOut() { - if (_process == NULL) - { + if (_process == NULL) { qDebug("VncServer::onStdOut() called in bad state."); return; } QByteArray data(_process->readAllStandardOutput()); qDebug() << "x11vnc: " << data; - if (_port <= 0) - { + if (_port <= 0) { const int pos = data.indexOf("PORT=", 0); - if (pos != -1) - { + if (pos != -1) { _port = atoi(data.constData() + pos + 5); qDebug() << "Got VNC port " << _port << ", ro " << _ropass << ", rw " << _rwpass; emit started(_port, _ropass, _rwpass); // Kill error timer, but only if port seemed valid - if (_timerId != 0 && _port > 0) - { + if (_timerId != 0 && _port > 0) { killTimer(_timerId); _timerId = 0; } @@ -208,8 +200,7 @@ void VncServer::onStdOut() */ void VncServer::onStdErr() { - if (_process == NULL) - { + if (_process == NULL) { qDebug("VncServer::onStdErr() called in bad state."); return; } diff --git a/src/client/vnc/vncserver.h b/src/client/vnc/vncserver.h index ac45822..61e6d21 100644 --- a/src/client/vnc/vncserver.h +++ b/src/client/vnc/vncserver.h @@ -31,7 +31,7 @@ private: public: static VncServer *instance(); - inline bool isVncServerRunning(){ return _port > 0; } + inline bool isVncServerRunning() { return _port > 0; } void start(); void stop(); diff --git a/src/client/vnc/vncthread.cpp b/src/client/vnc/vncthread.cpp index dfa35af..b710a2c 100644 --- a/src/client/vnc/vncthread.cpp +++ b/src/client/vnc/vncthread.cpp @@ -62,8 +62,7 @@ VncThread::~VncThread() Q_ASSERT(_run == false); if (_frameBuffer) delete[] _frameBuffer; - if (_client != NULL) - { + if (_client != NULL) { if (_client->sock != -1) ::close(_client->sock); _client->sock = -1; @@ -134,7 +133,7 @@ void VncThread::run() { qDebug("[%s] VNC client started.", metaObject()->className()); qDebug("[%s] Host: '%s' Port: %i Passwd: '%s' Quality: %i", metaObject()->className(), qPrintable(_host), _port, - qPrintable(_passwd), _quality); + qPrintable(_passwd), _quality); // setup network for (int retry = 0; retry < 5 && _run; ++retry) { @@ -156,8 +155,7 @@ void VncThread::run() rfbClientSetClientData(_client, 0, this); // start client - if (rfbInitClient(_client, NULL, NULL)) - { + if (rfbInitClient(_client, NULL, NULL)) { break; // Success! } // Connection failed @@ -167,8 +165,7 @@ void VncThread::run() // error, let's try again this->msleep(10 + qrand() % 50); } - if(_client != NULL) - { + if (_client != NULL) { qDebug("[%s] Connection successful!", metaObject()->className()); int one = 1; setsockopt(_client->sock, SOL_TCP, TCP_NODELAY, &one, sizeof(one)); @@ -180,16 +177,14 @@ void VncThread::run() _connected = true; emit projectionStarted(); } - while (_run) - { + while (_run) { const int i = WaitForMessage(_client, 100 * 1000); // wait 100ms for message. returns -1 on error/disconnect, 0 if nothing happened, 1 if new data arrived if (i < 0) break; if (i > 0 && !HandleRFBServerMessage(_client)) break; - if (_hasNewLocalSize) - { + if (_hasNewLocalSize) { QMutexLocker lock(&_mutex); _hasNewLocalSize = false; _localSize = _newLocalSize; @@ -235,8 +230,7 @@ const QString VncThread::getDesktopName() const */ void VncThread::processImageUpdate(const int x, const int y, const int w, const int h) { - if (_srcStepX > 1 || _srcStepY > 1) - { + if (_srcStepX > 1 || _srcStepY > 1) { // Scaling is required as vnc server and client are using different resolutions // Calc section offsets first const int startX = x / _srcStepX; @@ -256,17 +250,14 @@ void VncThread::processImageUpdate(const int x, const int y, const int w, const // Rescale { QMutexLocker lock(&_mutex); - if (_painter != NULL) - { + if (_painter != NULL) { QImage scaled( - _img.copy(srcX, srcY, srcW, srcH).scaled(dstW, dstH, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + _img.copy(srcX, srcY, srcW, srcH).scaled(dstW, dstH, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); _painter->drawImage(dstX, dstY, scaled, 0, 0, dstW, dstH); } } emit imageUpdated(dstX, dstY, dstW, dstH); - } - else - { + } else { // Same resolution, nothing to do emit imageUpdated(x, y, w, h); } @@ -318,8 +309,7 @@ rfbBool VncThread::frameBufferHandler(rfbClient *client) client->format.blueMax = 0xff; const int quality = t->_quality; - switch (quality) - { + switch (quality) { case VncThread::HIGH: client->appData.useBGR233 = 0; client->appData.encodingsString = "copyrect zlib hextile raw"; diff --git a/src/client/vnc/vncthread.h b/src/client/vnc/vncthread.h index a5b52b1..a75ca0f 100644 --- a/src/client/vnc/vncthread.h +++ b/src/client/vnc/vncthread.h @@ -34,7 +34,7 @@ extern "C" */ class VncThread : public QThread { -Q_OBJECT + Q_OBJECT private: rfbClient *_client; diff --git a/src/client/vnc/vncwindow.cpp b/src/client/vnc/vncwindow.cpp index f18fadc..818b22f 100644 --- a/src/client/vnc/vncwindow.cpp +++ b/src/client/vnc/vncwindow.cpp @@ -41,19 +41,17 @@ VncWindow::~VncWindow() */ void VncWindow::terminateVncThread() { - if(_vncWorker == NULL) + if (_vncWorker == NULL) return; _vncWorker->blockSignals(true); _vncWorker->stop(); _vncWorker = NULL; - if(_redrawTimer != 0) - { + if (_redrawTimer != 0) { killTimer(_redrawTimer); _redrawTimer = 0; } - if(_tcpTimeoutTimer != 0) - { + if (_tcpTimeoutTimer != 0) { killTimer(_tcpTimeoutTimer); _tcpTimeoutTimer = 0; } @@ -101,8 +99,8 @@ void VncWindow::open(const QString& host, int port, const QString& passwd, bool 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); + SLOT(onUpdateImage(const int, const int, const int, const int)), + Qt::QueuedConnection); setWindowTitle(caption); @@ -110,15 +108,12 @@ void VncWindow::open(const QString& host, int port, const QString& passwd, bool _remoteThumb.loadFromData(rawThumb); - if (fullscreen) - { + if (fullscreen) { setWindowFlags(Qt::WindowStaysOnTopHint); showFullScreen(); activateWindow(); raise(); - } - else - { + } else { resize(800, 600); showNormal(); } @@ -207,23 +202,18 @@ void VncWindow::onProjectionStopped() */ void VncWindow::timerEvent(QTimerEvent *event) { - if (event->timerId() == _redrawTimer) - { + if (event->timerId() == _redrawTimer) { killTimer(_redrawTimer); _redrawTimer = 0; if (this->isVisible()) this->repaint(); - } - else if (event->timerId() == _tcpTimeoutTimer) - { + } else if (event->timerId() == _tcpTimeoutTimer) { killTimer(_tcpTimeoutTimer); _tcpTimeoutTimer = 0; - if (_vncWorker != NULL && !_vncWorker->isConnected()) - { + if (_vncWorker != NULL && !_vncWorker->isConnected()) { this->close(); } - } - else + } else killTimer(event->timerId()); } @@ -237,24 +227,18 @@ void VncWindow::timerEvent(QTimerEvent *event) */ void VncWindow::paintEvent(QPaintEvent *event) { - if (_vncWorker == NULL || !_vncWorker->isConnected()) - { + if (_vncWorker == NULL || !_vncWorker->isConnected()) { QPainter painter(this); - if (!_remoteThumb.isNull() && _remoteThumb.height() > 0) - { + if (!_remoteThumb.isNull() && _remoteThumb.height() > 0) { painter.drawPixmap(0, 0, this->width(), this->height(), _remoteThumb); - } - else - { + } else { painter.fillRect(event->rect(), QColor(60, 63, 66)); } QFontInfo fi = painter.fontInfo(); painter.setPen(QColor(200, 100, 10)); painter.setFont(QFont(fi.family(), 28, fi.weight(), fi.italic())); painter.drawText(this->contentsRect(), Qt::AlignCenter, tr("Connecting...")); - } - else - { + } else { const QRect &r = event->rect(); this->draw(r.left(), r.top(), r.width(), r.height()); } @@ -268,8 +252,7 @@ void VncWindow::paintEvent(QPaintEvent *event) */ void VncWindow::resizeEvent(QResizeEvent* event) { - if (_vncWorker != NULL) - { + if (_vncWorker != NULL) { _vncWorker->setTargetSize(event->size()); } this->repaint(); diff --git a/src/client/vnc/vncwindow.h b/src/client/vnc/vncwindow.h index 797ca90..2b91c0e 100644 --- a/src/client/vnc/vncwindow.h +++ b/src/client/vnc/vncwindow.h @@ -21,7 +21,7 @@ class QPainter; class VncWindow : public QWidget { -Q_OBJECT + Q_OBJECT public: VncWindow(QWidget *parent = 0); diff --git a/src/server/connectionframe/connectionframe.cpp b/src/server/connectionframe/connectionframe.cpp index 3278e04..0a7b180 100644 --- a/src/server/connectionframe/connectionframe.cpp +++ b/src/server/connectionframe/connectionframe.cpp @@ -22,31 +22,31 @@ #include static QString style_student( - "QLabel{ background-color: #FFF; border-radius: 2px; color: black;} \ + "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;} \ + "QLabel{ background-color: #FFF; border-radius: 2px; color: black;} \ QGroupBox { background-color: #70C670; margin: 2px; border-radius: 4px}" ); static QString style_selectedStudent( - "QLabel{ background-color: #FFF; border-radius: 2px; color: black; } \ + "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;} \ + "QLabel{ background-color: #FFF; border-radius: 2px; color: black;} \ QGroupBox { background-color: #99ff99; margin: 0px; border-radius: 4px; border: 4px solid #6C8CF0;}" ); static QString style_exam ( - "QLabel{ background-color: #919191; color: black; } \ + "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; } \ + "QLabel{ background-color: #919191; color: black; } \ QGroupBox { background-color: #cc743a; margin: 1px; border-radius: 4px}" ); static QString style_disconnected( - "QLabel{ background-color: #919191; color: black; } \ + "QLabel{ background-color: #919191; color: black; } \ QGroupBox { background-color: #7F7F7F; margin: 1px; border-radius: 4px}" ); @@ -59,13 +59,12 @@ static QIcon *term = NULL, *cam = NULL, *eye = NULL, *lock = NULL; * @param height */ ConnectionFrame::ConnectionFrame(QWidget *parent, int width, int height) : - QGroupBox(parent), _client(NULL), _timerId(0), _timerCounter(0), _isSelected(false), _isTutor(false) + QGroupBox(parent), _client(NULL), _timerId(0), _timerCounter(0), _isSelected(false), _isTutor(false) { //defines the ui-stuff // load icons first - if (term == NULL) - { + if (term == NULL) { term = new QIcon(":terminal"); cam = new QIcon(":cf_cam"); eye = new QIcon(":cf_eye"); @@ -74,50 +73,49 @@ ConnectionFrame::ConnectionFrame(QWidget *parent, int width, int height) : //this->setAttribute(Qt::WA_OpaquePaintEvent); - _mainLayout = new QBoxLayout(QBoxLayout::TopToBottom, this); - _mainLayout->setSpacing(1); - _mainLayout->setMargin(3); - _mainLayout->setAlignment(Qt::AlignHCenter); - this->setStyleSheet(style_student); - - _iconLayout = new QBoxLayout(QBoxLayout::RightToLeft, NULL); - _iconLayout->setSpacing(1); - _iconLayout->setMargin(3); - - _lblUserName = new QLabel("Test", this); - _lblUserName->setAlignment(Qt::AlignHCenter); - - _lblHostName = new QLabel("PC", this); - _lblHostName->setAlignment(Qt::AlignHCenter); - - _lblExamMode = new QLabel(tr("EXAM-MODE"), this); - _lblExamMode->setAlignment(Qt::AlignHCenter); - _lblExamMode->setVisible(false); - - _icoCam = addIcon(cam); - _icoEye = addIcon(eye); - _icoLock = addIcon(lock); - - _iconLayout->addWidget(_icoCam); - _iconLayout->addWidget(_icoEye); - _iconLayout->addWidget(_icoLock); - _iconLayout->addStretch(); - - _mainLayout->addLayout(_iconLayout); - _mainLayout->addStretch(); - _mainLayout->addWidget(_lblExamMode); - _mainLayout->addStretch(); - _mainLayout->addWidget(_lblUserName); - _mainLayout->addWidget(_lblHostName); - this->setLayout(_mainLayout); - this->setSize(width, height); - this->updateAppearance(); + _mainLayout = new QBoxLayout(QBoxLayout::TopToBottom, this); + _mainLayout->setSpacing(1); + _mainLayout->setMargin(3); + _mainLayout->setAlignment(Qt::AlignHCenter); + this->setStyleSheet(style_student); + + _iconLayout = new QBoxLayout(QBoxLayout::RightToLeft, NULL); + _iconLayout->setSpacing(1); + _iconLayout->setMargin(3); + + _lblUserName = new QLabel("Test", this); + _lblUserName->setAlignment(Qt::AlignHCenter); + + _lblHostName = new QLabel("PC", this); + _lblHostName->setAlignment(Qt::AlignHCenter); + + _lblExamMode = new QLabel(tr("EXAM-MODE"), this); + _lblExamMode->setAlignment(Qt::AlignHCenter); + _lblExamMode->setVisible(false); + + _icoCam = addIcon(cam); + _icoEye = addIcon(eye); + _icoLock = addIcon(lock); + + _iconLayout->addWidget(_icoCam); + _iconLayout->addWidget(_icoEye); + _iconLayout->addWidget(_icoLock); + _iconLayout->addStretch(); + + _mainLayout->addLayout(_iconLayout); + _mainLayout->addStretch(); + _mainLayout->addWidget(_lblExamMode); + _mainLayout->addStretch(); + _mainLayout->addWidget(_lblUserName); + _mainLayout->addWidget(_lblHostName); + this->setLayout(_mainLayout); + this->setSize(width, height); + this->updateAppearance(); } ConnectionFrame::~ConnectionFrame() { - if (_client != NULL) - { + if (_client != NULL) { _client->deleteLater(); } _iconLayout->deleteLater(); @@ -130,12 +128,12 @@ ConnectionFrame::~ConnectionFrame() */ QLabel* ConnectionFrame::addIcon(const QIcon* icon) { - QLabel *label = new QLabel(this); - label->setPixmap(icon->pixmap(24, 24, QIcon::Normal, QIcon::On)); - label->setAttribute(Qt::WA_TranslucentBackground); - label->hide(); - _icons.append(label); - return label; + QLabel *label = new QLabel(this); + label->setPixmap(icon->pixmap(24, 24, QIcon::Normal, QIcon::On)); + label->setAttribute(Qt::WA_TranslucentBackground); + label->hide(); + _icons.append(label); + return label; } /** @@ -196,16 +194,12 @@ void ConnectionFrame::showDefaultThumb() void ConnectionFrame::mouseReleaseEvent(QMouseEvent* event) { event->accept(); - if (event->button() == Qt::LeftButton) - { + if (event->button() == Qt::LeftButton) { QApplication::setOverrideCursor(QCursor(Qt::OpenHandCursor)); // Only recognize a move if the distance is larger than _startDragDistance - if ((this->pos() - _previousPosition).manhattanLength() > _startDragDistance ) - { + if ((this->pos() - _previousPosition).manhattanLength() > _startDragDistance ) { emit frameMoved(true, this); - } - else - { + } else { qDebug("Clicked"); move(_previousPosition); emit clicked(this); @@ -239,12 +233,9 @@ void ConnectionFrame::leaveEvent(QEvent* event) */ void ConnectionFrame::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::RightButton) - { + if (event->button() == Qt::RightButton) { // Menu... - } - else - { + } else { _clickPoint = event->pos(); _previousPosition = this->pos(); QApplication::setOverrideCursor(QCursor(Qt::ClosedHandCursor)); @@ -263,7 +254,7 @@ void ConnectionFrame::mousePressEvent(QMouseEvent *event) void ConnectionFrame::mouseMoveEvent(QMouseEvent *event) { QApplication::setOverrideCursor(QCursor(Qt::ClosedHandCursor)); - move(mapToParent(event->pos()-_clickPoint)); + move(mapToParent(event->pos() - _clickPoint)); event->accept(); } @@ -286,7 +277,7 @@ void ConnectionFrame::paintEvent(QPaintEvent *event) QGroupBox::paintEvent(event); if (_remoteScreen.isNull()) { return; - } + } QPainter painter(this); painter.drawPixmap((this->width() - _remoteScreen.width()) / 2, 4, _remoteScreen); @@ -339,19 +330,18 @@ void ConnectionFrame::setTutor(bool b) */ void ConnectionFrame::updateAppearance() { - if (_client == NULL) - { + if (_client == NULL) { // Unconnected Frame if (_isSelected) { this->setStyleSheet(style_selectedStudent); - } else if (_isTutor) { - this->setStyleSheet(style_tutor); - }else { + } else if (_isTutor) { + this->setStyleSheet(style_tutor); + } else { this->setStyleSheet(style_disconnected); - } + } for (QList::iterator it(_icons.begin()); it != _icons.end(); ++it) { (**it).hide(); - } + } return; } _icoCam->setVisible(_client->isActiveVncServer()); @@ -362,23 +352,19 @@ void ConnectionFrame::updateAppearance() _lblExamMode->setVisible(_client->isExamMode()); // Normal client, no special stuff active - if (_isSelected && _isTutor){ + if (_isSelected && _isTutor) { this->setStyleSheet(style_selectedTutor); - } - else if (_isTutor){ + } else if (_isTutor) { this->setStyleSheet(style_tutor); - } - else if (_client->isExamMode()) { + } else if (_client->isExamMode()) { if (_isSelected) { this->setStyleSheet(style_exam_selected); } else { this->setStyleSheet(style_exam); } - } - else if (_isSelected) { + } else if (_isSelected) { this->setStyleSheet(style_selectedStudent); - } - else { + } else { this->setStyleSheet(style_student); } } @@ -393,8 +379,7 @@ void ConnectionFrame::updateAppearance() */ void ConnectionFrame::onClientDisconnected() { - if (_timerId != 0) - { + if (_timerId != 0) { killTimer(_timerId); _timerId = 0; } diff --git a/src/server/connectionframe/connectionframe.h b/src/server/connectionframe/connectionframe.h index 9ac71c0..4f4decb 100644 --- a/src/server/connectionframe/connectionframe.h +++ b/src/server/connectionframe/connectionframe.h @@ -10,7 +10,7 @@ class ConnectionFrame : public QGroupBox { -Q_OBJECT + Q_OBJECT private: @@ -31,7 +31,7 @@ private: QPoint _previousPosition; QPoint _currentPosition; - QPoint _gridPosition; + QPoint _gridPosition; Client *_client; @@ -61,8 +61,8 @@ public: void setSelection(bool selected); const inline bool isSelected() const { return _isSelected; } - inline void setGridPosition(QPoint pos) { _gridPosition = pos; } - inline QPoint getGridPosition() const { return _gridPosition; }; + inline void setGridPosition(QPoint pos) { _gridPosition = pos; } + inline QPoint getGridPosition() const { return _gridPosition; }; const inline void setCurrentPosition(QPoint position) { _currentPosition = position; } const inline QPoint& getCurrentPosition() const { return _currentPosition; } diff --git a/src/server/helpwindow/helpwindow.h b/src/server/helpwindow/helpwindow.h index b2aeab7..528a4d3 100644 --- a/src/server/helpwindow/helpwindow.h +++ b/src/server/helpwindow/helpwindow.h @@ -3,7 +3,8 @@ #include -namespace Ui { +namespace Ui +{ class Help; } diff --git a/src/server/main.cpp b/src/server/main.cpp index 0c09f91..02fd399 100644 --- a/src/server/main.cpp +++ b/src/server/main.cpp @@ -8,7 +8,8 @@ using std::cout; using std::endl; -void usage() { +void usage() +{ cout << "USAGE pvsmgr [OPTIONS]" << endl; cout << "OPTIONS: " << endl; cout << "--manager-only" << endl; @@ -33,7 +34,7 @@ int main(int argc, char** argv) Global::manager_only = true; break; } else if (a.startsWith("--config=")) { - Global::setIniPath(a.mid(9)); + Global::setIniPath(a.mid(9)); } else if (a == "--usage" || a == "--help") { usage(); exit(0); diff --git a/src/server/mainwindow/mainwindow.cpp b/src/server/mainwindow/mainwindow.cpp index b29addc..e1d3f1e 100644 --- a/src/server/mainwindow/mainwindow.cpp +++ b/src/server/mainwindow/mainwindow.cpp @@ -66,16 +66,16 @@ using std::endl; MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow), _tbIconSize(24), _tbArea(Qt::LeftToolBarArea) { - qDebug() << "MainWindow(parent)"; + qDebug() << "MainWindow(parent)"; _mode = Mode::Multicast; _streamingSource = 0; - /* default value, these will be updated a room is loaded */ - _tilesX = 10; - _tilesY = 10; + /* default value, these will be updated a room is loaded */ + _tilesX = 10; + _tilesY = 10; - _virtCols = 0; - _virtRows = 0; + _virtCols = 0; + _virtRows = 0; _sessionNameWindow = new SessionNameWindow(this); _helpWindow = new HelpWindow(this); @@ -124,24 +124,24 @@ MainWindow::MainWindow(QWidget* parent) : connect(ui->action_Lock, SIGNAL(toggled(bool)), this, SLOT(onButtonLock(bool))); 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_DeleteClient, SIGNAL(triggered()), this, SLOT(onDeleteClient())); - // /* In exam-mode: disable most features */ + // /* In exam-mode: disable most features */ // QSharedPointer conf = Global::getSettings(); - // if (conf->contains("examMode")) { - // Global::setExam(conf->value("examMode").toBool()); - // } + // if (conf->contains("examMode")) { + // Global::setExam(conf->value("examMode").toBool()); + // } + + /* disable context-sensitive buttons by default */ + _contextButtons + << ui->action_DeleteClient + << ui->action_StudentToTutor + << ui->action_StudentToTutorExclusive + << ui->action_SetAsTutor + << ui->action_TutorToStudent; - /* disable context-sensitive buttons by default */ - _contextButtons - << ui->action_DeleteClient - << ui->action_StudentToTutor - << ui->action_StudentToTutorExclusive - << ui->action_SetAsTutor - << ui->action_TutorToStudent; - - lockContextButtons(); + lockContextButtons(); /* Stuff for the button lock */ //Setup a timeout @@ -151,18 +151,18 @@ MainWindow::MainWindow(QWidget* parent) : connect(_buttonLockTimer, SIGNAL(timeout()), this, SLOT(EnableButtons())); // Define the locking buttons _lockingButtons - << ui->action_Lock - << ui->action_TutorToAll - << ui->action_StudentToTutor - << ui->action_TutorToStudent - << ui->action_StopProjection - << ui->action_SetAsTutor; + << ui->action_Lock + << ui->action_TutorToAll + << ui->action_StudentToTutor + << ui->action_TutorToStudent + << ui->action_StopProjection + << ui->action_SetAsTutor; // Clicking the session name label shows the edit field for it connect(_sessionNameLabel, SIGNAL(clicked()), this, SLOT(onSessionNameClick())); // Listen to updates to the session name through the session name window connect(_sessionNameWindow, SIGNAL(updateSessionName()), this, - SLOT(onSessionNameUpdate())); + SLOT(onSessionNameUpdate())); setAttribute(Qt::WA_QuitOnClose); setUnifiedTitleAndToolBarOnMac(true); @@ -183,7 +183,8 @@ MainWindow::MainWindow(QWidget* parent) : /** this function determines if the number of clients in exam mode comprise * more than 50%. In that case the whole manager switches to exam mode, * disabling many features in the toolbar **/ -void MainWindow::updateExamMode() { +void MainWindow::updateExamMode() +{ /* TODO */ int numerator = 0; int denominator = 0; @@ -229,18 +230,20 @@ MainWindow::~MainWindow() } /** Euclidean distance (why is this not implemented in QPoint?) */ -float distance(QPoint a, QPoint b) { - int dx = a.x() - b.x(); - int dy = a.y() - b.y(); - int sum = dx*dx + dy*dy; - return sqrt((float) sum); +float distance(QPoint a, QPoint b) +{ + int dx = a.x() - b.x(); + int dy = a.y() - b.y(); + int sum = dx * dx + dy * dy; + return sqrt((float) sum); } -float distance(QPointF a, QPointF b) { - int dx = a.x() - b.x(); - int dy = a.y() - b.y(); - int sum = dx*dx + dy*dy; - return sqrt(sum); +float distance(QPointF a, QPointF b) +{ + int dx = a.x() - b.x(); + int dy = a.y() - b.y(); + int sum = dx * dx + dy * dy; + return sqrt(sum); } @@ -253,72 +256,74 @@ float distance(QPointF a, QPointF b) { * 'Algorithm': ideally, go in circles around the preferred point until you find * a free spot. Lazy way: store all free positions in an array and find later * there the closest (<- that's what I do) - * - * @param preferred in Pixels! + * + * @param preferred in Pixels! * @param toIgnore, ignore this connectionframe when considering free slots * @return the free slot */ -QPoint MainWindow::closestFreeSlot(QPoint preferredPixels, ConnectionFrame* toIgnore) { - const QSize& clientSize = Global::getCurrentRoom()->clientSize; +QPoint MainWindow::closestFreeSlot(QPoint preferredPixels, ConnectionFrame* toIgnore) +{ + const QSize& clientSize = Global::getCurrentRoom()->clientSize; bool grid[_tilesX][_tilesY]; memset(grid, 0, sizeof(bool) * _tilesX * _tilesY); /* set everything to false */ - /* fill grid */ + /* fill grid */ for (auto it = _clientFrames.begin(); it != _clientFrames.end(); ++it) { - if (*it == toIgnore) { continue; } - - const QPoint& p = (*it)->getGridPosition(); - - for (int x = p.x(); x < p.x() + clientSize.width(); x++) { - for (int y = p.y(); y < p.y() + clientSize.height(); y++) { - grid[x][y] = true; - } - } - } - - QList freePositions; - /* check all positions to see if they are available */ - for (int x = 0; x <= _tilesX - clientSize.width(); x++) { - for ( int y = 0; y <= _tilesY - clientSize.height(); y++) { - /* check if (x,y) is free */ - bool isFree = true; - for (int dx = 0; dx < clientSize.width(); dx++) { - for (int dy = 0; dy < clientSize.height(); dy++) { - if (grid[x + dx][y + dy]) { - isFree = false; - goto endLoop; // double-break - } - } - } + if (*it == toIgnore) { continue; } + + const QPoint& p = (*it)->getGridPosition(); + + for (int x = p.x(); x < p.x() + clientSize.width(); x++) { + for (int y = p.y(); y < p.y() + clientSize.height(); y++) { + grid[x][y] = true; + } + } + } + + QList freePositions; + /* check all positions to see if they are available */ + for (int x = 0; x <= _tilesX - clientSize.width(); x++) { + for ( int y = 0; y <= _tilesY - clientSize.height(); y++) { + /* check if (x,y) is free */ + bool isFree = true; + for (int dx = 0; dx < clientSize.width(); dx++) { + for (int dy = 0; dy < clientSize.height(); dy++) { + if (grid[x + dx][y + dy]) { + isFree = false; + goto endLoop; // double-break + } + } + } endLoop: - if (isFree) { freePositions << QPoint(x,y); } - } - } - /* among all the free positions, find the closest */ - float min_distance = 10000; - QPoint bestPosition = QPoint(-1, -1); - - for (QPoint freePos : freePositions) { - QPoint freePosCenter( freePos.x() * getTileWidthPx() + getTileWidthPx() * clientSize.width() / 2, - freePos.y() * getTileHeightPx() + getTileHeightPx() * clientSize.height() / 2); - float dist = distance(freePosCenter, preferredPixels); - if (dist < min_distance) { - min_distance = dist; - bestPosition = freePos; - } - } - return bestPosition; + if (isFree) { freePositions << QPoint(x, y); } + } + } + /* among all the free positions, find the closest */ + float min_distance = 10000; + QPoint bestPosition = QPoint(-1, -1); + + for (QPoint freePos : freePositions) { + QPoint freePosCenter( freePos.x() * getTileWidthPx() + getTileWidthPx() * clientSize.width() / 2, + freePos.y() * getTileHeightPx() + getTileHeightPx() * clientSize.height() / 2); + float dist = distance(freePosCenter, preferredPixels); + if (dist < min_distance) { + min_distance = dist; + bestPosition = freePos; + } + } + return bestPosition; } /* place frame in the cloest available spot */ -void MainWindow::placeFrameInFreeSlot(ConnectionFrame* frame, QPoint preferredPixels) { +void MainWindow::placeFrameInFreeSlot(ConnectionFrame* frame, QPoint preferredPixels) +{ - QPoint bestPosition = closestFreeSlot(preferredPixels, frame); + QPoint bestPosition = closestFreeSlot(preferredPixels, frame); - frame->setGridPosition(bestPosition); - QPoint freePosPx(bestPosition.x() * getTileWidthPx(), bestPosition.y() * getTileHeightPx()); - frame->setCurrentPosition(freePosPx); + frame->setGridPosition(bestPosition); + QPoint freePosPx(bestPosition.x() * getTileWidthPx(), bestPosition.y() * getTileHeightPx()); + frame->setCurrentPosition(freePosPx); } /***************************************************************************//** @@ -330,8 +335,8 @@ void MainWindow::placeFrameInFreeSlot(ConnectionFrame* frame, QPoint preferredPi ConnectionFrame* MainWindow::createFrame() { // Allocate and resize - int width = getTileWidthPx() * Global::getCurrentRoom()->clientSize.width(); - int height= getTileHeightPx() * Global::getCurrentRoom()->clientSize.height(); + int width = getTileWidthPx() * Global::getCurrentRoom()->clientSize.width(); + int height = getTileHeightPx() * Global::getCurrentRoom()->clientSize.height(); ConnectionFrame *cf = new ConnectionFrame(ui->frmRoom, width, height); _clientFrames.append(cf); @@ -350,14 +355,14 @@ ConnectionFrame* MainWindow::createFrame() ConnectionFrame* MainWindow::createFrame(QString computerId, QPoint pxCoord, QPoint gridPosition) { // Allocate and resize - const Room* room = Global::getCurrentRoom(); - int width = getTileWidthPx() * (room == NULL ? 1 : room->clientSize.width()); - int height = getTileHeightPx() * (room == NULL ? 1 : room->clientSize.height()); + const Room* room = Global::getCurrentRoom(); + int width = getTileWidthPx() * (room == NULL ? 1 : room->clientSize.width()); + int height = getTileHeightPx() * (room == NULL ? 1 : room->clientSize.height()); - ConnectionFrame *cf = new ConnectionFrame(ui->frmRoom, width, height); + ConnectionFrame *cf = new ConnectionFrame(ui->frmRoom, width, height); cf->setComputerId(computerId); cf->setCurrentPosition(pxCoord); - cf->setGridPosition(gridPosition); + cf->setGridPosition(gridPosition); _clientFrames.append(cf); cf->show(); connect(cf, SIGNAL(frameMoved(bool, ConnectionFrame *)), this, SLOT(onPlaceFrame(bool, ConnectionFrame *))); @@ -399,7 +404,7 @@ void MainWindow::tellClientCurrentSituation(Client* client) if (ui->action_Lock->isChecked() || _mode == Mode::LockedUnicast) client->lockScreen(true); - if (_mode == Mode::Broadcast){ + if (_mode == Mode::Broadcast) { client->setDesiredProjectionSource(_streamingSource); if (_streamingSource != 0) { client->startVncClient(getClientFromId(_streamingSource)); @@ -412,20 +417,21 @@ void MainWindow::tellClientCurrentSituation(Client* client) /** * returns the minimal grid size such that all clients fit on the grid **/ -QSize minimalGridSize(const QMap& clientPositions, QSize& clientSize) { - /* collect the maximum coordinates */ - 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(); } - - } - /* need a little extra space */ - QSize size(x + clientSize.width(), y + clientSize.height()); - return size; +QSize minimalGridSize(const QMap& clientPositions, QSize& clientSize) +{ + /* collect the maximum coordinates */ + 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(); } + + } + /* need a little extra space */ + QSize size(x + clientSize.width(), y + clientSize.height()); + return size; } /***************************************************************************//** @@ -433,17 +439,16 @@ QSize minimalGridSize(const QMap& clientPositions, QSize& clien */ void MainWindow::tryToUseRoomTemplate() { - qDebug() << "tryToUseRoomTemplate()"; + qDebug() << "tryToUseRoomTemplate()"; QMap roomsList; QSharedPointer conf = Global::getSettings(); if (!conf->contains("rooms")) { qDebug() << "Invalid config file (no rooms are set)!"; return; } QStringList rooms = conf->value("rooms").toStringList(); - QString myRoom = ""; + QString myRoom = ""; - for (QString roomId : rooms) - { + for (QString roomId : rooms) { conf->beginGroup(roomId); QString roomName = conf->value("name").toString(); @@ -455,61 +460,61 @@ void MainWindow::tryToUseRoomTemplate() qDebug() << "Invalid config file (room " << roomName << " needs a mgrIP)!"; return; } - QMap clientPositions; + QMap clientPositions; // First store all room configurations in _rooms. int size = conf->beginReadArray("client"); for (int j = 0; j < size; j++) { conf->setArrayIndex(j); // qDebug() << "ip: " << conf.value("ip").toString() << " pos: " << conf.value("pos").toPoint(); // roomsList[i].insert(conf.value("ip").toString(), conf.value("pos").toPoint()); - clientPositions.insert(conf->value("ip").toString(), conf->value("pos").toPoint()); + clientPositions.insert(conf->value("ip").toString(), conf->value("pos").toPoint()); } conf->endArray(); - /* read backgroundImage */ - QString image = conf->contains("backgroundImage") ? conf->value("backgroundImage").toString() : ""; + /* read backgroundImage */ + QString image = conf->contains("backgroundImage") ? conf->value("backgroundImage").toString() : ""; QString mgrIP = conf->value("mgrIP").toString(); - QString tutorIP = conf->value("tutorIP").toString(); - - QSize gridSize; - QSize clientSize(1,1); - /* read some other properties of the room */ - if (conf->contains("gridSize")) { - gridSize = conf->value("gridSize").toSize(); - } - if (conf->contains("clientSize")) { - clientSize = conf->value("clientSize").toSize(); - } - - foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { + QString tutorIP = conf->value("tutorIP").toString(); + + QSize gridSize; + QSize clientSize(1, 1); + /* read some other properties of the room */ + if (conf->contains("gridSize")) { + gridSize = conf->value("gridSize").toSize(); + } + if (conf->contains("clientSize")) { + clientSize = conf->value("clientSize").toSize(); + } + + foreach (const QHostAddress & address, QNetworkInterface::allAddresses()) { if (address != QHostAddress(QHostAddress::LocalHost) && mgrIP == address.toString()) { qDebug("Found this ip in config."); - myRoom = roomName; + myRoom = roomName; } } conf->endGroup(); - if (!gridSize.isValid()) { - /* ok, let's choose the minimum gridSize to fit all clients */ - gridSize = minimalGridSize(clientPositions, clientSize); - qDebug() << "had to use minimalGridSize(): = " << gridSize; + if (!gridSize.isValid()) { + /* ok, let's choose the minimum gridSize to fit all clients */ + gridSize = minimalGridSize(clientPositions, clientSize); + qDebug() << "had to use minimalGridSize(): = " << gridSize; - } - Room* r = new Room(clientPositions, gridSize, clientSize, image, tutorIP); - qDebug() << "read new room: " << roomName << ": " << gridSize << ", " << clientSize; - roomsList.insert(roomName, r); + } + Room* r = new Room(clientPositions, gridSize, clientSize, image, tutorIP); + qDebug() << "read new room: " << roomName << ": " << gridSize << ", " << clientSize; + roomsList.insert(roomName, r); } Global::setRooms(roomsList); - if (myRoom == "") { - /* so apparently this is not a manager of a room */ - if (Global::manager_only) { - cout << "exiting because of the argument --manager-only was set and this computer is not a manager" << endl; - exit(0); - } - } else { - switchRoomTo(myRoom); - } - + if (myRoom == "") { + /* so apparently this is not a manager of a room */ + if (Global::manager_only) { + cout << "exiting because of the argument --manager-only was set and this computer is not a manager" << endl; + exit(0); + } + } else { + switchRoomTo(myRoom); + } + } /***************************************************************************//** @@ -520,10 +525,8 @@ void MainWindow::tryToUseRoomTemplate() */ Client* MainWindow::getClientFromId(int id) { - for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - { - if ((*it)->client() != NULL) - { + for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { + if ((*it)->client() != NULL) { if ((*it)->client()->id() == id) return (*it)->client(); } @@ -539,8 +542,7 @@ Client* MainWindow::getClientFromId(int id) */ ConnectionFrame* MainWindow::getTutorFrame() { - for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - { + for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { if (((*it) != NULL) && ((*it)->isTutor())) return (*it); } @@ -555,8 +557,7 @@ ConnectionFrame* MainWindow::getTutorFrame() */ ConnectionFrame* MainWindow::getSelectedFrame() { - for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - { + for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { if (((*it) != NULL) && ((*it)->isSelected())) return (*it); } @@ -597,17 +598,18 @@ enum AspectStatus { GRID_OK, GRID_TOO_WIDE, GRID_TOO_TALL }; * size. The parameters in here are hand-adjusted. Feel free to make it more or * less sensitive. * */ -AspectStatus checkAspectRatio(const QSize& frameSize, const QSize& gridSize) { - float aspectRoom = ((float) gridSize.height()) / ((float) gridSize.width()); - float aspectFrame = ((float) frameSize.height()) / ((float) frameSize.width()); - - if (aspectRoom / aspectFrame < 0.8) { - return GRID_TOO_WIDE; - } - if ( aspectFrame / aspectRoom < 0.8) { - return GRID_TOO_TALL; - } - return GRID_OK; +AspectStatus checkAspectRatio(const QSize& frameSize, const QSize& gridSize) +{ + float aspectRoom = ((float) gridSize.height()) / ((float) gridSize.width()); + float aspectFrame = ((float) frameSize.height()) / ((float) frameSize.width()); + + if (aspectRoom / aspectFrame < 0.8) { + return GRID_TOO_WIDE; + } + if ( aspectFrame / aspectRoom < 0.8) { + return GRID_TOO_TALL; + } + return GRID_OK; } @@ -617,80 +619,81 @@ AspectStatus checkAspectRatio(const QSize& frameSize, const QSize& gridSize) { */ void MainWindow::resizeEvent(QResizeEvent* e) { - const Room* room = Global::getCurrentRoom(); - const QSize& clientSize = room->clientSize; + const Room* room = Global::getCurrentRoom(); + const QSize& clientSize = room->clientSize; if (ui->frmRoom->size().width() < 100 || ui->frmRoom->size().height() < 100 || _tilesX <= 0 || _tilesY <= 0) { return; } - QSize newGridSize = room->gridSize; - - /* do we have to add virtual columns? */ - while (checkAspectRatio(ui->frmRoom->size(), newGridSize) == GRID_TOO_WIDE) { - /* add row */ - newGridSize.setHeight(newGridSize.height() + 1); - } - while (checkAspectRatio(ui->frmRoom->size(), newGridSize) == GRID_TOO_TALL) { - /* add column */ - newGridSize.setWidth(newGridSize.width() + 1); - } - this->_tilesX = newGridSize.width(); - this->_tilesY = newGridSize.height(); - - /* Bring back frame that are now out of the screen */ - for (auto it = _clientFrames.begin(); it != _clientFrames.end(); ++it) { - const QPoint gp = (*it)->getGridPosition(); - if ( gp.x() >= _tilesX || gp.y() >= _tilesY ) { - qDebug() << "bring frame back"; - placeFrameInFreeSlot(*it, (*it)->getCurrentPosition()); - } - } + QSize newGridSize = room->gridSize; + + /* do we have to add virtual columns? */ + while (checkAspectRatio(ui->frmRoom->size(), newGridSize) == GRID_TOO_WIDE) { + /* add row */ + newGridSize.setHeight(newGridSize.height() + 1); + } + while (checkAspectRatio(ui->frmRoom->size(), newGridSize) == GRID_TOO_TALL) { + /* add column */ + newGridSize.setWidth(newGridSize.width() + 1); + } + this->_tilesX = newGridSize.width(); + this->_tilesY = newGridSize.height(); + + /* Bring back frame that are now out of the screen */ + for (auto it = _clientFrames.begin(); it != _clientFrames.end(); ++it) { + const QPoint gp = (*it)->getGridPosition(); + if ( gp.x() >= _tilesX || gp.y() >= _tilesY ) { + qDebug() << "bring frame back"; + placeFrameInFreeSlot(*it, (*it)->getCurrentPosition()); + } + } /* Resize all connection windows */ - for (QList::iterator it = _clientFrames.begin(); it != _clientFrames.end(); ++it) - { - int newPosX = (*it)->getGridPosition().x() * getTileWidthPx(); - int newPosY = (*it)->getGridPosition().y() * getTileHeightPx(); - QPoint newPos(newPosX, newPosY); - - (*it)->setSize(getTileWidthPx() * clientSize.width(), getTileHeightPx() * clientSize.height()); - (*it)->move(newPos); + for (QList::iterator it = _clientFrames.begin(); it != _clientFrames.end(); ++it) { + int newPosX = (*it)->getGridPosition().x() * getTileWidthPx(); + int newPosY = (*it)->getGridPosition().y() * getTileHeightPx(); + QPoint newPos(newPosX, newPosY); + + (*it)->setSize(getTileWidthPx() * clientSize.width(), getTileHeightPx() * clientSize.height()); + (*it)->move(newPos); } - /* update background image label */ - if (_backgroundImage != NULL) { - int w = ui->frmRoom->width() - 5; /* to make sure that we don't enlarge the window */ - int h = ui->frmRoom->height() - 5; - ui->imageLabel->hide(); - ui->imageLabel->setScaledContents(true); - ui->imageLabel->setPixmap(QPixmap::fromImage(*_backgroundImage).scaled(w,h, Qt::IgnoreAspectRatio)); - ui->imageLabel->show(); - } else { - ui->imageLabel->clear(); - } + /* update background image label */ + if (_backgroundImage != NULL) { + int w = ui->frmRoom->width() - 5; /* to make sure that we don't enlarge the window */ + int h = ui->frmRoom->height() - 5; + ui->imageLabel->hide(); + ui->imageLabel->setScaledContents(true); + ui->imageLabel->setPixmap(QPixmap::fromImage(*_backgroundImage).scaled(w, h, Qt::IgnoreAspectRatio)); + ui->imageLabel->show(); + } else { + ui->imageLabel->clear(); + } } -void MainWindow::lockContextButtons() { - for (auto it = _contextButtons.begin(); it != _contextButtons.end(); ++it) { - (*it)->setEnabled(false); - } +void MainWindow::lockContextButtons() +{ + for (auto it = _contextButtons.begin(); it != _contextButtons.end(); ++it) { + (*it)->setEnabled(false); + } } -void MainWindow::unlockContextButtons() { - for (auto it = _contextButtons.begin(); it != _contextButtons.end(); ++it) { - (*it)->setEnabled(true); - } - /* and disable some again based on special rules */ - if (getSelectedFrame()->client() != NULL) { - ui->action_DeleteClient->setEnabled(false); - } - if (getSelectedFrame()->client() == NULL) { - ui->action_SetAsTutor->setEnabled(false); - ui->action_StudentToTutorExclusive->setEnabled(false); - ui->action_StudentToTutor->setEnabled(false); - ui->action_TutorToStudent->setEnabled(false); - } +void MainWindow::unlockContextButtons() +{ + for (auto it = _contextButtons.begin(); it != _contextButtons.end(); ++it) { + (*it)->setEnabled(true); + } + /* and disable some again based on special rules */ + if (getSelectedFrame()->client() != NULL) { + ui->action_DeleteClient->setEnabled(false); + } + if (getSelectedFrame()->client() == NULL) { + ui->action_SetAsTutor->setEnabled(false); + ui->action_StudentToTutorExclusive->setEnabled(false); + ui->action_StudentToTutor->setEnabled(false); + ui->action_TutorToStudent->setEnabled(false); + } } @@ -709,11 +712,9 @@ void MainWindow::mouseReleaseEvent(QMouseEvent* e) if (pos.x() < 0 || pos.y() < 0) return; const QSize frame(ui->frmRoom->size()); - if (frame.width() > pos.x() && frame.height() > pos.y()) - { - lockContextButtons(); - if (getSelectedFrame() != NULL) - { + if (frame.width() > pos.x() && frame.height() > pos.y()) { + lockContextButtons(); + if (getSelectedFrame() != NULL) { getSelectedFrame()->setSelection(false); } } @@ -749,9 +750,9 @@ void MainWindow::onPlaceFrame(bool activateTrash, ConnectionFrame* connectionFra { // if (_tilesX <= 0 || _tilesY <= 0) return; const QPoint &preferredPixels = connectionFrame->frameGeometry().center(); - placeFrameInFreeSlot(connectionFrame, preferredPixels); + placeFrameInFreeSlot(connectionFrame, preferredPixels); - resizeEvent(NULL); + resizeEvent(NULL); } /***************************************************************************//** @@ -762,20 +763,19 @@ void MainWindow::onFrameClicked(ConnectionFrame* frame) { // If same frame is clicked again,, do nothing if (getSelectedFrame() == frame) - return; + return; // If another frame has been selected, unselect it // Set the ui selected and set a new reference - if (getSelectedFrame() != NULL) - { + if (getSelectedFrame() != NULL) { getSelectedFrame()->setSelection(false); } frame->setSelection(true); qDebug() << "ID of frame: " << frame->computerId(); qDebug() << "ID of selectedFrame: " << getSelectedFrame()->computerId(); - qDebug() << "position of selectedFrame: " << getSelectedFrame()->getGridPosition(); + qDebug() << "position of selectedFrame: " << getSelectedFrame()->getGridPosition(); - unlockContextButtons(); + unlockContextButtons(); } /***************************************************************************//** @@ -784,16 +784,13 @@ void MainWindow::onFrameClicked(ConnectionFrame* frame) void MainWindow::onSessionNameClick() { _countSessionNameUpdate++; - if (_countSessionNameUpdate > 1) - { + if (_countSessionNameUpdate > 1) { int ret = QMessageBox::question(this, "Warning", tr("Sure, You want to change SessionName again?\n" - "All Clients will be deleted afterwards."), 0, 1, 2); - if (ret == 1) - { + "All Clients will be deleted afterwards."), 0, 1, 2); + if (ret == 1) { _sessionNameWindow->show(Global::sessionName()); } - } - else + } else _sessionNameWindow->show((Global::sessionName())); } @@ -804,11 +801,9 @@ void MainWindow::onSessionNameUpdate() { // Stop all projections and clear all clients, which where connected to old sessionName. reset(); - if (_countSessionNameUpdate > 1) - { + if (_countSessionNameUpdate > 1) { { - for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - { + for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { (*it)->hide(); (*it)->deleteLater(); } @@ -863,79 +858,78 @@ void MainWindow::onReloadRoomCancel() _reloadWindow->hide(); } -void MainWindow::switchRoomTo(QString roomToReload) { - // qDebug() << roomToReload; - Global::setCurrentRoom(roomToReload); - Room *room = Global::getRooms()[roomToReload]; - /* set tiles */ - _tilesX = room->gridSize.width(); - _tilesY = room->gridSize.height(); - - - /* place connection frames */ - for (auto it = room->clientPositions.begin(); it != room->clientPositions.end(); ++it) { - QString computerId = it.key(); - QPoint pos = it.value(); - QPoint pxPos(pos.x() * getTileWidthPx(), pos.y() * getTileHeightPx()); - - ConnectionFrame *cf = createFrame(computerId, pxPos, pos); - cf->move(cf->getCurrentPosition()); - onPlaceFrame(false, cf); - if (computerId == room->tutorIP) { - qDebug() << "set computer with id " << computerId << " as tutor per configuration"; - if (getTutorFrame() != NULL) { - getTutorFrame()->setTutor(false); - } - cf->setTutor(true); - } else { - //qDebug() << "not tutor because id is " << computerId << " and tutorIP is " << room->tutorIP; - } - } - - /* load background image */ - QString imgPath = Global::getCurrentRoom()->imagePath; - qDebug() << "imgPath is " << imgPath; - - /* delete old image */ - if (_backgroundImage != NULL) {delete _backgroundImage; } - _backgroundImage = NULL; - - if (imgPath != "") { - 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(); - QSvgRenderer renderer(imgPath); - _backgroundImage = new QImage(s, QImage::Format_ARGB32); - _backgroundImage->fill(Qt::lightGray); /* background color */ - QPainter painter(_backgroundImage); - renderer.render(&painter); - } else { - _backgroundImage = new QImage(); - _backgroundImage->load(imgPath); - } - } - - /* and force a resize event (this scales the image) */ - resizeEvent(NULL); +void MainWindow::switchRoomTo(QString roomToReload) +{ + // qDebug() << roomToReload; + Global::setCurrentRoom(roomToReload); + Room *room = Global::getRooms()[roomToReload]; + /* set tiles */ + _tilesX = room->gridSize.width(); + _tilesY = room->gridSize.height(); + + + /* place connection frames */ + for (auto it = room->clientPositions.begin(); it != room->clientPositions.end(); ++it) { + QString computerId = it.key(); + QPoint pos = it.value(); + QPoint pxPos(pos.x() * getTileWidthPx(), pos.y() * getTileHeightPx()); + + ConnectionFrame *cf = createFrame(computerId, pxPos, pos); + cf->move(cf->getCurrentPosition()); + onPlaceFrame(false, cf); + if (computerId == room->tutorIP) { + qDebug() << "set computer with id " << computerId << " as tutor per configuration"; + if (getTutorFrame() != NULL) { + getTutorFrame()->setTutor(false); + } + cf->setTutor(true); + } else { + //qDebug() << "not tutor because id is " << computerId << " and tutorIP is " << room->tutorIP; + } + } + + /* load background image */ + QString imgPath = Global::getCurrentRoom()->imagePath; + qDebug() << "imgPath is " << imgPath; + + /* delete old image */ + if (_backgroundImage != NULL) {delete _backgroundImage; } + _backgroundImage = NULL; + + if (imgPath != "") { + 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(); + QSvgRenderer renderer(imgPath); + _backgroundImage = new QImage(s, QImage::Format_ARGB32); + _backgroundImage->fill(Qt::lightGray); /* background color */ + QPainter painter(_backgroundImage); + renderer.render(&painter); + } else { + _backgroundImage = new QImage(); + _backgroundImage->load(imgPath); + } + } + + /* and force a resize event (this scales the image) */ + resizeEvent(NULL); } void MainWindow::onReloadRoomOk() { - if (_reloadWindow->ui->roomList->currentItem() == NULL) - { + if (_reloadWindow->ui->roomList->currentItem() == NULL) { QMessageBox::critical(this, "Warning", tr("No item selected, please select room!"), 0, 1); return; } int ret = QMessageBox::QMessageBox::question(this, "Warning", tr("Are you sure you want to reload the room?\n" - "Note that all clients will be deleted."), 0, 1, 2); + "Note that all clients will be deleted."), 0, 1, 2); if (ret == 1) { disconnect(_reloadWindow->ui->buttonBox, SIGNAL(accepted()), this, SLOT(onReloadRoomOk())); disconnect(_reloadWindow->ui->buttonBox, SIGNAL(rejected()), this, SLOT(onReloadRoomCancel())); // Delete all clients. - for (QList::iterator it = _clientFrames.begin(); it != _clientFrames.end(); it++) - { + for (QList::iterator it = _clientFrames.begin(); it != _clientFrames.end(); it++) { (*it)->hide(); (*it)->deleteLater(); } @@ -943,19 +937,21 @@ void MainWindow::onReloadRoomOk() // Load new room configuration. QString roomToReload = _reloadWindow->ui->roomList->currentItem()->data(0).toString(); - switchRoomTo(roomToReload); + switchRoomTo(roomToReload); _reloadWindow->ui->roomList->clear(); _reloadWindow->hide(); - } + } } -int MainWindow::getTileWidthPx() const { - return ui->frmRoom->size().width() / _tilesX; +int MainWindow::getTileWidthPx() const +{ + return ui->frmRoom->size().width() / _tilesX; } -int MainWindow::getTileHeightPx() const { - return ui->frmRoom->size().height() / _tilesY; +int MainWindow::getTileHeightPx() const +{ + return ui->frmRoom->size().height() / _tilesY; } /***************************************************************************//** @@ -981,8 +977,7 @@ void MainWindow::onButtonTutorToAll() QMessageBox::critical(this, tr("Projection"), sStrTutorOffline); else if (_clientFrames.size() == 1) QMessageBox::critical(this, tr("Projection"), sStrNoDestAv); - else - { + else { // If this mode is already active, reset everything if (_mode == Mode::Broadcast) { reset(); @@ -1018,8 +1013,7 @@ void MainWindow::onButtonTutorToStudent() QMessageBox::critical(this, tr("Projection"), sStrDestOffline); else if (getTutorFrame()->client() == NULL) QMessageBox::critical(this, tr("Projection"), sStrTutorOffline); - else - { + else { // If this is the first call in this mode clear the watchers if (_mode != Mode::Multicast) { for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) @@ -1057,11 +1051,9 @@ void MainWindow::onButtonStudentToTutor() QMessageBox::critical(this, tr("Projection"), sStrSourceOffline); else if (getTutorFrame()->client() == NULL) QMessageBox::critical(this, tr("Projection"), sStrTutorOffline); - else - { + else { // If this is not the first run in this mode and the current source is selected, stop the streaming. - if (_mode == Mode::Unicast && getSelectedFrame()->client()->id() == _streamingSource) - { + if (_mode == Mode::Unicast && getSelectedFrame()->client()->id() == _streamingSource) { // Stop reset everything _mode = Mode::None; reset(); @@ -1071,7 +1063,7 @@ void MainWindow::onButtonStudentToTutor() // Unset all clients desired sources. Except the tutors desired source, this has to be the selecteds frame for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) if ((*it)->client() != NULL) - (*it)->client()->setDesiredProjectionSource(getTutorFrame()->client()->id() == (*it)->client()->id() ? getSelectedFrame()->client()->id():NO_SOURCE); + (*it)->client()->setDesiredProjectionSource(getTutorFrame()->client()->id() == (*it)->client()->id() ? getSelectedFrame()->client()->id() : NO_SOURCE); DisableButtons(); _mode = Mode::Unicast; @@ -1097,11 +1089,9 @@ void MainWindow::onButtonStudentToTutorExclusive() QMessageBox::critical(this, tr("Projection"), sStrSourceOffline); else if (getTutorFrame()->client() == NULL) QMessageBox::critical(this, tr("Projection"), sStrTutorOffline); - else - { + else { // If this is not the first run in this mode and the current source is selected, stop the streaming. - if (_mode == Mode::Unicast && getSelectedFrame()->client()->id() == _streamingSource) - { + if (_mode == Mode::Unicast && getSelectedFrame()->client()->id() == _streamingSource) { // Stop reset everything _mode = Mode::None; reset(); @@ -1111,7 +1101,7 @@ void MainWindow::onButtonStudentToTutorExclusive() // Unset all clients desired sources. Except the tutors desired source, this has to be the selecteds frame for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) if ((*it)->client() != NULL) - (*it)->client()->setDesiredProjectionSource(getTutorFrame()->client()->id() == (*it)->client()->id() ? getSelectedFrame()->client()->id():NO_SOURCE); + (*it)->client()->setDesiredProjectionSource(getTutorFrame()->client()->id() == (*it)->client()->id() ? getSelectedFrame()->client()->id() : NO_SOURCE); DisableButtons(); _mode = Mode::LockedUnicast; @@ -1142,8 +1132,7 @@ void MainWindow::onButtonLock(bool checked) // Stop all projections reset(); - for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - { + for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { if ((*it)->client() == NULL) continue; (*it)->client()->lockScreen(checked); @@ -1167,20 +1156,16 @@ void MainWindow::onButtonSetAsTutor() ui->action_Lock->setChecked(false); // If no frame is selected, warning. - if (getSelectedFrame() == NULL) - { + if (getSelectedFrame() == NULL) { QMessageBox::critical(this, tr("Selection"), tr("No client is selected.")); return; } // If frame of inactive client has been selected unselect it - if (getSelectedFrame()->client() == NULL) - { + if (getSelectedFrame()->client() == NULL) { QMessageBox::critical(this, tr("Selection"), tr("The selected client is not connected.")); return; - } - else // If selected client is locked, first unlock - { + } else { // If selected client is locked, first unlock getSelectedFrame()->client()->lockScreen(false); } @@ -1189,8 +1174,7 @@ void MainWindow::onButtonSetAsTutor() return; // Else unset the old and set the new tutor - if (getTutorFrame() != NULL) - { + if (getTutorFrame() != NULL) { getTutorFrame()->setTutor(false); } getSelectedFrame()->setTutor(true); @@ -1227,23 +1211,19 @@ void MainWindow::onClientAuthenticating(Client* client, ClientLogin* request) bool inuse; QString check = request->name; int addnum = 1; - do - { + do { inuse = false; - for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - { + for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { Client *c = (**it).client(); if (c == NULL) continue; if (!c->isAuthed()) continue; - if (c->ip() == request->ip) - { + if (c->ip() == request->ip) { request->accept = false; return; } - if (c->name() == check) - { + if (c->name() == check) { inuse = true; check = request->name + " (" + QString::number(++addnum) + ")"; break; @@ -1273,17 +1253,14 @@ void MainWindow::onClientAuthenticated(Client* client) connect(client, SIGNAL(vncClientStateChange(Client*)), this, SLOT(onVncClientStateChange(Client*))); bool hasActiveTutor = false; ConnectionFrame *existing = NULL; - for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - { + for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { // qDebug() << "Existing frame ip: " << (*it)->computerId(); // qDebug() << "New Clients ip: " << client->ip(); // qDebug() << ((*it)->computerId() == client->ip()); - if ((*it)->computerId() == client->ip()) - { + if ((*it)->computerId() == client->ip()) { existing = *it; } - if ((*it)->isTutor()) - { + if ((*it)->isTutor()) { if ((*it)->client() != NULL) hasActiveTutor = true; } @@ -1291,21 +1268,17 @@ void MainWindow::onClientAuthenticated(Client* client) bool isTutor = false; - if (!hasActiveTutor) - { - for (int i = 0; i < _tutorList.size(); i++) - { + if (!hasActiveTutor) { + for (int i = 0; i < _tutorList.size(); i++) { // Check if client is possible tutor - if (client->ip() == _tutorList[i]) - { + if (client->ip() == _tutorList[i]) { isTutor = true; break; } } } // Clients ip already exists, but was not active. - if (existing != NULL) - { + if (existing != NULL) { // qDebug() << "Should go into this if clause."; existing->setTutor(isTutor); existing->assignClient(client); @@ -1325,8 +1298,7 @@ void MainWindow::onClientAuthenticated(Client* client) if (x >= _tilesX || y >= _tilesY) ok = false; - if (ok) - { + if (ok) { if (x < 0) x = 0; if (y < 0) @@ -1334,9 +1306,7 @@ void MainWindow::onClientAuthenticated(Client* client) qDebug("Move E"); cf->move(x * getTileWidthPx(), y * getTileHeightPx()); onPlaceFrame(true, cf); - } - else - { + } else { // Move to any free tile placeFrameInFreeSlot(cf); } @@ -1345,7 +1315,7 @@ void MainWindow::onClientAuthenticated(Client* client) // Assign client instance cf->assignClient(client); - resizeEvent(NULL); // This is where all the positioning should be + resizeEvent(NULL); // This is where all the positioning should be tellClientCurrentSituation(client); updateExamMode(); @@ -1362,12 +1332,10 @@ void MainWindow::onVncServerStateChange(Client* client) if (client == getClientFromId(_streamingSource)) EnableButtons(); - if (client->isActiveVncServer()) - { + if (client->isActiveVncServer()) { // apply the desired projection sources for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - if ( (*it)->client() != NULL) // Ignore offline clients - { + if ( (*it)->client() != NULL) { // Ignore offline clients if ( (*it)->client()->desiredProjectionSource() == client->id() ) (*it)->client()->startVncClient(client); else @@ -1377,14 +1345,10 @@ void MainWindow::onVncServerStateChange(Client* client) } // Dont forget to unlock the vnc server client->lockScreen(false); - } - else - { + } else { // VNC server stopped on some client or failed to start - reset local pending projection information - for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) - { - if ((*it)->client() != NULL) - { + for (QList::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it) { + if ((*it)->client() != NULL) { if ((*it)->client()->desiredProjectionSource() == client->id()) { (*it)->client()->setDesiredProjectionSource(NO_SOURCE); (*it)->client()->stopVncClient(); @@ -1397,7 +1361,7 @@ void MainWindow::onVncServerStateChange(Client* client) client->lockScreen(client->desiredProjectionSource() == NO_SOURCE && _mode == Mode::LockedUnicast); // If this was the current source remember that there is no source anymore and reset mode - if (client == getClientFromId(_streamingSource)){ + if (client == getClientFromId(_streamingSource)) { _streamingSource = NO_SOURCE; _mode = Mode::None; } @@ -1412,11 +1376,9 @@ void MainWindow::onVncServerStateChange(Client* client) */ void MainWindow::onVncClientStateChange(Client* client) { - if (client != NULL) - { + if (client != NULL) { // VNC Client stopped -> remove from watchers - if (!client->isActiveVncClient()) - { + if (!client->isActiveVncClient()) { // Only unset a desired Projection source if it has not changed meanwhile if (client->projectionSource() == client->desiredProjectionSource()) client->setDesiredProjectionSource(NO_SOURCE); @@ -1438,8 +1400,7 @@ void MainWindow::onVncClientStateChange(Client* client) break; } - if ( !(serverHasWatchers || _mode == Mode::Broadcast) ) - { + if ( !(serverHasWatchers || _mode == Mode::Broadcast) ) { Client* c = getClientFromId(client->projectionSource()); if (c != NULL) c->stopVncServer(); @@ -1453,10 +1414,10 @@ void MainWindow::onVncClientStateChange(Client* client) */ void MainWindow::DisableButtons() { - qDebug() << "DisableButtons()"; + qDebug() << "DisableButtons()"; _buttonLockTimer->start(); - foreach (QAction* a, _lockingButtons) - a->setDisabled(true); + foreach (QAction * a, _lockingButtons) + a->setDisabled(true); } /***************************************************************************//** @@ -1464,16 +1425,17 @@ void MainWindow::DisableButtons() */ void MainWindow::EnableButtons() { - qDebug() << "EnableButtons()"; + qDebug() << "EnableButtons()"; _buttonLockTimer->stop(); - foreach (QAction* a, _lockingButtons) - a->setEnabled(true); + foreach (QAction * a, _lockingButtons) + a->setEnabled(true); } -void MainWindow::onDeleteClient() { +void MainWindow::onDeleteClient() +{ // If no frame is selected, warning. - ConnectionFrame* frame = getSelectedFrame(); + ConnectionFrame* frame = getSelectedFrame(); if (frame == NULL) { QMessageBox::critical(this, tr("Selection"), tr("No client is selected.")); return; @@ -1482,20 +1444,20 @@ void MainWindow::onDeleteClient() { QMessageBox::critical(this, tr("Selection"), tr("This client is still connected.")); return; } else { - qDebug() << "Now delete the client"; - int ret = QMessageBox::question(this, "Warning", tr("Sure, You want to delete selected client?"), 0, 1, 2); - if (ret == 1) { - frame->hide(); - frame->deleteLater(); - _clientFrames.removeOne(frame); - lockContextButtons(); + qDebug() << "Now delete the client"; + int ret = QMessageBox::question(this, "Warning", tr("Sure, You want to delete selected client?"), 0, 1, 2); + if (ret == 1) { + frame->hide(); + frame->deleteLater(); + _clientFrames.removeOne(frame); + lockContextButtons(); updateExamMode(); - return; - } else { - frame->move(frame->getPreviousPosition()); + return; + } else { + frame->move(frame->getPreviousPosition()); updateExamMode(); - return; - } + return; + } } diff --git a/src/server/mainwindow/mainwindow.h b/src/server/mainwindow/mainwindow.h index 3de0e1c..637628a 100644 --- a/src/server/mainwindow/mainwindow.h +++ b/src/server/mainwindow/mainwindow.h @@ -12,8 +12,9 @@ class DiscoveryListener; class HelpWindow; class ReloadRoomWindow; -namespace Ui{ - class MainWindow; +namespace Ui +{ +class MainWindow; } /** @@ -27,7 +28,7 @@ class MainWindow : public QMainWindow public: MainWindow(QWidget *parent = 0); - ~MainWindow(); + ~MainWindow(); private: @@ -41,29 +42,30 @@ private: Qt::ToolBarArea _tbArea; int _tilesX; int _tilesY; - QImage* _backgroundImage = NULL; + QImage* _backgroundImage = NULL; QLabel* _examModeLabel = NULL; - /* virtual columns to preserve the aspect ratio of the loaded room */ - int _virtCols; - int _virtRows; + /* virtual columns to preserve the aspect ratio of the loaded room */ + int _virtCols; + int _virtRows; // Button block stuff QTimer *_buttonLockTimer; QList _lockingButtons; static const qint64 _buttonBlockTime = 2000; - /* Context-sensitive Buttons */ - QList _contextButtons; + /* Context-sensitive Buttons */ + QList _contextButtons; // Management stuff - enum class Mode { - Broadcast, - Multicast, - Unicast, - LockedUnicast, - None + enum class Mode + { + Broadcast, + Multicast, + Unicast, + LockedUnicast, + None } _mode; int _streamingSource; int _countSessionNameUpdate; @@ -73,8 +75,8 @@ private: DiscoveryListener *_discoveryListener; QStringList _tutorList; - QPoint closestFreeSlot(QPoint preferredPixels, ConnectionFrame* toIgnore); - void placeFrameInFreeSlot(ConnectionFrame* frame, QPoint preferred = QPoint(0,0)); + QPoint closestFreeSlot(QPoint preferredPixels, ConnectionFrame* toIgnore); + void placeFrameInFreeSlot(ConnectionFrame* frame, QPoint preferred = QPoint(0, 0)); ConnectionFrame* createFrame(); ConnectionFrame* createFrame(QString computerId, QPoint position, QPoint gridPosition); bool loadPosition(QSharedPointer settings, const QString& id, int& x, int& y); @@ -92,19 +94,19 @@ private: void resizeEvent(QResizeEvent *e); void mouseReleaseEvent(QMouseEvent* e); - int getTileWidthPx() const; - int getTileHeightPx() const; + int getTileWidthPx() const; + int getTileHeightPx() const; - void lockContextButtons(); - void unlockContextButtons(); + void lockContextButtons(); + void unlockContextButtons(); - void switchRoomTo(QString); + void switchRoomTo(QString); protected slots: void onSessionNameClick(); void onSessionNameUpdate(); - void onDeleteClient(); + void onDeleteClient(); void onButtonLock(bool checked); void onButtonStudentToTutor(); diff --git a/src/server/net/certmanager.cpp b/src/server/net/certmanager.cpp index b85966a..e91fed3 100644 --- a/src/server/net/certmanager.cpp +++ b/src/server/net/certmanager.cpp @@ -1,94 +1,90 @@ -/* - # Copyright (c) 2009 - OpenSLX Project, Computer Center University of Freiburg - # - # This program is free software distributed under the GPL version 2. - # See http://openslx.org/COPYING - # - # If you have any feedback please consult http://openslx.org/feedback and - # send your suggestions, praise, or complaints to feedback@openslx.org - # - # General information about OpenSLX can be found at http://openslx.org/ - # ----------------------------------------------------------------------------- - # src/util/CertManager.cpp - # - Manage SSL certificates - # - provide access by name - # ----------------------------------------------------------------------------- - */ - -#include "certmanager.h" -#include "../util/util.h" -#include -#include -#include -#include -#include -#include - -namespace CertManager -{ -static QMap _certs; -static QMap _keys; - -static void generateFiles(QString& key, QString& cert); -static bool loadFiles(QString& keyFile, QString& certFile, QSslKey &key, QSslCertificate &cert); - -bool getPrivateKeyAndCert(const QString &name, QSslKey &key, QSslCertificate &cert) -{ - if (_keys.contains(name)) - { - key = _keys[name]; - cert = _certs[name]; - return true; - } - QString certFile = QDir::homePath().append("/").append(CERTSTORAGE).append(name); - QString keyFile = certFile; - keyFile.append(".rsa"); - certFile.append(".crt"); - // - if (!loadFiles(keyFile, certFile, key, cert)) - { - generateFiles(keyFile, certFile); - if (!loadFiles(keyFile, certFile, key, cert)) - qDebug() << "error while creating cert and key files\n"; - return false; - } - _certs.insert(name, cert); - _keys.insert(name, key); - return true; -} - -static bool loadFiles(QString& keyFile, QString& certFile, QSslKey &key, QSslCertificate &cert) -{ - QFileInfo keyInfo(keyFile); - QFileInfo certInfo(certFile); - if (keyInfo.exists() && certInfo.exists()) - { // Both files exist, see if they're valid and return - QFile kf(keyFile); - kf.open(QFile::ReadOnly); - key = QSslKey(&kf, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey); - QList certlist = QSslCertificate::fromPath(certFile); - if (!key.isNull() && !certlist.empty()) - { - cert = certlist.first(); - if (!cert.isNull()) - { - return true; - } - } - } - return false; -} - -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 3650 -newkey rsa:1024 -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); -} -} +/* + # Copyright (c) 2009 - OpenSLX Project, Computer Center University of Freiburg + # + # This program is free software distributed under the GPL version 2. + # See http://openslx.org/COPYING + # + # If you have any feedback please consult http://openslx.org/feedback and + # send your suggestions, praise, or complaints to feedback@openslx.org + # + # General information about OpenSLX can be found at http://openslx.org/ + # ----------------------------------------------------------------------------- + # src/util/CertManager.cpp + # - Manage SSL certificates + # - provide access by name + # ----------------------------------------------------------------------------- + */ + +#include "certmanager.h" +#include "../util/util.h" +#include +#include +#include +#include +#include +#include + +namespace CertManager +{ +static QMap _certs; +static QMap _keys; + +static void generateFiles(QString& key, QString& cert); +static bool loadFiles(QString& keyFile, QString& certFile, QSslKey &key, QSslCertificate &cert); + +bool getPrivateKeyAndCert(const QString &name, QSslKey &key, QSslCertificate &cert) +{ + if (_keys.contains(name)) { + key = _keys[name]; + cert = _certs[name]; + return true; + } + QString certFile = QDir::homePath().append("/").append(CERTSTORAGE).append(name); + QString keyFile = certFile; + keyFile.append(".rsa"); + certFile.append(".crt"); + // + if (!loadFiles(keyFile, certFile, key, cert)) { + generateFiles(keyFile, certFile); + if (!loadFiles(keyFile, certFile, key, cert)) + qDebug() << "error while creating cert and key files\n"; + return false; + } + _certs.insert(name, cert); + _keys.insert(name, key); + return true; +} + +static bool loadFiles(QString& keyFile, QString& certFile, QSslKey &key, QSslCertificate &cert) +{ + QFileInfo keyInfo(keyFile); + QFileInfo certInfo(certFile); + if (keyInfo.exists() && certInfo.exists()) { + // Both files exist, see if they're valid and return + QFile kf(keyFile); + kf.open(QFile::ReadOnly); + key = QSslKey(&kf, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey); + QList certlist = QSslCertificate::fromPath(certFile); + if (!key.isNull() && !certlist.empty()) { + cert = certlist.first(); + if (!cert.isNull()) { + return true; + } + } + } + return false; +} + +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 3650 -newkey rsa:1024 -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); +} +} diff --git a/src/server/net/certmanager.h b/src/server/net/certmanager.h index c69bc23..fee2691 100644 --- a/src/server/net/certmanager.h +++ b/src/server/net/certmanager.h @@ -1,29 +1,29 @@ -/* -# Copyright (c) 2009 - OpenSLX Project, Computer Center University of Freiburg -# -# This program is free software distributed under the GPL version 2. -# See http://openslx.org/COPYING -# -# If you have any feedback please consult http://openslx.org/feedback and -# send your suggestions, praise, or complaints to feedback@openslx.org -# -# General information about OpenSLX can be found at http://openslx.org/ -# ----------------------------------------------------------------------------- -# src/util/CertManager.cpp -# - Manage SSL certificates -# - provide access by name -# ----------------------------------------------------------------------------- -*/ - -#ifndef CERTMANAGER_H_ -#define CERTMANAGER_H_ - -#include -#include - -namespace CertManager -{ - bool getPrivateKeyAndCert(const QString &name, QSslKey &key, QSslCertificate &cert); -} - -#endif /* CERTMANAGER_H_ */ +/* +# Copyright (c) 2009 - OpenSLX Project, Computer Center University of Freiburg +# +# This program is free software distributed under the GPL version 2. +# See http://openslx.org/COPYING +# +# If you have any feedback please consult http://openslx.org/feedback and +# send your suggestions, praise, or complaints to feedback@openslx.org +# +# General information about OpenSLX can be found at http://openslx.org/ +# ----------------------------------------------------------------------------- +# src/util/CertManager.cpp +# - Manage SSL certificates +# - provide access by name +# ----------------------------------------------------------------------------- +*/ + +#ifndef CERTMANAGER_H_ +#define CERTMANAGER_H_ + +#include +#include + +namespace CertManager +{ +bool getPrivateKeyAndCert(const QString &name, QSslKey &key, QSslCertificate &cert); +} + +#endif /* CERTMANAGER_H_ */ diff --git a/src/server/net/client.cpp b/src/server/net/client.cpp index 84c45a9..5cd5c30 100644 --- a/src/server/net/client.cpp +++ b/src/server/net/client.cpp @@ -33,13 +33,13 @@ Client::Client(QSslSocket* socket) : _socket(socket) qDebug("*** Client %s created.", qPrintable(_socket->peerAddress().toString())); // Connect important signals connect(_socket, SIGNAL(disconnected()), - this, SLOT(disconnect())); + this, SLOT(disconnect())); connect(_socket, SIGNAL(error(QAbstractSocket::SocketError)), - this, SLOT(disconnect())); + this, SLOT(disconnect())); connect(_socket, SIGNAL(sslErrors(const QList &)), - this, SLOT(disconnect())); + this, SLOT(disconnect())); connect(_socket, SIGNAL(readyRead()), - this, SLOT(onDataArrival())); + this, SLOT(onDataArrival())); // Send challenge _challenge.resize(CHALLENGE_LEN); for (int i = 0; i < CHALLENGE_LEN; ++i) @@ -64,23 +64,18 @@ Client::~Client() /******************************************************************************/ void Client::timerEvent(QTimerEvent* event) { - if (event->timerId() == _timerPingTimeout) - { - if (_pingTimeout < QDateTime::currentMSecsSinceEpoch()) - { + if (event->timerId() == _timerPingTimeout) { + if (_pingTimeout < QDateTime::currentMSecsSinceEpoch()) { qDebug() << "Client" << _socket->peerAddress().toString() << "has a ping timeout."; killTimer(_timerPingTimeout); this->disconnect(); } - } - else if (event->timerId() == _timerIdAuthTimeout) - { + } else if (event->timerId() == _timerIdAuthTimeout) { // Client did not send login request within 3 seconds killTimer(_timerIdAuthTimeout); _timerIdAuthTimeout = 0; this->disconnect(); - } - else + } else killTimer(event->timerId()); } @@ -90,8 +85,7 @@ void Client::sendMessage(NetworkMessage& message) if (_socket->state() != QAbstractSocket::ConnectedState) return; message.writeMessage(_socket); - if (!message.writeComplete()) - { + if (!message.writeComplete()) { qCritical() << "SendMessage to client " << _name << "@" << _socket->peerAddress().toString() << " failed!"; } } @@ -99,8 +93,7 @@ void Client::sendMessage(NetworkMessage& message) /******************************************************************************/ void Client::requestThumb(const int width, const int height) { - if (_socket->state() != QAbstractSocket::ConnectedState) - { + if (_socket->state() != QAbstractSocket::ConnectedState) { qDebug("requestThumb called in bad state"); return; } @@ -115,25 +108,21 @@ void Client::requestThumb(const int width, const int height) void Client::onDataArrival() { // - if (_socket->state() != QAbstractSocket::ConnectedState) - { + if (_socket->state() != QAbstractSocket::ConnectedState) { qDebug("dataArrival called in bad state"); return; } bool ret; - while (_socket->bytesAvailable() > 0) - { + while (_socket->bytesAvailable() > 0) { ret = _fromClient.readMessage(_socket); // let the message read data from socket - if (ret == NM_READ_FAILED) // error parsing msg, disconnect client! - { + if (ret == NM_READ_FAILED) { // error parsing msg, disconnect client! this->disconnect(); return; } if (ret == NM_READ_INCOMPLETE) return; - if (_fromClient.readComplete()) // message is complete - { + if (_fromClient.readComplete()) { // message is complete this->handleMsg(); _fromClient.reset(); } @@ -145,47 +134,35 @@ void Client::handleMsg() { _pingTimeout = QDateTime::currentMSecsSinceEpoch() + PING_TIMEOUT_MS; const QString &id = _fromClient.getFieldString(_ID); - if (id.isEmpty()) - { + if (id.isEmpty()) { qDebug("Received message with empty ID field. ignored."); return; } - if (_authed == 2) - { + if (_authed == 2) { // Following messages are only valid of the client is already authenticated - if (id == _THUMB) - { + if (id == _THUMB) { QPixmap pixmap; const QByteArray& rawImage = _fromClient.getFieldBytes("IMG"); /* size 0 means the client is in exam-mode and therefore doesn't send any thumbnail */ if (rawImage.size() > 0) { - if (!pixmap.loadFromData(rawImage)) - { + if (!pixmap.loadFromData(rawImage)) { qDebug("Could not decode thumbnail image from client."); return; } _rawRemoteScreen = QByteArray(rawImage); emit thumbUpdated(this, pixmap, rawImage); } - } - else if (id == _VNCSERVER) - { + } else if (id == _VNCSERVER) { // Client tells about startup of vnc server const int port = _fromClient.getFieldString("PORT").toInt(); - if (port <= 0) - { - if (_vncPort <= 0) - { - qDebug() << "Starting VNC server on client" << _name << " (" << _socket->peerAddress().toString()+_vncPort << ") failed."; - } - else - { + if (port <= 0) { + if (_vncPort <= 0) { + qDebug() << "Starting VNC server on client" << _name << " (" << _socket->peerAddress().toString() + _vncPort << ") failed."; + } else { qDebug() << "Client " << _name << " stopped its VNC server"; } - } - else - { + } else { _vncRoPass = _fromClient.getFieldString("ROPASS"); _vncRwPass = _fromClient.getFieldString("RWPASS"); qDebug() << "Client " << _name << " started its VNC server"; @@ -193,20 +170,15 @@ void Client::handleMsg() _vncPort = port; emit vncServerStateChange(this); emit stateChanged(); - } - else if (id == _VNCCLIENT) - { + } else if (id == _VNCCLIENT) { // Client tells us that it started or stopped displaying a remote screen via VNC const int projectionSource = (int)_fromClient.getFieldString("CLIENTID").toInt(); - if (_fromClient.getFieldString("ENABLED").toInt() != 0) - { + if (_fromClient.getFieldString("ENABLED").toInt() != 0) { qDebug() << "Client " << _name << " started its VNC client (watching " << projectionSource << ")"; _projectionSource = projectionSource; _isActiveVncClient = true; emit vncClientStateChange(this); - } - else - { + } else { qDebug() << "Client " << _name << " stopped its VNC client (watched " << projectionSource << ")"; _isActiveVncClient = false; emit vncClientStateChange(this); @@ -217,10 +189,8 @@ void Client::handleMsg() } // Not authed yet, only care about login requests - if (_authed == 1) - { - if (id == _LOGIN) - { + if (_authed == 1) { + if (id == _LOGIN) { killTimer(_timerIdAuthTimeout); _timerIdAuthTimeout = 0; ClientLogin request; @@ -233,8 +203,7 @@ void Client::handleMsg() qDebug() << "Login request by " << request.name << (request.examMode ? "(in exam mode)" : ""); // emit event, see if request is accepted emit authenticating(this, &request); - if (!request.accept) - { + if (!request.accept) { qDebug("Request denied."); this->disconnect(); // Nope return; @@ -253,16 +222,14 @@ void Client::handleMsg() } // Did not pass challenge yet - if (_authed == 0) - { + if (_authed == 0) { // Waiting for challenge reply by client - if (id == _CHALLENGE) - { + if (id == _CHALLENGE) { QByteArray hash(_fromClient.getFieldBytes(_HASH)); QByteArray challenge(_fromClient.getFieldBytes(_CHALLENGE)); if (genSha1(&Global::sessionNameArray(), &_challenge) != hash - && !(Global::getCurrentRoom()->clientPositions.contains(_socket->peerAddress().toString()))) - { // Challenge reply is invalid, drop client + && !(Global::getCurrentRoom()->clientPositions.contains(_socket->peerAddress().toString()))) { + // Challenge reply is invalid, drop client NetworkMessage msgErr; msgErr.buildErrorMessage("Challenge reply invalid."); msgErr.writeMessage(_socket); @@ -310,8 +277,7 @@ void Client::startVncClient(const Client * const to) msg.setField("ROPASS", to->_vncRoPass); msg.setField("CLIENTID", QString::number(to->_id)); msg.setField("CAPTION", to->_name + " @ " + to->_host); - if (!to->_rawRemoteScreen.isEmpty()) - { + if (!to->_rawRemoteScreen.isEmpty()) { msg.setField(_THUMB, to->_rawRemoteScreen); } sendMessage(msg); @@ -333,18 +299,18 @@ void Client::stopVncClient() */ bool Client::isManagerMachine() { - foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) - if (address != QHostAddress(QHostAddress::LocalHost) - && this != NULL - && this->ip() == address.toString()) - return true; + foreach (const QHostAddress & address, QNetworkInterface::allAddresses()) + if (address != QHostAddress(QHostAddress::LocalHost) + && this != NULL + && this->ip() == address.toString()) + return true; return false; } /******************************************************************************/ void Client::lockScreen(bool lock) { - if (!_isTutor && _locked != lock && !isManagerMachine()){ + if (!_isTutor && _locked != lock && !isManagerMachine()) { _locked = lock; NetworkMessage msg; msg.setField(_ID, _LOCK); diff --git a/src/server/net/client.h b/src/server/net/client.h index 872d0e1..e7c9c5c 100644 --- a/src/server/net/client.h +++ b/src/server/net/client.h @@ -12,8 +12,7 @@ #define NO_SOURCE 0 -struct ClientLogin -{ +struct ClientLogin { bool accept; QString name; QString host; @@ -39,13 +38,13 @@ public: inline const bool isActiveVncClient() const { return _isActiveVncClient; } inline const bool isActiveVncServer() const { return _vncPort > 0; } inline const bool isLocked() const { return _locked; } - inline const int desiredProjectionSource(){ return _desiredSource; } + inline const int desiredProjectionSource() { return _desiredSource; } inline const int projectionSource() const { return _projectionSource; } inline const int isExamMode() const { return _isExamMode; } // Setters - inline void setTutor(bool enable){ _isTutor = enable; } - inline void setDesiredProjectionSource(int id){_desiredSource = id;} + inline void setTutor(bool enable) { _isTutor = enable; } + inline void setDesiredProjectionSource(int id) {_desiredSource = id;} inline void setExamMode(bool mode) { _isExamMode = mode; } //Send message stuff diff --git a/src/server/net/discoverylistener.cpp b/src/server/net/discoverylistener.cpp index 892ca53..8eb1091 100644 --- a/src/server/net/discoverylistener.cpp +++ b/src/server/net/discoverylistener.cpp @@ -55,21 +55,18 @@ DiscoveryListener::~DiscoveryListener() 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 + 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); } quint8 data[16], len; - if (host.protocol() == QAbstractSocket::IPv4Protocol) - { + if (host.protocol() == QAbstractSocket::IPv4Protocol) { // IPv4 quint32 addr = host.toIPv4Address(); len = 4; memcpy(data, &addr, len); - } - else if (QAbstractSocket::IPv6Protocol) - { + } else if (QAbstractSocket::IPv6Protocol) { // IPv6 len = 16; // Fast version (might break with future qt versions) @@ -79,9 +76,7 @@ static quint16 hash(const QHostAddress& host) for (int i = 0; i < len; ++i) data[i] = addr[i]; */ - } - else - { + } else { // Durr? len = 2; data[0] = (quint16)qrand(); @@ -89,8 +84,7 @@ static quint16 hash(const QHostAddress& host) } quint16 result = 0; quint16 mod = seed1; - for (quint8 i = 0; i < len; ++i) - { + for (quint8 i = 0; i < len; ++i) { result = ((result << 1) + data[i]) ^ mod; // because of the shift this algo is not suitable for len(input) > 8 mod += seed2 + data[i]; } @@ -107,8 +101,7 @@ static quint16 hash(const QHostAddress& host) */ void DiscoveryListener::timerEvent(QTimerEvent* event) { - for (int i = 0; i < SPAM_MODERATE_AT_ONCE; ++i) - { + for (int i = 0; i < SPAM_MODERATE_AT_ONCE; ++i) { if (++_counterResetPos >= SD_PACKET_TABLE_SIZE) _counterResetPos = 0; if (_packetCounter[_counterResetPos] > 10) @@ -130,14 +123,12 @@ void DiscoveryListener::onReadyRead() char data[UDPBUFSIZ]; QHostAddress addr; quint16 port; - while (_socket.hasPendingDatagrams()) - { + while (_socket.hasPendingDatagrams()) { const qint64 size = _socket.readDatagram(data, UDPBUFSIZ, &addr, &port); if (size <= 0) continue; const quint16 bucket = hash(addr) % SD_PACKET_TABLE_SIZE; - if (_packetCounter[bucket] > SPAM_CUTOFF) - { + if (_packetCounter[bucket] > SPAM_CUTOFF) { qDebug() << "SD: Potential (D)DoS from " << _socket.peerAddress().toString(); // emit some signal and pop up a big warning that someone is flooding/ddosing the PVS SD // ... on the other hand, will the user understand? ;) @@ -160,8 +151,7 @@ void DiscoveryListener::onReadyRead() continue; // If so, check if the submitted hash seems valid if (genSha1(&Global::sessionNameArray(), &salt1, &iplist) != hash && - !(Global::getCurrentRoom()->clientPositions.contains(addr.toString()))) - { + !(Global::getCurrentRoom()->clientPositions.contains(addr.toString()))) { // did not match local session name and client is not in same room. continue; } diff --git a/src/server/net/filedownloader.cpp b/src/server/net/filedownloader.cpp index aa27948..b930869 100644 --- a/src/server/net/filedownloader.cpp +++ b/src/server/net/filedownloader.cpp @@ -10,27 +10,32 @@ #include "filedownloader.h" FileDownloader::FileDownloader(QObject *parent) : - QObject(parent) { + QObject(parent) +{ connect(&m_WebCtrl, SIGNAL(finished(QNetworkReply*)), - SLOT(fileDownloaded(QNetworkReply*))); + SLOT(fileDownloaded(QNetworkReply*))); } -FileDownloader::~FileDownloader() { +FileDownloader::~FileDownloader() +{ } -void FileDownloader::connectSlot(QObject* obj, const char* slot) { +void FileDownloader::connectSlot(QObject* obj, const char* slot) +{ QObject::connect(this, SIGNAL(downloaded(QByteArray&)), - obj, slot); + obj, slot); } -void FileDownloader::fileDownloaded(QNetworkReply* pReply) { +void FileDownloader::fileDownloaded(QNetworkReply* pReply) +{ QByteArray downloadedData = pReply->readAll(); //emit a signal pReply->deleteLater(); emit downloaded(downloadedData); } -void FileDownloader::downloadFile(const QUrl& fileUrl) { +void FileDownloader::downloadFile(const QUrl& fileUrl) +{ m_WebCtrl.get(QNetworkRequest(fileUrl)); } diff --git a/src/server/net/listenserver.cpp b/src/server/net/listenserver.cpp index ba56177..1ce5016 100644 --- a/src/server/net/listenserver.cpp +++ b/src/server/net/listenserver.cpp @@ -31,8 +31,7 @@ ListenServer::~ListenServer() void ListenServer::newClientConnection() { QSslSocket* sock; - while ((sock = (QSslSocket*)_server.nextPendingConnection()) != NULL) - { + while ((sock = (QSslSocket*)_server.nextPendingConnection()) != NULL) { Client* client = new Client(sock); // TODO: what happens with disconnected clients emit newClient(client); } diff --git a/src/server/net/sslserver.cpp b/src/server/net/sslserver.cpp index ffbf262..3d8f924 100644 --- a/src/server/net/sslserver.cpp +++ b/src/server/net/sslserver.cpp @@ -46,15 +46,12 @@ void SslServer::incomingConnection(int socketDescriptor) serverSocket->setPeerVerifyMode(QSslSocket::VerifyNone); serverSocket->setProtocol(QSsl::TlsV1SslV3); //printf("Keylen %d\n", serverSocket->privateKey().length()); - if (serverSocket->setSocketDescriptor(socketDescriptor)) - { + if (serverSocket->setSocketDescriptor(socketDescriptor)) { // Once the connection is successfully encrypted, raise our newConnection event connect(serverSocket, SIGNAL(encrypted()), this, SIGNAL(newConnection())); serverSocket->startServerEncryption(); _pending.push_back(serverSocket); - } - else - { + } else { serverSocket->deleteLater(); } } @@ -67,8 +64,7 @@ void SslServer::sslErrors(const QList & errors) void SslServer::timerEvent(QTimerEvent* event) { // Remove all sockets marked for deletion - while (!_delete.isEmpty()) - { + while (!_delete.isEmpty()) { QSslSocket *sock = _delete.takeFirst(); sock->blockSignals(true); sock->deleteLater(); @@ -79,8 +75,7 @@ void SslServer::timerEvent(QTimerEvent* event) bool SslServer::hasPendingConnections() { - for (QList::iterator it(_pending.begin()); it != _pending.end(); it++) - { + for (QList::iterator it(_pending.begin()); it != _pending.end(); it++) { qDebug("State: %d - Encrypted: %d", (int)(*it)->state(), (*it)->isEncrypted()); if ((*it)->state() == QAbstractSocket::ConnectedState && (*it)->isEncrypted()) return true; @@ -90,10 +85,8 @@ bool SslServer::hasPendingConnections() QTcpSocket* SslServer::nextPendingConnection() { - for (QList::iterator it(_pending.begin()); it != _pending.end(); it++) - { - if ((*it)->state() == QAbstractSocket::ConnectedState && (*it)->isEncrypted()) - { + for (QList::iterator it(_pending.begin()); it != _pending.end(); it++) { + if ((*it)->state() == QAbstractSocket::ConnectedState && (*it)->isEncrypted()) { QSslSocket *sock = *it; QObject::disconnect(sock, SIGNAL(encrypted()), this, SIGNAL(newConnection())); _pending.removeAll(sock); @@ -101,10 +94,8 @@ QTcpSocket* SslServer::nextPendingConnection() return sock; } } - for (QList::iterator it(_delete.begin()); it != _delete.end(); it++) - { - if ((*it)->state() == QAbstractSocket::ConnectedState && (*it)->isEncrypted()) - { + for (QList::iterator it(_delete.begin()); it != _delete.end(); it++) { + if ((*it)->state() == QAbstractSocket::ConnectedState && (*it)->isEncrypted()) { QSslSocket *sock = *it; QObject::disconnect(sock, SIGNAL(encrypted()), this, SIGNAL(newConnection())); _pending.removeAll(sock); diff --git a/src/server/numerickeyboard/numerickeyboard.cpp b/src/server/numerickeyboard/numerickeyboard.cpp index 3f59eb8..d819a58 100644 --- a/src/server/numerickeyboard/numerickeyboard.cpp +++ b/src/server/numerickeyboard/numerickeyboard.cpp @@ -7,30 +7,30 @@ using std::endl; NumericKeyboard::NumericKeyboard(QWidget *parent) : - QGroupBox(parent), - ui(new Ui::NumericKeyboard) + QGroupBox(parent), + ui(new Ui::NumericKeyboard) { - ui->setupUi(this); - /* das geht leider nicht ? */ + ui->setupUi(this); + /* das geht leider nicht ? */ // connect(ui->button_0, SIGNAL (clicked(bool)), this, SLOT (relayDigit(0))); - 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, 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_del, SIGNAL (clicked(bool)), this, SLOT(relayDelete())); + connect(ui->button_del, SIGNAL (clicked(bool)), this, SLOT(relayDelete())); } NumericKeyboard::~NumericKeyboard() { - delete ui; + delete ui; } void NumericKeyboard::relayDigit0() { emit digitTyped(0); } @@ -43,4 +43,4 @@ void NumericKeyboard::relayDigit6() { emit digitTyped(6); } void NumericKeyboard::relayDigit7() { emit digitTyped(7); } void NumericKeyboard::relayDigit8() { emit digitTyped(8); } void NumericKeyboard::relayDigit9() { emit digitTyped(9); } -void NumericKeyboard::relayDelete() { emit digitDelete(); } +void NumericKeyboard::relayDelete() { emit digitDelete(); } diff --git a/src/server/numerickeyboard/numerickeyboard.h b/src/server/numerickeyboard/numerickeyboard.h index dce7999..3ece99c 100644 --- a/src/server/numerickeyboard/numerickeyboard.h +++ b/src/server/numerickeyboard/numerickeyboard.h @@ -3,37 +3,38 @@ #include -namespace Ui { +namespace Ui +{ class NumericKeyboard; } class NumericKeyboard : public QGroupBox { - Q_OBJECT + Q_OBJECT public: - explicit NumericKeyboard(QWidget *parent = 0); - ~NumericKeyboard(); + explicit NumericKeyboard(QWidget *parent = 0); + ~NumericKeyboard(); private: - Ui::NumericKeyboard *ui; + Ui::NumericKeyboard *ui; signals: - void digitTyped(int); - void digitDelete(); + void digitTyped(int); + void digitDelete(); private slots: - void relayDigit0(); - void relayDigit1(); - void relayDigit2(); - void relayDigit3(); - void relayDigit4(); - void relayDigit5(); - void relayDigit6(); - void relayDigit7(); - void relayDigit8(); - void relayDigit9(); - void relayDelete(); + void relayDigit0(); + void relayDigit1(); + void relayDigit2(); + void relayDigit3(); + void relayDigit4(); + void relayDigit5(); + void relayDigit6(); + void relayDigit7(); + void relayDigit8(); + void relayDigit9(); + void relayDelete(); }; diff --git a/src/server/reloadroomwindow/reloadroomwindow.h b/src/server/reloadroomwindow/reloadroomwindow.h index 9ce0aba..2d2ae85 100644 --- a/src/server/reloadroomwindow/reloadroomwindow.h +++ b/src/server/reloadroomwindow/reloadroomwindow.h @@ -3,7 +3,8 @@ #include -namespace Ui { +namespace Ui +{ class ReloadRoom; } diff --git a/src/server/sessionnamewindow/sessionnamewindow.cpp b/src/server/sessionnamewindow/sessionnamewindow.cpp index ba67557..6ffbeca 100644 --- a/src/server/sessionnamewindow/sessionnamewindow.cpp +++ b/src/server/sessionnamewindow/sessionnamewindow.cpp @@ -30,11 +30,11 @@ SessionNameWindow::SessionNameWindow(QWidget *parent) : connect(ui->bboxOkCancel, SIGNAL(rejected()), this, SLOT(close())); connect(ui->cmdRandom, SIGNAL(clicked(bool)), this, SLOT(onGenerateRandomName())); - /* add a virtual numeric keyboard */ - NumericKeyboard *keyboard = new NumericKeyboard(); - ui->keyboard_placeholder->addWidget(keyboard); - connect(keyboard, SIGNAL(digitTyped(int)), this, SLOT(onDigitTyped(int))); - connect(keyboard, SIGNAL(digitDelete()), this, SLOT(onDigitDelete())); + /* add a virtual numeric keyboard */ + NumericKeyboard *keyboard = new NumericKeyboard(); + ui->keyboard_placeholder->addWidget(keyboard); + connect(keyboard, SIGNAL(digitTyped(int)), this, SLOT(onDigitTyped(int))); + connect(keyboard, SIGNAL(digitDelete()), this, SLOT(onDigitDelete())); } @@ -76,14 +76,16 @@ void SessionNameWindow::onGenerateRandomName() } /** deletes the last digit of the saved sessionname */ -void SessionNameWindow::onDigitDelete() { - QString text = ui->lineEditName->text(); - ui->lineEditName->setText(text.left(text.length() - 1)); +void SessionNameWindow::onDigitDelete() +{ + QString text = ui->lineEditName->text(); + ui->lineEditName->setText(text.left(text.length() - 1)); } /** appends the digit to the session name */ -void SessionNameWindow::onDigitTyped(int i) { - QString text = ui->lineEditName->text(); - ui->lineEditName->setText(text + QString::number(i)); +void SessionNameWindow::onDigitTyped(int i) +{ + QString text = ui->lineEditName->text(); + ui->lineEditName->setText(text + QString::number(i)); } diff --git a/src/server/sessionnamewindow/sessionnamewindow.h b/src/server/sessionnamewindow/sessionnamewindow.h index b3e6cdc..2338def 100644 --- a/src/server/sessionnamewindow/sessionnamewindow.h +++ b/src/server/sessionnamewindow/sessionnamewindow.h @@ -4,7 +4,8 @@ #include -namespace Ui{ +namespace Ui +{ class SessionName; } @@ -27,9 +28,9 @@ protected: private slots: void onOkClicked(); void onGenerateRandomName(); - void onDigitDelete(); - void onDigitTyped(int); - + void onDigitDelete(); + void onDigitTyped(int); + signals: void updateSessionName(); diff --git a/src/server/util/global.cpp b/src/server/util/global.cpp index 990eee1..97c0355 100644 --- a/src/server/util/global.cpp +++ b/src/server/util/global.cpp @@ -36,31 +36,33 @@ void Global::setCurrentRoom(QString room) Global::_currentRoom = room; } -const Room* Global::getCurrentRoom() { - if (_rooms.contains(_currentRoom)) { - return _rooms[_currentRoom]; - } else { - static Room* defaultRoom = NULL; - if (defaultRoom == NULL) { - defaultRoom = new Room(QMap(), QSize(8, 6), QSize(1,1), "", ""); - } - return defaultRoom; - } +const Room* Global::getCurrentRoom() +{ + if (_rooms.contains(_currentRoom)) { + return _rooms[_currentRoom]; + } else { + static Room* defaultRoom = NULL; + if (defaultRoom == NULL) { + defaultRoom = new Room(QMap(), QSize(8, 6), QSize(1, 1), "", ""); + } + return defaultRoom; + } } -bool Global::manager_only = false; +bool Global::manager_only = false; bool Global::_isExam = false; QString Global::_iniPath = ""; -QSharedPointer Global::getSettings() { - QSharedPointer set; - if (_iniPath == "") { - /* default location (system scope) */ - set = QSharedPointer(new QSettings(QSettings::IniFormat, QSettings::SystemScope, "openslx/pvs2", "pvs2")); - } else { - /* use _iniPath to find ini file */ - set = QSharedPointer(new QSettings(Global::_iniPath, QSettings::IniFormat)); - } - set->setIniCodec("UTF-8"); - return set; +QSharedPointer Global::getSettings() +{ + QSharedPointer set; + if (_iniPath == "") { + /* default location (system scope) */ + set = QSharedPointer(new QSettings(QSettings::IniFormat, QSettings::SystemScope, "openslx/pvs2", "pvs2")); + } else { + /* use _iniPath to find ini file */ + set = QSharedPointer(new QSettings(Global::_iniPath, QSettings::IniFormat)); + } + set->setIniCodec("UTF-8"); + return set; } diff --git a/src/server/util/global.h b/src/server/util/global.h index 6ab1c42..ce1c2ab 100644 --- a/src/server/util/global.h +++ b/src/server/util/global.h @@ -19,31 +19,32 @@ #include struct Room { - Room(QMap cPos, QSize grid, QSize client, QString image, QString tutor) : - clientPositions(cPos), - gridSize(grid), - clientSize(client), - imagePath(image), - tutorIP(tutor){}; - QMap clientPositions; - QSize gridSize; - QSize clientSize; - QString imagePath; - QString tutorIP; + Room(QMap cPos, QSize grid, QSize client, QString image, QString tutor) : + clientPositions(cPos), + gridSize(grid), + clientSize(client), + imagePath(image), + tutorIP(tutor) {}; + QMap clientPositions; + QSize gridSize; + QSize clientSize; + QString imagePath; + QString tutorIP; }; -class Global { +class Global +{ private: - Global(){} - ~Global(){} + Global() {} + ~Global() {} static QString _sessionName; static QByteArray _sessionNameArray; static QMap _rooms; static QString _currentRoom; - static bool _isExam; - static QString _iniPath; + static bool _isExam; + static QString _iniPath; public: static const QString& sessionName() { return Global::_sessionName; } @@ -51,26 +52,27 @@ public: static void setSessionName(const QString& name); static void setSessionName(); - static bool manager_only; + static bool manager_only; static void setRooms(const QMap & roomList); - static const QMap & getRooms() { + static const QMap & getRooms() + { return _rooms; } - static void setIniPath(QString s) {_iniPath = s;}; - static QString getIniPath() { return _iniPath; }; - static QSharedPointer getSettings(); + static void setIniPath(QString s) {_iniPath = s;}; + static QString getIniPath() { return _iniPath; }; + static QSharedPointer getSettings(); - static bool isExam() { return _isExam; } - static void setExam(bool b) { _isExam = b; } + static bool isExam() { return _isExam; } + static void setExam(bool b) { _isExam = b; } static void setCurrentRoom(QString room); static const QString& getCurrentRoomName() { return _currentRoom; } - /* returns a pointer to the current room or a pointer to the constant "defaultRoom". - * (NEVER returns NULL or undefined) */ - static const Room* getCurrentRoom(); + /* returns a pointer to the current room or a pointer to the constant "defaultRoom". + * (NEVER returns NULL or undefined) */ + static const Room* getCurrentRoom(); }; diff --git a/src/shared/network.cpp b/src/shared/network.cpp index 6dd6a73..392cd43 100644 --- a/src/shared/network.cpp +++ b/src/shared/network.cpp @@ -29,8 +29,7 @@ QString interfaceAddressesToString(const QList& list) { QString ret; ret.reserve(500); - for (QList::const_iterator it(list.begin()); it != list.end(); ++it) - { + for (QList::const_iterator it(list.begin()); it != list.end(); ++it) { if (*it == QHostAddress::LocalHost || *it == QHostAddress::LocalHostIPv6) continue; // TODO: Filter other addresses/ranges? ret.append("|"); diff --git a/src/shared/networkmessage.cpp b/src/shared/networkmessage.cpp index 6ab5d78..61a29ea 100644 --- a/src/shared/networkmessage.cpp +++ b/src/shared/networkmessage.cpp @@ -69,8 +69,7 @@ NetworkMessage::~NetworkMessage() inline void NetworkMessage::allocBuffer() { - if (_lastBufferSize < _bufferSize || _buffer == NULL) - { + if (_lastBufferSize < _bufferSize || _buffer == NULL) { if (_buffer) delete[] _buffer; _lastBufferSize = _bufferSize; @@ -81,23 +80,19 @@ inline void NetworkMessage::allocBuffer() int NetworkMessage::readMessage(QAbstractSocket* socket) { // Check/Set the _mode variable, so read and write calls are not mixed - if (_mode != 1) - { - if (_mode != 0) - { + if (_mode != 1) { + if (_mode != 0) { qDebug("NetworkMessage::readMessage(TCP) called when class was in mode %d!", _mode); return NM_READ_FAILED; } _mode = 1; } // buffer size == 0 means the header hasn't been received yet. do so and set things up - if (_bufferSize == 0) - { + if (_bufferSize == 0) { if (socket->bytesAvailable() < HEADER_LEN) return NM_READ_INCOMPLETE; char header[HEADER_LEN]; - if (socket->read(header, HEADER_LEN) != HEADER_LEN) - { + if (socket->read(header, HEADER_LEN) != HEADER_LEN) { qDebug("FIXME: Socket said 8 bytes available, but could not read 8..."); return NM_READ_FAILED; } @@ -106,22 +101,18 @@ int NetworkMessage::readMessage(QAbstractSocket* socket) //qDebug() << "Expecting message of " << _bufferSize << " bytes"; allocBuffer(); } - if (_bufferSize > _bufferPos) - { - while (_bufferSize > _bufferPos && socket->bytesAvailable() > 0) - { + if (_bufferSize > _bufferPos) { + while (_bufferSize > _bufferPos && socket->bytesAvailable() > 0) { const qint64 ret = socket->read(_buffer + _bufferPos, _bufferSize - _bufferPos); //qDebug() << "Read " << ret << " bytes"; - if (ret < 0) - { + if (ret < 0) { qDebug("Socket read failed (TCP), return code %d", (int)ret); return NM_READ_FAILED; } _bufferPos += ret; //qDebug() << "Buffer has now " << _bufferPos << " of " << _bufferSize << " bytes"; } - if (_bufferSize == _bufferPos) - { + if (_bufferSize == _bufferPos) { if (!this->parseMessage(_buffer)) return NM_READ_FAILED; } @@ -132,24 +123,20 @@ int NetworkMessage::readMessage(QAbstractSocket* socket) int NetworkMessage::readMessage(char* data, quint32 len) { // Check/Set the _mode variable, so read and write calls are not mixed - if (_mode != 1) - { - if (_mode != 0) - { + if (_mode != 1) { + if (_mode != 0) { qDebug("NetworkMessage::readMessage(UDP) called when class was in mode %d!", _mode); return NM_READ_FAILED; } _mode = 1; } - if (len < HEADER_LEN) - { + if (len < HEADER_LEN) { qDebug("UDP message shorter than 8 bytes. ignored."); return NM_READ_FAILED; } if (!this->parseHeader(data)) return NM_READ_FAILED; - if (len != _bufferSize + HEADER_LEN) - { + if (len != _bufferSize + HEADER_LEN) { qDebug("UDP packet has wrong size. Is %d, expected %d", (int)_bufferSize, len - HEADER_LEN); return NM_READ_FAILED; } @@ -158,20 +145,17 @@ int NetworkMessage::readMessage(char* data, quint32 len) bool NetworkMessage::parseHeader(char *header) { - if (header[0] != 'P' || header[1] != 'V' || header[2] != 'S' || header[3] != '2') - { + if (header[0] != 'P' || header[1] != 'V' || header[2] != 'S' || header[3] != '2') { qDebug("Protocol magic wrong."); return false; } _bufferPos = 0; _bufferSize = _ntohl(*(quint32*)(header + 4)); - if (_bufferSize > MAX_MSG_LEN) - { + if (_bufferSize > MAX_MSG_LEN) { qDebug("Disconnecting Client: MAX_MSG_LEN exceeded."); return false; } - if (_bufferSize < 4) // TODO: magic number. msg needs to be at least 4 bytes for 1 key/value pair of length 0 each. - { + if (_bufferSize < 4) { // TODO: magic number. msg needs to be at least 4 bytes for 1 key/value pair of length 0 each. qDebug("A Client sent an empty message."); return false; } @@ -181,16 +165,14 @@ bool NetworkMessage::parseHeader(char *header) bool NetworkMessage::parseMessage(char *buffer) { char *ptr = buffer; - while (_bufferSize - (ptr - buffer) >= 4) - { + while (_bufferSize - (ptr - buffer) >= 4) { const quint16 keyLen = _ntohs(*(quint16*)(ptr)); ptr += 2; const quint16 valLen = _ntohs(*(quint16*)(ptr)); ptr += 2; - if (_bufferSize - (ptr - buffer) < keyLen + valLen) - { + if (_bufferSize - (ptr - buffer) < keyLen + valLen) { qDebug() << "Warning: Error parsing message. key(" << keyLen << ")+value(" << valLen - << ") length > total remaining bytes (" << (_bufferSize - (ptr - buffer)) << ")"; + << ") length > total remaining bytes (" << (_bufferSize - (ptr - buffer)) << ")"; return false; } _fields.insert(QByteArray(ptr, keyLen), QByteArray(ptr + keyLen, valLen)); @@ -203,10 +185,8 @@ bool NetworkMessage::parseMessage(char *buffer) bool NetworkMessage::writeMessage(QAbstractSocket * const socket) { - if (_mode != 2) - { - if (_mode == 1) - { + if (_mode != 2) { + if (_mode == 1) { qDebug("NetworkMessage::writeMessage called when class was in mode %d!", _mode); return false; } @@ -214,8 +194,7 @@ bool NetworkMessage::writeMessage(QAbstractSocket * const socket) _bufferPos = 0; } // key/value pairs have not been serialized yet... - if (_bufferSize == 0) - { + if (_bufferSize == 0) { this->serializeMessage(); } const qint64 ret = socket->write(_buffer + _bufferPos, _bufferSize - _bufferPos); @@ -224,8 +203,7 @@ bool NetworkMessage::writeMessage(QAbstractSocket * const socket) if (ret < 0) return false; _bufferPos += ret; - if (_bufferPos == _bufferSize) - { + if (_bufferPos == _bufferSize) { _bufferPos = 0; _mode = 4; } @@ -234,10 +212,8 @@ bool NetworkMessage::writeMessage(QAbstractSocket * const socket) bool NetworkMessage::writeMessage(QUdpSocket* socket, const QHostAddress& address, quint16 port) { - if (_mode != 4) - { - if (_mode == 1) - { + if (_mode != 4) { + if (_mode == 1) { qDebug("NetworkMessage::writeMessage called when class was in mode %d!", _mode); return false; } @@ -245,8 +221,7 @@ bool NetworkMessage::writeMessage(QUdpSocket* socket, const QHostAddress& addres _bufferPos = 0; } // key/value pairs have not been serialized yet... - if (_bufferSize == 0) - { + if (_bufferSize == 0) { this->serializeMessage(); } const qint64 ret = socket->writeDatagram(_buffer, _bufferSize, address, port); @@ -263,8 +238,7 @@ void NetworkMessage::serializeMessage() QByteArray buf; //qDebug() << "Default size: " << buf.capacity(); buf.reserve(_lastBufferSize > 0 ? _lastBufferSize : 200); - for (QHash::const_iterator it = _fields.begin(); it != _fields.end(); ++it) - { + for (QHash::const_iterator it = _fields.begin(); it != _fields.end(); ++it) { const QByteArray &ba = it.key(); const QByteArray &val = it.value(); quint16 keyLen = _htons((quint16)ba.size()); -- cgit v1.2.3-55-g7522