From bd7a10645fd5f02141f200509e0c18d17a1c7e87 Mon Sep 17 00:00:00 2001 From: Tobias Weiss Date: Fri, 10 Nov 2017 18:33:38 +0100 Subject: [PATCH 01/30] version 2.1.5 - merge from fork - most important change is the session starter tab (moved back from pop up) --- CHANGELOG.md | 11 + Labcontrol.pro | 8 +- data/Labcontrol.conf | 99 +++-- doc/manual.tex | 2 +- src/Lib/client.cpp | 127 +++--- src/Lib/client.h | 23 +- src/Lib/lablib.cpp | 22 +- src/Lib/lablib.h | 12 +- src/Lib/receipts_handler.cpp | 4 +- src/Lib/settings.cpp | 24 +- src/Lib/settings.h | 13 +- src/localzleafstarter.cpp | 9 + src/localzleafstarter.ui | 34 +- src/main.cpp | 2 +- src/mainwindow.cpp | 769 +++++++++++++++++++--------------- src/mainwindow.h | 27 +- src/mainwindow.ui | 778 +++++++++++++++++++++++++++++------ src/manualprintingsetup.cpp | 2 +- src/sessiondisplay.cpp | 34 -- src/sessiondisplay.h | 46 --- src/sessiondisplay.ui | 24 -- src/sessionstarter.cpp | 206 ---------- src/sessionstarter.h | 69 ---- src/sessionstarter.ui | 319 -------------- 24 files changed, 1386 insertions(+), 1278 deletions(-) delete mode 100755 src/sessiondisplay.cpp delete mode 100755 src/sessiondisplay.h delete mode 100755 src/sessiondisplay.ui delete mode 100755 src/sessionstarter.cpp delete mode 100755 src/sessionstarter.h delete mode 100755 src/sessionstarter.ui diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ac64fc..f7134cc 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,17 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed ### Removed +## [v2.1.5] - 2017-10-21 +### Added +* Dialog for Upload folder button +* Open browser on clients +* Full Control VNC Button +* LineEdit for zLeaf CMD +### Changed +* Session popup is now a tab +* Tab layout separated in prep / session / admin / info +* Version info displayed in info + ## [v2.1.0] - 2016-10-12 ### Added * Manual printing of _z-Tree_ payment files diff --git a/Labcontrol.pro b/Labcontrol.pro index 76cba58..64cf3b4 100755 --- a/Labcontrol.pro +++ b/Labcontrol.pro @@ -8,8 +8,6 @@ SOURCES += src/localzleafstarter.cpp \ src/main.cpp \ src/mainwindow.cpp \ src/manualprintingsetup.cpp \ - src/sessiondisplay.cpp \ - src/sessionstarter.cpp \ src/Lib/client.cpp \ src/Lib/clienthelpnotificationserver.cpp \ src/Lib/clientpinger.cpp \ @@ -25,8 +23,6 @@ SOURCES += src/localzleafstarter.cpp \ HEADERS += src/localzleafstarter.h \ src/mainwindow.h \ src/manualprintingsetup.h \ - src/sessiondisplay.h \ - src/sessionstarter.h \ src/Lib/client.h \ src/Lib/clienthelpnotificationserver.h \ src/Lib/clientpinger.h \ @@ -42,9 +38,7 @@ HEADERS += src/localzleafstarter.h \ FORMS += src/localzleafstarter.ui \ src/mainwindow.ui \ - src/manualprintingsetup.ui \ - src/sessiondisplay.ui \ - src/sessionstarter.ui + src/manualprintingsetup.ui QMAKE_CXXFLAGS += -std=c++11 diff --git a/data/Labcontrol.conf b/data/Labcontrol.conf index bf54f48..d04b702 100755 --- a/data/Labcontrol.conf +++ b/data/Labcontrol.conf @@ -1,11 +1,33 @@ [General] -# The user names of all users which shall be able to conduct administrative tasks with Labcontrol -admin_users="UserA|UserB|UserC" -# The browser in which ORSEE shall be displayed -browser_command=/usr/bin/firefox +### Server settings +# The IP of the server running zTree +server_ip=192.168.1.200 +# Network broadcast address +network_broadcast_address=192.168.1.255 +# The port which shall be used by zTree by default +initial_port=8000 # The port the client help server shall listen on client_help_server_port=XXXX -# Client settings +# User names of all users which shall be able to conduct administrative tasks with Labcontrol +admin_users="UserA|UserB|UserC" +# The public keys to access the clients as root +pkey_path_root=/usr/local/share/labcontrol/id_labclient_root +# The public keys to access the clients as unprivileged user +pkey_path_user=/usr/local/share/labcontrol/id_labclient_dsa +# The default name for locally started zLeaves +local_zLeaf_name=local +# Default dimension for locally started zLeaves +local_zLeaf_size=1280x1024 +# If multiple receipts are availabe, this indicates, which one will be shown by default (the index counting from 0 following an alphabetical ordering) +default_receipt_index=0 +# The URL address of your lab's ORSEE +orsee_url=http://yourORSEEserver.tld +# URLs to available webcams +webcams=http://user:pass@webcam_right|http://user:pass@webcam_left +# Display names for the webcams +webcams_names="Webcam right|Webcam left" + +### Client settings # The client settings are represented as an array. So the info of the first client stands in the first field in every section and the same is valid for the other clients with other indices each. client_ips=192.168.1.1|192.168.1.2|192.168.1.3|192.168.1.4|192.168.1.5|192.168.1.6|192.168.1.7|192.168.1.8|192.168.1.9|192.168.1.10|192.168.1.11|192.168.1.12|192.168.1.13|192.168.1.14|192.168.1.15|192.168.1.16|192.168.1.17|192.168.1.18|192.168.1.19|192.168.1.20|192.168.1.21|192.168.1.22|192.168.1.23|192.168.1.24 client_macs=00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00|00:00:00:00:00:00 @@ -16,50 +38,57 @@ client_quantity=24 # The following two coordinates specify where the client will be shown in the coordinate grid at the bottom of the Labcontrol screen client_xpos=1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24 client_ypos=1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1 -# If multiple receipts are availabe, this indicates, which one will be shown by default (the index counting from 0 following an alphabetical ordering) -default_receipt_index=0 -dvips_command=/usr/bin/dvips -file_manager=/usr/bin/dolphin -# The port which shall be used by zTree by default -initial_port=8000 +# The name of the user of the clients which is used to conduct experiments +user_name_on_clients=user + +### Binary paths +# Path to your lpr binary +lpr_command=/usr/bin/lpr +# Path to your netstat binary +netstat_command=/bin/netstat # The command used to kill 'zleaf.exe' instances (part of the 'psmisc' package) killall_command=/usr/bin/killall # Where all Labcontrol data got installed -labcontrol_installation_directory=/usr/local/share/labcontrol +#DOTO: REMOVE VAGUE NAME WHEN NOT NEEDED ANYMORE (AFTER 2.1.4 MIRGRATION) +labcontrol_data_directory=/usr/local/share/labcontrol +labcontrol_data_directory=/usr/local/share/labcontrol +# Path to your latex binary latex_command=/usr/bin/latex -# The default name for locally started zLeaves -local_zLeaf_name=local -local_zLeaf_size=1280x1024 -lpr_command=/usr/bin/lpr -netstat_command=/bin/netstat -network_broadcast_address=192.168.1.255 -# The URL address of your lab's ORSEE -orsee_url=http://yourORSEEserver.tld +# Path to your dvips binary +dvips_command=/usr/bin/dvips +# Path to your filemanager binary +file_manager=/usr/bin/dolphin +# Path to your ping binary ping_command=/bin/ping -# The public keys to access the clients -pkey_path_root=/usr/local/share/labcontrol/id_labclient_root -pkey_path_user=/usr/local/share/labcontrol/id_labclient_dsa +# Path to PDF/Postscript viewer binary postscript_viewer=/usr/bin/okular +# Path to ps2pdf binary ps2pdf_command=/usr/bin/ps2pdf +# Path to rm binary rm_command=/bin/rm +# Path to SCP binary scp_command=/usr/bin/scp -# The IP of the server running zTree -server_ip=192.168.1.200 +# The browser in which ORSEE shall be displayed +browser_command=/usr/bin/firefox +# Path to wmctrl binary ssh_command=/usr/bin/ssh +# Path to taskset binary taskset_command=/usr/bin/taskset -terminal_emulator_command=/usr/bin/konsole -# The name of the user of the clients which is used to conduct experiments -user_name_on_clients=user +# Path to terminal-emulator binary +terminal_emulator_command=/usr/bin/gnome-terminal +# Path to wine binary +wine_command=/usr/bin/wine +# Path to wmctrl binary +wmctrl_command=/usr/bin/wmctrl +# Path to xset binary +xset_command=/usr/bin/xset +# Path to VNC viewer binary vnc_viewer=/usr/bin/vinagre +# Path to wakeonlan binary wakeonlan_command=/usr/bin/wakeonlan # The program used to view the laboratory's webcams webcam_command=/usr/local/bin/WebcamDisplay -# URLs to available webcams -webcams="webcam_left|webcam_right" -wine_command=/usr/bin/wine -wmctrl_command=/usr/bin/wmctrl -xset_command=/usr/bin/xset # The folder were all zTree versions are installed (in subfolders matching the scheme zTree_X.Y.Z) ztree_installation_directory=/opt/z-Leaves -# Script to be called after session crash -restart_crashed_session_script=/home/scripts/start_zTree_after_crash.sh \ No newline at end of file +# Script to be called after session crash +restart_crashed_session_script=/home/scripts/start_zTree_after_crash.sh diff --git a/doc/manual.tex b/doc/manual.tex index 5bc94ed..107271a 100755 --- a/doc/manual.tex +++ b/doc/manual.tex @@ -93,7 +93,7 @@ Like already mentioned all \emph{z-Tree} and \emph{z-Leaf} versions should be co The directories in the \texttt{data} directory should be copied to the \emph{zTree installation directory}. -Afterwards place the \texttt{Labcontrol.conf} in a subfolder \texttt{Economic Laboratory} in the place where \emph{QSettings} stores its definitions on your platform (on \emph{Linux} this would be \texttt{/etc/xdg/Economic Laboratory/Labcontrol.conf}) and adjust it to your needs and prerequisites. +Afterwards place the \texttt{Labcontrol.conf} in a subfolder \texttt{Labcontrol} in the place where \emph{QSettings} stores its definitions on your platform (on \emph{Linux} this would be \texttt{/etc/xdg/Labcontrol/Labcontrol.conf}) and adjust it to your needs and prerequisites. To allow \emph{Labcontrol} to control the clients password-less public-key authentication must be available at least for the experiment user on the clients. For administration this is also required for \texttt{root}. Also all clients should be known by \texttt{ /etc/ssh/ssh\_known\_hosts}. This file must be readable by the users! If this is missing \emph{Labcontrol} will query the user on every connection attempt, which is not user-friendly. diff --git a/src/Lib/client.cpp b/src/Lib/client.cpp index 66d39ce..bd6d109 100755 --- a/src/Lib/client.cpp +++ b/src/Lib/client.cpp @@ -23,8 +23,10 @@ #include "client.h" #include "settings.h" +#include "lablib.h" extern std::unique_ptr< lc::Settings > settings; +extern std::unique_ptr< lc::Lablib > lablib; lc::Client::Client( const QString &argIP, const QString &argMAC, const QString &argName, unsigned short int argXPosition, unsigned short int argYPosition, @@ -105,22 +107,6 @@ void lc::Client::Boot() { GotStatusChanged( state_t::BOOTING ); } -void lc::Client::DeactiveScreensaver() { - QStringList arguments; - arguments << "-i" << settings->pkeyPathUser - << QString{ settings->userNameOnClients + "@" + ip } - << settings->xsetCmd << "-display" << ":0.0" << "dpms" << "force" << "on"; - - // Start the process - QProcess deactiveScreensaverProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - deactiveScreensaverProcess.setProcessEnvironment( env ); - deactiveScreensaverProcess.startDetached( settings->sshCmd, arguments ); - - // Output message via the debug messages tab - qDebug() << settings->sshCmd << arguments.join( " " ); -} - void lc::Client::GotStatusChanged( state_t argState ) { if ( ( protectedCycles > 0 ) && ( state == state_t::BOOTING ) && ( argState != state_t::RESPONDING ) ) { return; @@ -173,22 +159,13 @@ void lc::Client::OpenTerminal( const QString &argCommand, const bool &argOpenAsR QStringList *arguments = nullptr; arguments = new QStringList; if ( !argOpenAsRoot ) { - *arguments << "--title" << name << "-e" << - QString{ settings->sshCmd + " -i " + settings->pkeyPathUser + " " + *arguments << "-e" + << QString{ settings->sshCmd + " -i " + settings->pkeyPathUser + " " + settings->userNameOnClients + "@" + ip }; } else { - *arguments << "--title" << name << "-e" << + *arguments << "-e" << QString{ settings->sshCmd + " -i " + settings->pkeyPathRoot - + " " + "root@" + ip }; - } - - if ( settings->termEmulCmd.contains( "konsole" ) ) { - arguments->prepend( "--new-tab" ); - arguments->prepend( "--show-tabbar" ); - } else { - if ( settings->termEmulCmd.contains( "gnome-terminal" ) ) { - arguments->prepend( "--tab" ); - } + + " " + "root@" + ip}; } if ( !argCommand.isEmpty() ) { @@ -224,7 +201,7 @@ void lc::Client::SetStateToZLEAF_RUNNING( QString argClientIP ) { } } -void lc::Client::ShowDesktop() { +void lc::Client::ShowDesktopViewOnly() { QStringList arguments; arguments << ip; @@ -237,6 +214,19 @@ void lc::Client::ShowDesktop() { qDebug() << settings->vncViewer << arguments.join( " " ); } +void lc::Client::ShowDesktopFullControl() { + QStringList arguments; + arguments << ip + ":5901"; + + QProcess showDesktopProcess; + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + showDesktopProcess.setProcessEnvironment( env ); + showDesktopProcess.startDetached( settings->vncViewer, arguments ); + + // Output message via the debug messages tab + qDebug() << settings->vncViewer << arguments.join( " " ); +} + void lc::Client::Shutdown() { if ( state == state_t::NOT_RESPONDING || state == state_t::BOOTING || state == state_t::SHUTTING_DOWN ) { @@ -262,7 +252,7 @@ void lc::Client::Shutdown() { GotStatusChanged( state_t::SHUTTING_DOWN ); } -void lc::Client::StartZLeaf( const QString * const argFakeName ) { +void lc::Client::StartZLeaf( const QString * argFakeName, QString cmd ) { if ( state < state_t::RESPONDING || zLeafVersion.isEmpty() || GetSessionPort() < 7000 ) { return; } @@ -281,32 +271,18 @@ void lc::Client::StartZLeaf( const QString * const argFakeName ) { if ( ( messageBoxRunningZLeafFound.get() != nullptr && messageBoxRunningZLeafFound->clickedButton() - == messageBoxRunningZLeafFound->button( QMessageBox::Yes ) ) + == messageBoxRunningZLeafFound->button( QMessageBox::Yes ) ) || state != state_t::ZLEAF_RUNNING ) { QStringList arguments; - if ( argFakeName == nullptr && GetSessionPort() == 7000 ) { + if ( argFakeName == nullptr ) { arguments << "-i" << settings->pkeyPathUser << QString{ settings->userNameOnClients + "@" + ip } - << "DISPLAY=:0.0" << settings->tasksetCmd << "0x00000001" << settings->wineCmd - << QString{ settings->zTreeInstDir + "/zTree_" + GetzLeafVersion() + "/zleaf.exe" } - << "/server" << settings->serverIP; + << cmd; } else { - if ( argFakeName == nullptr ) { - arguments << "-i" << settings->pkeyPathUser - << QString{ settings->userNameOnClients + "@" + ip } - << "DISPLAY=:0.0" << settings->tasksetCmd << "0x00000001" << settings->wineCmd - << QString{ settings->zTreeInstDir + "/zTree_" + GetzLeafVersion() + "/zleaf.exe" } - << "/server" << settings->serverIP << "/channel" - << QString::number( GetSessionPort() - 7000 ); - } else { - arguments << "-i" << settings->pkeyPathUser - << QString{ settings->userNameOnClients + "@" + ip } - << "DISPLAY=:0.0" << settings->tasksetCmd << "0x00000001" << settings->wineCmd - << QString{ settings->zTreeInstDir + "/zTree_" + GetzLeafVersion() + "/zleaf.exe" } - << "/server" << settings->serverIP << "/channel" - << QString::number( GetSessionPort() - 7000 ) - << "/name" << *argFakeName; - } + arguments << "-i" << settings->pkeyPathUser + << QString{ settings->userNameOnClients + "@" + ip } + << cmd + << "/name" << *argFakeName; } // Start the process @@ -319,3 +295,50 @@ void lc::Client::StartZLeaf( const QString * const argFakeName ) { qDebug() << settings->sshCmd << arguments.join( " " ); } } + +void lc::Client::StartClientBrowser( const QString * const argURL, const bool * const argFullscreen ) { + //Declarations + QStringList arguments; + + // Build arguments list for SSH command + arguments << "-i" << settings->pkeyPathUser + << QString{ settings->userNameOnClients + "@" + ip } + << "DISPLAY=:0.0" + << settings->clientBrowserCmd + << *argURL; + + // Add fullscreen toggle if checked + if (*argFullscreen == true){ + arguments << "& sleep 3 && DISPLAY=:0.0 xdotool key --clearmodifiers F11"; + } + + // Start the process + QProcess startClientBrowserProcess; + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + startClientBrowserProcess.setProcessEnvironment( env ); + startClientBrowserProcess.startDetached( settings->sshCmd, arguments ); + + // Output message via the debug messages tab + qDebug() << settings->sshCmd << arguments.join( " " ); +} + +void lc::Client::StopClientBrowser() { + //Declarations + QStringList arguments; + + //Build arguments list + arguments << "-i" << settings->pkeyPathUser + << QString{ settings->userNameOnClients + "@" + ip } + << "killall" + << settings->clientBrowserCmd + << "& sleep 1 && rm -R /home/ewfuser/.mozilla/firefox/*"; + + // Start the process + QProcess startClientBrowserProcess; + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + startClientBrowserProcess.setProcessEnvironment( env ); + startClientBrowserProcess.startDetached( settings->sshCmd, arguments ); + + // Output message via the debug messages tab + qDebug() << settings->sshCmd << arguments.join( " " ); +} diff --git a/src/Lib/client.h b/src/Lib/client.h index 0b474bd..2b75897 100755 --- a/src/Lib/client.h +++ b/src/Lib/client.h @@ -96,23 +96,36 @@ public: void OpenFilesystem( const QString * const argUserToBeUsed ); /*! * \brief Opens a terminal for the client - * \param argCommand A command which shall be executed in the terminal window (Pass an empty QString if not wanted) + * \param argCommand A command which shall be executed in the terminal window (Pass an empty QString if not wanted) * \param argOpenAsRoot Run the terminal session as root (true) or as normal user (false) */ void OpenTerminal( const QString &argCommand, const bool &argOpenAsRoot ); void SetSessionPort( int argSP ) { sessionPort = argSP; } void SetzLeafVersion( const QString &argzLeafV ) { zLeafVersion = argzLeafV; } //! Shows the desktop of the given client - void ShowDesktop(); + void ShowDesktopViewOnly(); + void ShowDesktopFullControl(); /*! * \brief Shuts down the client */ void Shutdown(); - //! Starts a zLeaf instance on the client + + /*! + * \brief Starts a zLeaf instance on the client + * @param argFakeName The name the zLeaf instance shall have (if not the default, which is the hostname of the client) + */ + void StartZLeaf(const QString *argFakeName = nullptr, QString cmd = "" ); + + /*! + * \brief Opens a browser window on the client + * @param argURL URL to open in clients browser + */ + void StartClientBrowser( const QString *argURL = nullptr, const bool *argFullscreen = nullptr ); + /*! - @param argFakeName The name the zLeaf instance shall have (if not the default, which is the hostname of the client) + * \brief Closes all browser instances */ - void StartZLeaf( const QString * const argFakeName = nullptr ); + void StopClientBrowser(); private: const QString &GetzLeafVersion() const { return zLeafVersion; } diff --git a/src/Lib/lablib.cpp b/src/Lib/lablib.cpp index 1f82560..78fa67a 100755 --- a/src/Lib/lablib.cpp +++ b/src/Lib/lablib.cpp @@ -26,7 +26,7 @@ lc::Lablib::Lablib( QObject *argParent ) : QObject{ argParent }, - labSettings{ "Economic Laboratory", "Labcontrol", this }, + labSettings{ "Labcontrol", "Labcontrol", this }, sessionsModel{ new SessionsModel{ this } } { for ( const auto &s : settings->GetClients() ) { @@ -107,7 +107,7 @@ void lc::Lablib::ShowPreprints() { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); showPreprintsProcess.setProcessEnvironment( env ); QString program{ settings->fileMngr }; - QStringList arguments{ QStringList{} << settings->lcInstDir + "/preprints" }; + QStringList arguments{ QStringList{} << settings->lcDataDir + "/preprints" }; showPreprintsProcess.startDetached( program, arguments ); // Output message via the debug messages tab @@ -167,3 +167,21 @@ void lc::Lablib::SetLocalZLeafDefaultName( const QString &argName ) { settings->SetLocalzLeafName( argName ); labSettings.setValue( "local_zLeaf_name", argName ); } + +//Returns the commandline that is issued on the client when zleaf is started +QStringList lc::Lablib::getzLeafArgs( int sessionPort, QString zleafVersion ){ + QStringList arguments; + if ( sessionPort == 7000 ) { + arguments << "DISPLAY=:0.0" << settings->tasksetCmd << "0x00000001" << settings->wineCmd + << QString{ settings->zTreeInstDir + "/zTree_" + zleafVersion + "/zleaf.exe" } + << "/server" << settings->serverIP; + } else { + arguments << "DISPLAY=:0.0" << settings->tasksetCmd << "0x00000001" << settings->wineCmd + << QString{ settings->zTreeInstDir + "/zTree_" + zleafVersion + "/zleaf.exe" } + << "/server" << settings->serverIP << "/channel" + << QString::number( sessionPort- 7000 ); + } + + //Return the crafted QStringList + return arguments; +} diff --git a/src/Lib/lablib.h b/src/Lib/lablib.h index 865d94c..68764aa 100755 --- a/src/Lib/lablib.h +++ b/src/Lib/lablib.h @@ -88,13 +88,21 @@ public: void SetLocalZLeafDefaultName( const QString &argName ); void ShowOrsee(); void ShowPreprints(); - -public slots: void StartNewSession( QVector< Client* > argAssocCl, QString argParticipNameReplacement, bool argPrintLocalReceipts, QString argReceiptsHeader, QString argzTreeDataTargetPath, quint16 argzTreePort, QString argzTreeVersion ); + /*! + * \brief Returns the commandline to issue on the client(s) in order to start zLeaf + * @param sessionPort The port zLeaf shall connect to + * @param zLeafVersion zLeaf Version to start + */ + QStringList getzLeafArgs( int sessionPort, QString zleafVersion ); + + +public slots: + signals: void ZLEAF_RUNNING( QString argClientIP ); diff --git a/src/Lib/receipts_handler.cpp b/src/Lib/receipts_handler.cpp index d702b6a..c7f0f1b 100755 --- a/src/Lib/receipts_handler.cpp +++ b/src/Lib/receipts_handler.cpp @@ -255,11 +255,11 @@ QVector *lc::ReceiptsHandler::GetParticipantsDataFromPaymentFile() { QString *lc::ReceiptsHandler::LoadLatexHeader() { // Prepare all facilities to read the latex header file - QFile latexHeaderFile( settings->lcInstDir + "/" + latexHeaderName + "_header.tex" ); + QFile latexHeaderFile( settings->lcDataDir + "/" + latexHeaderName + "_header.tex" ); if ( !latexHeaderFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) { QMessageBox messageBox{ QMessageBox::Critical, tr( "LaTeX header could not be loaded" ), tr( "The LaTeX header at '%1/%2_header.tex' could not be loaded. Receipts printing will not work." ) - .arg( settings->lcInstDir ).arg( latexHeaderName ), QMessageBox::Ok }; + .arg( settings->lcDataDir ).arg( latexHeaderName ), QMessageBox::Ok }; messageBox.exec(); return nullptr; } diff --git a/src/Lib/settings.cpp b/src/Lib/settings.cpp index fb26344..7214061 100755 --- a/src/Lib/settings.cpp +++ b/src/Lib/settings.cpp @@ -31,6 +31,9 @@ lc::Settings::Settings( const QSettings &argSettings, QObject *argParent ) : browserCmd{ ReadSettingsItem( "browser_command", "Opening ORSEE in a browser will not work.", argSettings, true ) }, + clientBrowserCmd{ ReadSettingsItem( "client_browser_command", + "Opening a browser window on clients will not work.", + argSettings, false ) }, dvipsCmd{ ReadSettingsItem( "dvips_command", "Receipts creation will not work.", argSettings, true ) }, @@ -43,8 +46,8 @@ lc::Settings::Settings( const QSettings &argSettings, QObject *argParent ) : latexCmd{ ReadSettingsItem( "latex_command", "Receipts creation will not work.", argSettings, true ) }, - lcInstDir{ ReadSettingsItem( "labcontrol_installation_directory", - "Labcontrol will missbehave with high propability.", + lcDataDir{ ReadSettingsItem( "labcontrol_data_directory", + "Datapath not set. Labcontrol will missbehave with high propability.", argSettings, true ) }, localUserName{ GetLocalUserName() }, localzLeafSize{ ReadSettingsItem( "local_zLeaf_size", @@ -109,6 +112,8 @@ lc::Settings::Settings( const QSettings &argSettings, QObject *argParent ) : argSettings, true ) }, webcams{ argSettings.value( "webcams", "" ).toString().split( '|', QString::SkipEmptyParts, Qt::CaseInsensitive ) }, + webcams_names{ argSettings.value( "webcams_names", "" ).toString().split( '|', QString::SkipEmptyParts, + Qt::CaseInsensitive ) }, wineCmd{ ReadSettingsItem( "wine_command", "Running z-Leaves or z-Tree will be possible.", argSettings, true ) }, @@ -258,12 +263,12 @@ QMap< QString, lc::Client* > lc::Settings::CreateClIPsToClMap( const QVector< Cl QStringList lc::Settings::DetectInstalledLaTeXHeaders() const { QStringList tempLaTeXHeaders{ "None found" }; // Detect the installed LaTeX headers - if ( !lcInstDir.isEmpty() ) { - QDir laTeXDirectory{ lcInstDir, "*_header.tex", QDir::Name, + if ( !lcDataDir.isEmpty() ) { + QDir laTeXDirectory{ lcDataDir, "*_header.tex", QDir::Name, QDir::CaseSensitive | QDir::Files | QDir::Readable }; if ( !laTeXDirectory.exists() || laTeXDirectory.entryList().isEmpty() ) { qDebug() << "Receipts printing will not work. No LaTeX headers could be found in" - << lcInstDir; + << lcDataDir; } else { tempLaTeXHeaders = laTeXDirectory.entryList(); tempLaTeXHeaders.replaceInStrings( "_header.tex", "" ); @@ -375,3 +380,12 @@ QString lc::Settings::ReadSettingsItem( const QString &argVariableName, } return QString{}; } + +void lc::Settings::SetLocalzLeafSize( QString arg) { + localzLeafSize = arg; +} + +void lc::Settings::SetChosenZTreePort( const int argPort ){ + chosenzTreePort = argPort; +} + diff --git a/src/Lib/settings.h b/src/Lib/settings.h index f727369..685f66b 100755 --- a/src/Lib/settings.h +++ b/src/Lib/settings.h @@ -48,13 +48,16 @@ public: const int defaultReceiptIndex = 0; const QString browserCmd; + const QString clientBrowserCmd; const QString dvipsCmd; const QString fileMngr; const QString killallCmd; const QString latexCmd; - const QString lcInstDir; + const QString lcDataDir; const QString localUserName; - const QString localzLeafSize; + QString localzLeafSize; + void SetLocalzLeafSize( QString arg); + QString GetLocalzLeafSize() const { return localzLeafSize; } const QString lprCmd; const QString netstatCmd; const QString netwBrdAddr; @@ -75,6 +78,7 @@ public: const QString wakeonlanCmd; const QString webcamDisplayCmd; const QStringList webcams; + const QStringList webcams_names; const QString wineCmd; const QString wmctrlCmd; const QString xsetCmd; @@ -117,11 +121,6 @@ inline QString lc::Settings::GetLocalzLeafName() const { return localzLeafName; } -inline void lc::Settings::SetChosenZTreePort( const int argPort ) { - chosenzTreePort = argPort; - qDebug() << "'chosenZTreePort' set to:" << chosenzTreePort; -} - inline void lc::Settings::SetLocalzLeafName( const QString &argLocalzLeafName ) { localzLeafName = argLocalzLeafName; } diff --git a/src/localzleafstarter.cpp b/src/localzleafstarter.cpp index 244caa7..2c25413 100755 --- a/src/localzleafstarter.cpp +++ b/src/localzleafstarter.cpp @@ -33,10 +33,15 @@ lc::LocalzLeafStarter::LocalzLeafStarter( QWidget *argParent ) : { ui->setupUi( this ); + //Choose initial port from settings if ( settings->GetChosenZTreePort() ) { ui->SBzLeafPort->setValue( settings->GetChosenZTreePort() ); } + //Choose initial z-Leave size from settings + ui->LELocalzLeafSize->setText( settings->GetLocalzLeafSize() ); + + ui->CBzLeafVersion->addItem( tr( "Please choose a version" ) ); if ( !settings->installedZTreeVersions.isEmpty() ) { ui->CBzLeafVersion->addItems( settings->installedZTreeVersions ); @@ -55,6 +60,10 @@ void lc::LocalzLeafStarter::on_PBStartLocalzLeaf_clicked() { return; } + //Set chosen z-Leaf size + settings->SetLocalzLeafSize( ui->LELocalzLeafSize->text() ); + + //Emit start local z-Leaf request to main window emit LocalzLeafRequested( ui->LEzLeafName->text(), ui->CBzLeafVersion->currentText(), ui->SBzLeafPort->value() ); } diff --git a/src/localzleafstarter.ui b/src/localzleafstarter.ui index ecc4410..4fae56f 100755 --- a/src/localzleafstarter.ui +++ b/src/localzleafstarter.ui @@ -6,7 +6,7 @@ 0 0 - 352 + 371 352 @@ -20,7 +20,7 @@ This sets the name with which this local z-Leaf will connect to z-Tree. - Set the name of the to be started z-Leaf: + Set the name of the to be started z-Leaf @@ -30,7 +30,7 @@ This sets the name with which this local z-Leaf will connect to z-Tree. - background: cyan; + local @@ -43,7 +43,7 @@ Choose of which version the started z-Leaf shall be. - Choose the version of the to be started z-Leaf: + Choose the version of the to be started z-Leaf @@ -53,7 +53,7 @@ Choose of which version the started z-Leaf shall be. - background: cyan; + 32 @@ -66,17 +66,20 @@ Set the port on which the z-Tree which shall be connected to listens. - Choose the port the to be started z-Leaf shall listen on: + Choose the port the to be started z-Leaf shall listen on + + ArrowCursor + Set the port on which the z-Tree which shall be connected to listens. - background: cyan; + 7000 @@ -89,6 +92,23 @@ + + + + Choose the size the local z-Leaf shall have + + + + + + + + + + Qt::Horizontal + + + diff --git a/src/main.cpp b/src/main.cpp index d9f7695..ba01477 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -28,7 +28,7 @@ std::unique_ptr< lc::Settings > settings; int main( int argc, char *argv[] ) { QApplication a{ argc, argv }; - settings.reset( new lc::Settings{ QSettings{ "Economic Laboratory", "Labcontrol" } } ); + settings.reset( new lc::Settings{ QSettings{ "Labcontrol", "Labcontrol" } } ); lc::MainWindow w; w.show(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 2aec657..b0fb33d 100755 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -47,6 +47,37 @@ lc::MainWindow::MainWindow( QWidget *argParent ) : this, &MainWindow::UpdateClientsTableView ); gui_update_timer->start( 500 ); } + + /* session actions */ + + // Add z-Tree versions to the corresponding combo box + ui->CBzTreeVersion->addItem( tr( "Please choose a version:" ) ); + ui->CBzTreeVersion->addItems( settings->installedZTreeVersions ); + + // Add default path to the corresponding combo box + ui->CBDataTargetPath->addItem( tr( "Set a new path HERE" ) ); + ui->CBDataTargetPath->addItem( QDir::homePath() ); + ui->CBDataTargetPath->addItem( QDir::homePath() + "/zTreeData" ); + ui->CBDataTargetPath->setCurrentIndex( 2 ); + connect( this, &MainWindow::RequestNewDataTargetPath, + this, &MainWindow::GetNewDataTargetPath ); + + if ( settings->dvipsCmd.isEmpty() || settings->latexCmd.isEmpty() + || settings->lcDataDir.isEmpty() || settings->lprCmd.isEmpty() + || settings->postscriptViewer.isEmpty() || settings->ps2pdfCmd.isEmpty() + || settings->rmCmd.isEmpty() || settings->vncViewer.isEmpty() ) { + QMessageBox::information( this, tr( "Receipts printing will not work" ), + tr( "Some component essential for receipts creation and" + " printing is missing. No receipts will be created or" + " printed." ), QMessageBox::Ok ); + } else { + ui->CBReceiptsHeader->addItems( settings->installedLaTeXHeaders ); + + if ( settings->defaultReceiptIndex + && settings->defaultReceiptIndex < ui->CBReceiptsHeader->count() ) { + ui->CBReceiptsHeader->setCurrentIndex( settings->defaultReceiptIndex ); + } + } } lc::MainWindow::~MainWindow() { @@ -71,20 +102,29 @@ bool lc::MainWindow::CheckIfUserIsAdmin() { } void lc::MainWindow::DisableDisfunctionalWidgets() { + const QStringList &zTreeEntries = settings->installedZTreeVersions; + if ( zTreeEntries.isEmpty() ) { + ui->CBClientNames->setEnabled( false ); + //ui->GBzTree->setEnabled( false ); + ui->L_FakeName->setEnabled( false ); + ui->PBRunzLeaf->setEnabled( false ); + ui->PBStartLocalzLeaf->setEnabled( false ); + ui->PBStartzLeaf->setEnabled( false ); + } + // Disable all z-Leaf killing related buttons if the 'killall' command is not available if ( settings->killallCmd.isEmpty() ) { ui->PBKillLocalzLeaf->setEnabled( false ); ui->PBKillzLeaf->setEnabled( false ); } // Disable all functions relying on the labcontrol installation directory if it is not available - if ( settings->lcInstDir.isEmpty() ) { + if ( settings->lcDataDir.isEmpty() ) { ui->CBClientNames->setEnabled( false ); ui->CBWebcamChooser->setEnabled( false ); ui->GBClientActions->setEnabled( false ); - ui->GBzTree->setEnabled( false ); ui->LEFilePath->setEnabled( false ); - ui->LFakeName->setEnabled( false ); - ui->LWebcamChooser->setEnabled( false ); + ui->L_FakeName->setEnabled( false ); + ui->L_WebcamChooser->setEnabled( false ); ui->PBBeamFile->setEnabled( false ); ui->PBChooseFile->setEnabled( false ); ui->PBKillLocalzLeaf->setEnabled( false ); @@ -114,10 +154,9 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { || settings->userNameOnClients.isEmpty() ) { ui->CBClientNames->setEnabled( false ); ui->LEFilePath->setEnabled( false ); - ui->LFakeName->setEnabled( false ); + ui->L_FakeName->setEnabled( false ); ui->PBBeamFile->setEnabled( false ); ui->PBChooseFile->setEnabled( false ); - ui->PBDeactivateScreensaver->setEnabled( false ); ui->PBKillzLeaf->setEnabled( false ); ui->PBRunzLeaf->setEnabled( false ); ui->PBShutdown->setEnabled( false ); @@ -156,7 +195,7 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { if ( settings->sshCmd.isEmpty() ) { ui->CBClientNames->setEnabled( false ); ui->GBClientActions->setEnabled( false ); - ui->LFakeName->setEnabled( false ); + ui->L_FakeName->setEnabled( false ); ui->LEFilePath->setEnabled( false ); ui->PBBeamFile->setEnabled( false ); ui->PBChooseFile->setEnabled( false ); @@ -169,7 +208,7 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { if ( settings->tasksetCmd.isEmpty() ) { ui->CBClientNames->setEnabled( false ); - ui->LFakeName->setEnabled( false ); + ui->L_FakeName->setEnabled( false ); ui->PBRunzLeaf->setEnabled( false ); ui->PBStartSession->setEnabled( false ); ui->PBStartLocalzLeaf->setEnabled( false ); @@ -184,7 +223,8 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { // Disable 'PBViewDesktop' if 'vnc_viewer' was not set if ( settings->vncViewer.isEmpty() ) { - ui->PBViewDesktop->setEnabled( false ); + ui->PBViewDesktopViewOnly->setEnabled( false ); + ui->PBViewDesktopFullControl->setEnabled( false ); } // Disable 'PBBoot' if 'wakeonlan_command' was not set @@ -196,26 +236,21 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { if ( settings->webcamDisplayCmd.isEmpty() || settings->webcams.isEmpty() ) { ui->CBWebcamChooser->setEnabled( false ); - ui->LWebcamChooser->setEnabled( false ); + ui->L_WebcamChooser->setEnabled( false ); } if ( settings->wineCmd.isEmpty() ) { ui->CBClientNames->setEnabled( false ); - ui->LFakeName->setEnabled( false ); + ui->L_FakeName->setEnabled( false ); ui->PBRunzLeaf->setEnabled( false ); - ui->PBStartSession->setEnabled( false ); + //ui->PBStartSession->setEnabled( false ); ui->PBStartLocalzLeaf->setEnabled( false ); ui->PBStartzLeaf->setEnabled( false ); } - // Disable the disable screensaver function if the 'xset_command' was not set - if ( settings->xsetCmd.isEmpty() ) { - ui->PBDeactivateScreensaver->setEnabled( false ); - } - if ( settings->zTreeInstDir.isEmpty() ) { ui->CBClientNames->setEnabled( false ); - ui->LFakeName->setEnabled( false ); + ui->L_FakeName->setEnabled( false ); ui->PBRunzLeaf->setEnabled( false ); ui->PBStartSession->setEnabled( false ); ui->PBStartLocalzLeaf->setEnabled( false ); @@ -224,7 +259,7 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { } void lc::MainWindow::LoadIconPixmaps() { - if ( settings->lcInstDir.isEmpty() ) { + if ( settings->lcDataDir.isEmpty() ) { return; } @@ -237,122 +272,10 @@ void lc::MainWindow::LoadIconPixmaps() { << "zLeaf.png" }; for ( int i = 0; i < ( int )icons_t::ICON_QUANTITY; i++ ) { - if ( !icons[ i ].load( settings->lcInstDir + "/icons/" + iconNames[ i ] ) ) { + if ( !icons[ i ].load( settings->lcDataDir + "/icons/" + iconNames[ i ] ) ) { QMessageBox::information( this, tr( "Could not load icon '%1'" ).arg( iconNames[ i ] ), tr( "The icon in '%1/icons/%2' could not be loaded." ) - .arg( settings->lcInstDir ).arg( iconNames[ i ] ), QMessageBox::Ok ); - } - } -} - -void lc::MainWindow::on_CBWebcamChooser_activated( int argIndex ) { - if ( argIndex != 0 ) { - QString program{ settings->webcamDisplayCmd }; - QStringList arguments; - arguments << ui->CBWebcamChooser->currentText(); - - QProcess showWebcamProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - showWebcamProcess.setProcessEnvironment( env ); - showWebcamProcess.startDetached( program, arguments ); - } -} - -void lc::MainWindow::on_PBBeamFile_clicked() { - QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - const QString fileToBeam{ ui->LEFilePath->text() }; - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - client->BeamFile( fileToBeam, &settings->pkeyPathUser, &settings->userNameOnClients ); - } - } -} - -void lc::MainWindow::on_PBBoot_clicked() { - QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - client->Boot(); - } - } -} - -void lc::MainWindow::on_PBChooseFile_clicked() { - QFileDialog *file_dialog = new QFileDialog{ this, tr( "Choose a file to beam" ), QDir::homePath() }; - file_dialog->setFileMode( QFileDialog::Directory ); - file_dialog->setOption( QFileDialog::DontUseNativeDialog, true ); - file_dialog->setOption( QFileDialog::ReadOnly, true ); - file_dialog->setOption( QFileDialog::ShowDirsOnly, true ); - - if(file_dialog->exec()) { - ui->LEFilePath->setText(file_dialog->selectedFiles().at(0)); - qDebug() << "Chose file" << ui->LEFilePath->text() << "for beaming."; - } - else { - ui->LEFilePath->setText( tr( "File choosing cancelled" ) ); - qDebug() << "File choosing cancelled"; - } - delete file_dialog; -} - -void lc::MainWindow::on_PBDeactivateScreensaver_clicked() { - for ( auto s : settings->GetClients() ) { - if ( s->GetClientState() >= state_t::RESPONDING ) - s->DeactiveScreensaver(); - } -} - -void lc::MainWindow::on_PBExecute_clicked() { - // This will be set to false, if the command shall be executed only on the chosen clients (that's if not all clients are up) - bool executeOnEveryClient = true; - - // Cancel, if not all clients are up and running - for ( auto s: settings->GetClients() ) { - if ( !( s->name.contains( "backup", Qt::CaseInsensitive ) ) ) { - if ( s->GetClientState() < state_t::RESPONDING ) { - QMessageBox messageBox{ QMessageBox::Warning, tr( "Not all clients are running" ), - tr( "Not all clients are running. The command could not be executed on every client and should therefore be canceled to keep the clients consistent.\n\nAre you sure you want to continue only with the currently chosen clients?" ), QMessageBox::No | QMessageBox::Yes, this }; - messageBox.setDefaultButton( QMessageBox::No ); - messageBox.exec(); - executeOnEveryClient = false; - if ( messageBox.clickedButton() == messageBox.button( QMessageBox::No ) ) { - return; - } else { - break; - } - } - } - } - - // Get the command to be executed ... - QString command = ui->CBCommandToExecute->currentText(); - - // Set the correct public key - QString pkeyPathUser; - if ( ui->RBUseUserRoot->isChecked() ) { - pkeyPathUser = settings->pkeyPathRoot; - } else { - pkeyPathUser = settings->pkeyPathUser; - } - - // and execute it - if ( executeOnEveryClient ) { - qDebug() << "Executing command" << command << "on every client."; - for ( auto s: settings->GetClients() ) { - if ( !( s->name.contains( "backup", Qt::CaseInsensitive ) ) ) { - s->OpenTerminal( command, ui->RBUseUserRoot->isChecked() ); - } - } - } else { - qDebug() << "Executing command" << command << "only on chosen clients."; - QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - client->OpenTerminal( command, ui->RBUseUserRoot->isChecked() ); - } + .arg( settings->lcDataDir ).arg( iconNames[ i ] ), QMessageBox::Ok ); } } } @@ -374,51 +297,6 @@ void lc::MainWindow::on_PBKillLocalzLeaf_clicked() { qDebug() << program << arguments; } -void lc::MainWindow::on_PBKillzLeaf_clicked() { - QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - client->KillZLeaf(); - } - } -} - -void lc::MainWindow::on_PBOpenFilesystem_clicked() { - // Determine the correct user to be used - QString * userToBeUsed = nullptr; - if ( ui->RBUseUserRoot->isChecked() ) { - userToBeUsed = new QString{ "root" }; - } else { - userToBeUsed = new QString{ settings->userNameOnClients }; - } - - QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - client->OpenFilesystem( userToBeUsed ); - } - } - delete userToBeUsed; -} - -void lc::MainWindow::on_PBOpenTerminal_clicked() { - QString pkeyPathUser; - if ( ui->RBUseUserRoot->isChecked() ) { - pkeyPathUser = settings->pkeyPathRoot; - } else { - pkeyPathUser = settings->pkeyPathUser; - } - QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - client->OpenTerminal( QString{}, ui->RBUseUserRoot->isChecked() ); - } - } -} - void lc::MainWindow::on_PBPrintPaymentFileManually_clicked() { ManualPrintingSetup *manPrint = new ManualPrintingSetup{ this }; manPrint->setWindowFlags( Qt::Window ); @@ -454,107 +332,6 @@ void lc::MainWindow::on_PBRunzLeaf_clicked() { } } -void lc::MainWindow::on_PBShowORSEE_clicked() { - lablib->ShowOrsee(); -} - -void lc::MainWindow::on_PBShowPreprints_clicked() { - lablib->ShowPreprints(); -} - -void lc::MainWindow::on_PBShowSessions_clicked() { - QWidget *sessionDisplay = new SessionDisplay{ lablib->GetSessionsModel(), this }; - sessionDisplay->setWindowFlags( Qt::Window ); - sessionDisplay->show(); - connect( sessionDisplay, &SessionDisplay::destroyed, - sessionDisplay, &SessionDisplay::deleteLater ); -} - -void lc::MainWindow::on_PBShutdown_clicked() { - // Confirmation dialog - QMessageBox::StandardButton reply; - reply = QMessageBox::question(this, "Confirm", "Really shutdown the selected clients?", QMessageBox::Yes|QMessageBox::No); - if (reply == QMessageBox::Yes) { - QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - // Do not shut down the server itself - if ( client->name == "self"){ - QMessageBox::information(NULL, "Shutdown canceled", "It is not allowed to shutdown the server itself via labcontrol!"); - } else { - client->Shutdown(); - } - } - } - } else { - qDebug() << "Canceled shutting down the selected clients"; - } -} - -void lc::MainWindow::on_PBStartLocalzLeaf_clicked() { - LocalzLeafStarter *localzLeafStarter = new LocalzLeafStarter{ this }; - localzLeafStarter->setWindowFlags( Qt::Window ); - localzLeafStarter->show(); - connect( localzLeafStarter, &LocalzLeafStarter::LocalzLeafRequested, - this, &MainWindow::StartLocalzLeaf ); - connect( localzLeafStarter, SIGNAL( LocalzLeafRequested( QString, QString, int ) ), - localzLeafStarter, SLOT( deleteLater() ) ); -} - -void lc::MainWindow::on_PBStartSession_clicked() { - SessionStarter *sessionStarter = new SessionStarter{ lablib->GetOccupiedPorts(), this }; - sessionStarter->setWindowFlags( Qt::Window ); - sessionStarter->show(); - connect( sessionStarter, &SessionStarter::RequestNewSession, - lablib, &Lablib::StartNewSession ); - connect( sessionStarter, &SessionStarter::destroyed, - sessionStarter, &SessionStarter::deleteLater ); -// // Show an error message, if no zTree version was chosen yet -// if (ui->CBzTreeVersion->currentIndex() == 0) { -// QMessageBox messageBox{ QMessageBox::Warning, tr("Unset zTree version"), tr("There is no zTree version chosen yet. Please choose one."), QMessageBox::Ok, this }; -// messageBox.exec(); -// return; -// } - -// // Ask a second time, if no valid LaTeX header was set -// if (ui->CBReceiptsHeader->currentText() == "None found") { -// QMessageBox messageBox{ QMessageBox::Information, tr("No valid LaTeX header chosen"), -// tr("No valid LaTeX header was chosen. Receipts creation and printing will not work. Shall a new zTree instance be started nonetheless?"), QMessageBox::Yes | QMessageBox::No, this }; -// messageBox.exec(); -// if (messageBox.clickedButton() == messageBox.button(QMessageBox::No)) -// return; -// } - -// ui->CBDataTargetPath->setStyleSheet( "" ); -// ui->CBPrintanonymousreceipts->setStyleSheet( "" ); -// ui->CBReceiptsHeader->setStyleSheet( "" ); -// ui->CBReceiptsforLocalClients->setStyleSheet( "" ); -// ui->SBPort->setStyleSheet( "" ); - -// lablib->StartNewZTreeInstance(); -} - -void lc::MainWindow::on_PBStartzLeaf_clicked() { - QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - client->StartZLeaf( nullptr ); - } - } -} - -void lc::MainWindow::on_PBViewDesktop_clicked() { - QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - client->ShowDesktop(); - } - } -} - void lc::MainWindow::on_RBUseLocalUser_toggled(bool checked) { if ( checked ) { qDebug() << "'RBUseLocalUser' got toggled."; @@ -593,12 +370,12 @@ void lc::MainWindow::SetupWidgets() { valid_items->squeeze(); } else { QMessageBox messageBox{ QMessageBox::Warning, tr( "Could not construct clients view" ), - tr( "The creation of the clients view failed. Please check the file '/etc/xdg/Economic Laboratory/Labcontrol.conf'." ), QMessageBox::Ok, this }; + tr( "The creation of the clients view failed. Please check the file '/etc/xdg/Labcontrol/Labcontrol.conf'." ), QMessageBox::Ok, this }; messageBox.exec(); ui->CBClientNames->setEnabled( false ); ui->GBClientActions->setEnabled( false ); ui->LEFilePath->setEnabled( false ); - ui->LFakeName->setEnabled( false ); + ui->L_FakeName->setEnabled( false ); ui->PBBeamFile->setEnabled( false ); ui->PBChooseFile->setEnabled( false ); ui->PBRunzLeaf->setEnabled( false ); @@ -608,28 +385,18 @@ void lc::MainWindow::SetupWidgets() { // Fill the 'CBWebcamChooser' with all available network webcams if ( !settings->webcams.isEmpty() ) { - for ( const auto &s : settings->webcams ) + for ( const auto &s : settings->webcams_names ) ui->CBWebcamChooser->addItem( s ); } - const QStringList &zTreeEntries = settings->installedZTreeVersions; - if ( zTreeEntries.isEmpty() ) { - ui->CBClientNames->setEnabled( false ); - ui->GBzTree->setEnabled( false ); - ui->LFakeName->setEnabled( false ); - ui->PBRunzLeaf->setEnabled( false ); - ui->PBStartLocalzLeaf->setEnabled( false ); - ui->PBStartzLeaf->setEnabled( false ); - } - // Disable the admin tab if the user has no administrative rights and set it up if ( CheckIfUserIsAdmin() ) { ui->TAdminActions->setEnabled( true ); - ui->LAdministrativeRights->setText( tr( "You have administrative rights." ) ); + ui->L_AdministrativeRights->setText( tr( "You have administrative rights." ) ); } else { - ui->LAdministrativeRights->setText( tr( "You don't have administrative rights." ) ); + ui->L_AdministrativeRights->setText( tr( "You don't have administrative rights." ) ); } - ui->LUserName->setText( tr( "You are user %1" ).arg( settings->localUserName ) ); + ui->L_UserName->setText( tr( "You are user %1" ).arg( settings->localUserName ) ); if ( !settings->userNameOnClients.isEmpty() ) { ui->RBUseLocalUser->setText( settings->userNameOnClients ); } else { @@ -654,10 +421,16 @@ void lc::MainWindow::SetupWidgets() { << "apt full-upgrade -y" << "reboot" << "uname -a" ); } - DisableDisfunctionalWidgets(); + // Disable buttons which are not configured + //DisableDisfunctionalWidgets(); // Set the info text in LInfo on the TInfo tab - ui->LInfo->setText( "This is Labcontrol.\n\nCopyright 2014-2016 Markus Prasser\n\n\n" + ui->LInfo->setText( "This is Labcontrol version 2.1.5\n\n\n\n\n\n" + "Developers\n\n" + "0day-2016 Henning Prömpers\n" + "2014-2016 Markus Prasser\n" + "2016 - now WiwilabHiwiOrgaization\n\n\n" + "Copyright\n\n" "Labcontrol is free software: you can redistribute it and/or modify\n" "it under the terms of the GNU General Public License as published by\n" "the Free Software Foundation, either version 3 of the License, or\n" @@ -670,27 +443,6 @@ void lc::MainWindow::SetupWidgets() { "along with Labcontrol. If not, see .\n\n\n" ); } -void lc::MainWindow::StartLocalzLeaf( QString argzLeafName, QString argzLeafVersion, - int argzTreePort ) { - if ( settings->tasksetCmd.isEmpty() || settings->wineCmd.isEmpty() - || settings->zTreeInstDir.isEmpty() ) { - return; - } - - QProcess startProc; - startProc.setProcessEnvironment( QProcessEnvironment::systemEnvironment() ); - QStringList arguments; - arguments << "0x00000001" << settings->wineCmd - << QString{ settings->zTreeInstDir + "/zTree_" + argzLeafVersion + "/zleaf.exe" } - << "/server" << "127.0.0.1" << "/channel" - << QString::number( argzTreePort - 7000 ) << "/name" << argzLeafName; - if ( !settings->localzLeafSize.isEmpty() ) { - arguments << "/size" << QString{ settings->localzLeafSize }; - } - - startProc.startDetached( settings->tasksetCmd, arguments ); -} - void lc::MainWindow::StartReceiptsHandler( QString argzTreeDataTargetPath, bool argReceiptsForLocalClients, QString argAnonymousReceiptsPlaceholder, @@ -735,16 +487,200 @@ void lc::MainWindow::UpdateClientsTableView() { } } -// TODO: Implement the functionality of the script in here -void lc::MainWindow::on_PBrestartCrashedSession_clicked() { +/* Experiment tab functions */ + +void lc::MainWindow::on_PBBoot_clicked() { + QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->Boot(); + } + } +} + +void lc::MainWindow::on_PBChooseFile_clicked() { + QFileDialog *file_dialog = new QFileDialog{ this, tr( "Choose a file to beam" ), QDir::homePath() }; + file_dialog->setFileMode( QFileDialog::Directory ); + file_dialog->setOption( QFileDialog::DontUseNativeDialog, true ); + file_dialog->setOption( QFileDialog::ReadOnly, true ); + file_dialog->setOption( QFileDialog::ShowDirsOnly, true ); + + if(file_dialog->exec()) { + ui->LEFilePath->setText(file_dialog->selectedFiles().at(0)); + qDebug() << "Chose file" << ui->LEFilePath->text() << "for beaming."; + } + else { + ui->LEFilePath->setText( tr( "File choosing cancelled" ) ); + qDebug() << "File choosing cancelled"; + } + delete file_dialog; +} + +void lc::MainWindow::on_PBBeamFile_clicked() { + QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); + const QString fileToBeam{ ui->LEFilePath->text() }; + if(fileToBeam == ""){ + QMessageBox::information(this, "Upload failed", "You didn't choose any folder to upload."); + } else { + //Iterate over the selected clients to upload the file + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->BeamFile( fileToBeam, &settings->pkeyPathUser, &settings->userNameOnClients ); + } + } + // Inform the user about the path + QMessageBox::information(this, "Upload completed", "The folder was copied to all selected clients.\nThe path on every client is /home/ewfuser/media4ztree" + fileToBeam.mid(fileToBeam.lastIndexOf('/')) +".\nDon't forget to adjust the media path within zTree!"); + } +} + +void lc::MainWindow::on_PBShowORSEE_clicked() { + lablib->ShowOrsee(); +} + +void lc::MainWindow::on_PBShowPreprints_clicked() { + lablib->ShowPreprints(); +} + +void lc::MainWindow::on_PBShutdown_clicked() { + // Confirmation dialog + QMessageBox::StandardButton reply; + reply = QMessageBox::question(this, "Confirm", "Really shutdown the selected clients?", QMessageBox::Yes|QMessageBox::No); + if (reply == QMessageBox::Yes) { + QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + // Do not shut down the server itself + if ( client->name == "self"){ + QMessageBox::information(NULL, "Shutdown canceled", "It is not allowed to shutdown the server itself via labcontrol!"); + } else { + client->Shutdown(); + } + } + } + } else { + qDebug() << "Canceled shutting down the selected clients"; + } +} + +void lc::MainWindow::on_CBWebcamChooser_activated( int argIndex ) { + if ( argIndex != 0 ) { + QString program{ settings->webcamDisplayCmd }; + QStringList arguments; + + // Attention argIndex is NOT 0-based + arguments << settings->webcams[argIndex-1]; + qDebug() << "Webcam" << arguments << "will be opened"; + + QProcess showWebcamProcess; + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + showWebcamProcess.setProcessEnvironment( env ); + showWebcamProcess.startDetached( program, arguments ); + } +} + +void lc::MainWindow::on_PBstartBrowser_clicked() +{ + QString argURL = ui->LEURL->text(); + bool argFullscreen = ui->CBFullscreen->checkState(); + QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->StartClientBrowser( &argURL, &argFullscreen ); + } + } +} + +void lc::MainWindow::on_PBstopBrowser_clicked() +{ + // Confirmation dialog + QMessageBox::StandardButton reply; + reply = QMessageBox::question(this, "Confirm", "Really kill all selected browser instances?", QMessageBox::Yes|QMessageBox::No); + if (reply == QMessageBox::Yes) { + QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->StopClientBrowser( ); + } + } + } else { + qDebug() << "Canceled stopping all selected browser processes"; + } +} + +// View only VNC button +void lc::MainWindow::on_PBViewDesktopViewOnly_clicked() +{ + QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->ShowDesktopViewOnly(); + } + } +} + +// Full control VNC button +void lc::MainWindow::on_PBViewDesktopFullControl_clicked() +{ + QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->ShowDesktopFullControl(); + } + } +} + + +/* Session tab functions */ +void lc::MainWindow::on_PBStartzLeaf_clicked() { + QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->StartZLeaf( nullptr, ui->LEzLeafCommandline->text() ); + } + } +} + +void lc::MainWindow::on_PBStartLocalzLeaf_clicked() { + LocalzLeafStarter *localzLeafStarter = new LocalzLeafStarter{ this }; + localzLeafStarter->setWindowFlags( Qt::Window ); + localzLeafStarter->show(); + connect( localzLeafStarter, &LocalzLeafStarter::LocalzLeafRequested, + this, &MainWindow::StartLocalzLeaf ); + connect( localzLeafStarter, SIGNAL( LocalzLeafRequested( QString, QString, int ) ), + localzLeafStarter, SLOT( deleteLater() ) ); +} + +void lc::MainWindow::StartLocalzLeaf( QString argzLeafName, QString argzLeafVersion, + int argzTreePort ) { + if ( settings->tasksetCmd.isEmpty() || settings->wineCmd.isEmpty() + || settings->zTreeInstDir.isEmpty() ) { + return; + } + QProcess startProc; startProc.setProcessEnvironment( QProcessEnvironment::systemEnvironment() ); - if ( !settings->restartCrashedSessionScript.isEmpty() ) { - startProc.startDetached( settings->restartCrashedSessionScript); + QStringList arguments; + arguments << "0x00000001" << settings->wineCmd + << QString{ settings->zTreeInstDir + "/zTree_" + argzLeafVersion + "/zleaf.exe" } + << "/server" << "127.0.0.1" << "/channel" + << QString::number( argzTreePort - 7000 ) << "/name" << argzLeafName; + if ( !settings->localzLeafSize.isEmpty() ) { + arguments << "/size" << QString{ settings->localzLeafSize }; } + + qDebug() << "Start local zLeaf:" << arguments; + startProc.startDetached( settings->tasksetCmd, arguments ); } -void lc::MainWindow::on_PBKillzTree_clicked() +void lc::MainWindow::on_PBStopZtree_clicked() { QString program{ settings->killallCmd }; QStringList arguments; @@ -761,6 +697,191 @@ void lc::MainWindow::on_PBKillzTree_clicked() // Output message via the debug messages tab qDebug() << program << arguments; } else { - qDebug() << "Canceled killing all z-Tree processes"; + qDebug() << "Canceled stopping all z-Tree processes"; + } +} + +void lc::MainWindow::on_PBRecoverCrashedSession_clicked() +{ + // TODO: Implement the functionality of the restore session script in here (no zenity script) + QProcess startProc; + startProc.setProcessEnvironment( QProcessEnvironment::systemEnvironment() ); + if ( !settings->restartCrashedSessionScript.isEmpty() ) { + startProc.startDetached( settings->restartCrashedSessionScript); + } +} + +void lc::MainWindow::on_CBDataTargetPath_activated( int argIndex ) +{ + if ( !argIndex ) { + emit RequestNewDataTargetPath(); + } + + ui->CBDataTargetPath->setStyleSheet( "" ); +} + +// Open a folder chooser dialog for zTree data path +void lc::MainWindow::GetNewDataTargetPath() { + QFileDialog fileDialog{ this }; + fileDialog.setFileMode( QFileDialog::Directory ); + fileDialog.setDirectory( QDir::homePath() ); + fileDialog.setOption( QFileDialog::ShowDirsOnly, true ); + fileDialog.setOption( QFileDialog::DontUseNativeDialog, true ); + if ( fileDialog.exec() ) { + const QString fileName = fileDialog.selectedFiles().at( 0 ); + ui->CBDataTargetPath->addItem( fileName ); + ui->CBDataTargetPath->setCurrentText( fileName ); + } +} + +// Dummy function for enabling anonymous receipts section in UI +void lc::MainWindow::on_CBReceiptsHeader_activated(int argIndex) +{ + Q_UNUSED( argIndex ); + ui->CBReceiptsHeader->setStyleSheet( "" ); +} + +// Anonymous receipients header check box +void lc::MainWindow::on_ChBPrintanonymousreceipts_clicked() +{ + ui->LReplaceParticipantNames->setEnabled(true); + ui->CBReplaceParticipantNames->setEnabled(true); +} + +// Start session button actions +void lc::MainWindow::on_PBStartSession_clicked() { + + if ( ui->CBzTreeVersion->currentIndex() == 0 ) { + QMessageBox::information( this, tr( "No z-Tree version chosen" ), + tr( "A z-Tree version was not chosen, yet. This setting is" + " mandatory." ), QMessageBox::Ok ); + return; + } + + const QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); + if( !ui->ChBSessionWithoutAttachedClients->isChecked() ) { + if ( !activatedItems.length() ) { + QMessageBox::information( this, tr( "Canceled, no clients were chosen" ), + tr( "The start of a new session was canceled.\n" + " Some clients have to be selected first or the" + " creation of sessions without clients must be" + " allowed with the checkbox." ) ); + return; + } + } + + QString anonymousReceiptsPlaceholder; + if ( ui->ChBPrintAnonymousReceipts->isChecked() ) { + anonymousReceiptsPlaceholder = ui->CBReplaceParticipantNames->currentText(); + } + + QVector< Client* > associatedClients; + for ( auto cit = activatedItems.cbegin(); cit != activatedItems.cend(); ++cit ) { + if ( ( *cit ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *cit ).data( Qt::UserRole ).value< void* >() ); + client->SetSessionPort( ui->SBPort->value() ); + client->SetzLeafVersion( ui->CBzTreeVersion->currentText() ); + associatedClients.append( client ); + } + } + + this->lablib->StartNewSession ( associatedClients, anonymousReceiptsPlaceholder, + ui->ChBReceiptsForLocalClients->isChecked(), + ui->CBReceiptsHeader->currentText(), + ui->CBDataTargetPath->currentText(), + static_cast< quint16 >( ui->SBPort->value() ), + ui->CBzTreeVersion->currentText() ); + + //Display the command line + QString cmd = this->lablib->getzLeafArgs( ui->SBPort->value(), ui->CBzTreeVersion->currentText()).join(" "); + ui->LEzLeafCommandline->setText(cmd); + + //Start z-Leaf on selected clients if checkbox is activated + if( ui->ChBautoStartClientZleaf->isChecked() ) { + for ( auto cit = activatedItems.cbegin(); cit != activatedItems.cend(); ++cit ) { + if ( ( *cit ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *cit ).data( Qt::UserRole ).value< void * >() ); + client->StartZLeaf( nullptr, cmd ); + } + } + } + + // Set chosen Port + settings->SetChosenZTreePort(ui->SBPort->text().toInt()); + // Increment port number + int newPort = ui->SBPort->text().toInt() + 1; + ui->SBPort->setValue(newPort); +} + +void lc::MainWindow::on_PBKillzLeaf_clicked() +{ + QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->KillZLeaf(); + } + } +} + +/* Admin tab functions */ + +void lc::MainWindow::on_PBOpenFilesystem_clicked() { + // Determine the correct user to be used + QString * userToBeUsed = nullptr; + if ( ui->RBUseUserRoot->isChecked() ) { + userToBeUsed = new QString{ "root" }; + } else { + userToBeUsed = new QString{ settings->userNameOnClients }; + } + + QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->OpenFilesystem( userToBeUsed ); + } + } + delete userToBeUsed; +} + +void lc::MainWindow::on_PBExecute_clicked() { + + // Get the command to be executed ... + QString command = ui->CBCommandToExecute->currentText(); + + // Set the correct public key + QString pkeyPathUser; + if ( ui->RBUseUserRoot->isChecked() ) { + pkeyPathUser = settings->pkeyPathRoot; + } else { + pkeyPathUser = settings->pkeyPathUser; + } + + qDebug() << "Executing command" << command << " on chosen clients."; + QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->OpenTerminal( command, ui->RBUseUserRoot->isChecked() ); + } + } + +} + +// Issue open terminal call +void lc::MainWindow::on_PBOpenTerminal_clicked() { + QString pkeyPathUser; + if ( ui->RBUseUserRoot->isChecked() ) { + pkeyPathUser = settings->pkeyPathRoot; + } else { + pkeyPathUser = settings->pkeyPathUser; + } + QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->OpenTerminal( QString{}, ui->RBUseUserRoot->isChecked() ); + } } } diff --git a/src/mainwindow.h b/src/mainwindow.h index 90f0925..154afef 100755 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -24,8 +24,6 @@ enum class icons_t : unsigned short int { UNKNOWN, OFF, DOWN, BOOT, ON, ZLEAF, I #include "Lib/client.h" #include "Lib/lablib.h" -#include "sessionstarter.h" -#include "sessiondisplay.h" #include "ui_mainwindow.h" #include @@ -61,22 +59,20 @@ private slots: void on_PBBeamFile_clicked(); void on_PBBoot_clicked(); void on_PBChooseFile_clicked(); - void on_PBDeactivateScreensaver_clicked(); void on_PBExecute_clicked(); void on_PBKillLocalzLeaf_clicked(); - void on_PBKillzLeaf_clicked(); void on_PBOpenFilesystem_clicked(); void on_PBOpenTerminal_clicked(); void on_PBPrintPaymentFileManually_clicked(); void on_PBRunzLeaf_clicked(); void on_PBShowORSEE_clicked(); void on_PBShowPreprints_clicked(); - void on_PBShowSessions_clicked(); void on_PBShutdown_clicked(); void on_PBStartLocalzLeaf_clicked(); void on_PBStartSession_clicked(); void on_PBStartzLeaf_clicked(); - void on_PBViewDesktop_clicked(); + void on_PBViewDesktopViewOnly_clicked(); + void on_PBViewDesktopFullControl_clicked(); void on_RBUseLocalUser_toggled(bool checked); void StartLocalzLeaf( QString argzLeafName, QString argzLeafVersion, int argzTreePort ); //! Updates the icons of the QTableView displaying the clients' states @@ -87,6 +83,12 @@ private slots: void UpdateClientsTableView(); signals: + /*Session actions*/ + void RequestNewDataTargetPath(); + void RequestNewSession( QVector< Client* > argAssocCl, QString argParticipNameReplacement, + bool argPrintLocalReceipts, QString argReceiptsHeader, + QString argzTreeDataTargetPath, quint16 argzTreePort, + QString argzTreeVersion ); private: //! Checks, if the user has administrative rights @@ -116,8 +118,17 @@ private slots: QString argAnonymousReceiptsPlaceholder, QString argLatexHeaderName, QString argDateString ); - void on_PBrestartCrashedSession_clicked(); - void on_PBKillzTree_clicked(); + void on_PBstartBrowser_clicked(); + void on_PBstopBrowser_clicked(); + + /* Session actions */ + void on_PBStopZtree_clicked(); + void on_PBRecoverCrashedSession_clicked(); + void GetNewDataTargetPath(); + void on_CBDataTargetPath_activated( int argIndex ); + void on_CBReceiptsHeader_activated(int argIndex); + void on_ChBPrintanonymousreceipts_clicked(); + void on_PBKillzLeaf_clicked(); }; } diff --git a/src/mainwindow.ui b/src/mainwindow.ui index e655b53..da11085 100755 --- a/src/mainwindow.ui +++ b/src/mainwindow.ui @@ -6,10 +6,16 @@ 0 0 - 800 + 730 900 + + + 0 + 0 + + Labcontrol @@ -18,6 +24,15 @@ ../../../../../../usr/local/share/labcontrol/icons/icon.png../../../../../../usr/local/share/labcontrol/icons/icon.png + + true + + + + 0 + 0 + + @@ -25,23 +40,56 @@ true - + 0 0 + + + 640 + 580 + + + + + 0 + 0 + + + + + false + true + + 0 + + true + + + false + + + true + + + + 0 + 0 + + - Experimenter actions + Experiment prepatation - - + + 0 @@ -49,82 +97,122 @@ - z-Tree - - - false + Experiment preparation / server actions - + - - - Start a new session. A new window will be opened to enter all required parameters. + + + Plan a session or print attendee list + + + + - Start session + Show ORSEE - - - true + + + Qt::Horizontal + + + + - Show sessions + Print local files - + + + Show preprints + + + + + - Kill all local z-Tree instances + Choose a payment file manually, which will then be printed. - Terminate z-Tree + Print payment file manually - + Qt::Horizontal - + - Session recovery: + Show webcams - - - Continue crashed session - + + + + Choose webcam + + - - - Choose a payment file manually, which will then be printed. + + + Qt::Vertical - - Print payment file manually + + + 20 + 40 + - + + + + + + + 6 + + + true + + + + 0 + 0 + + Client actions - + + + + + Switch the selected clients on or off + + + @@ -146,134 +234,515 @@ - - - Starts zLeaf on the selected clients with the port given in the 'zTree' groupbox. - - - Start z-Leaf + + + Qt::Horizontal - - - Kills zLeaf on all selected clients. + + + Qt::Horizontal + + + + - Terminate z-Leaf + Remote control the selected clients - + Shows the desktop of the selected clients. - View desktop + View desktop (view only) - - - - - - - - - 6 - - - - - Further local actions - - - + - Show ORSEE + Control desktop (mouse and keyboard) - + + + Qt::Horizontal + + + + + + + + + + + Upload folder to the selected clients + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + + + + + + + Choose folder + + + + + + + true + + + + + + + + + Start to upload folder + + + + + + + + + + + Qt::Horizontal + + + + + - Show preprints + Start browser on the selected clients - + - + - Start local z-Leaf + URL: - + - Kill local z-Leaf + http:// + + + + Fullscreen + + + true + + + + + + + + + Start browser + + + + + + + Stop browser + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + - - - - Special actions - - + + + + + + + true + + + + 0 + 439 + + + + Session actions + + + + + 10 + 10 + 691 + 71 + + + + + + + + 50 + false + + + + Cleanup / recover last session + + + + + + + + + Stop z-Tree + + + + + + + Stops zLeaf on all selected clients + + + Stop z-Leaf on selected clients + + + + + + + Qt::Vertical + + + + + + + Recover crashed session + + + + + + + + + Qt::Horizontal + + + + + + + + + 10 + 88 + 691 + 468 + + + + + QLayout::SetDefaultConstraint + + + + + New Session + + + + + + + + + 9 + + + 9 + + + 9 + + + 9 + - + - Show webcam: + z-Tree version - + + + + + + Data target path (No whitespaces allowed) + + + + + + + + + + 0 + + + + + + + Port: + + + + + + + 7000 + + + 10000 + + + + + + + + + + + Qt::Horizontal + + + + + + + Template for receipts + + + + + + + + + + Print anonymous receipts + + + + + + + false + + + Replace participant names with: + + + + + + + false + + + true + - Choose webcam + \hspace{5cm} + + + + + anonym + + + + + anonymous + + + + + nicht ausfüllen - + + + Print receipt for local client + + + false + + + + + Qt::Horizontal - + + + true + + + Use ramdisk for gamesafe file + + + + + + + Allow session without attached clients + + + + + + + Start z-Leaf on clients with default parameters + + + true + + + + + + + Start session + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + z-Leaves + + + 4 + + + + + + + command line to be executed + + + + + + + + 0 + 0 + + + + + + - Deactivates the screensavers on the selected clients. + Starts zLeaf on the selected clients with the port given in the 'zTree' groupbox. - Deactivate screensaver + Start z-Leaf on selected clients - + Qt::Horizontal - + true @@ -284,7 +753,7 @@ - <html><head/><body><p>Run zLeaf with another name than the client's:</p></body></html> + <html><head/><body><p>Run zLeaf with another name<br/>(select a single client):</p></body></html> Qt::RichText @@ -302,9 +771,12 @@ true + + Choose the name z-Leaf shall have + - Choose the name the z-Leaf shall have + Choose the name z-Leaf shall have @@ -317,54 +789,56 @@ - + Qt::Horizontal - + - Upoad folder: + Local zLeaf - + - - - - - Choose folder - - - - - - - true - - - - + + + Start local z-Leaf + + - + - Beam folder to ~/media4zTree on all clients + Stop local z-Leaf + + + + Qt::Vertical + + + + 20 + 40 + + + + - - - - - + + + + + @@ -381,14 +855,14 @@ - + TextLabel - + TextLabel @@ -406,7 +880,7 @@ - + User to be used for remote terminal session: @@ -461,7 +935,7 @@ - Execute command on every client + Execute command on selected clients @@ -507,15 +981,77 @@ + + true + + + + 0 + 0 + + 0 256 + + + 8 + + + + false + + + Qt::LeftToRight + + + Qt::ScrollBarAlwaysOff + + + Qt::ScrollBarAlwaysOff + + + QAbstractScrollArea::AdjustToContents + + + false + + true + + false + + false + + + true + + + 115 + + + 30 + + + false + + + false + + + 35 + + + 25 + + + false + diff --git a/src/manualprintingsetup.cpp b/src/manualprintingsetup.cpp index e1aed9a..2eda978 100755 --- a/src/manualprintingsetup.cpp +++ b/src/manualprintingsetup.cpp @@ -34,7 +34,7 @@ lc::ManualPrintingSetup::ManualPrintingSetup( QWidget *argParent ) : ui->setupUi( this ); if ( settings->dvipsCmd.isEmpty() || settings->latexCmd.isEmpty() - || settings->lcInstDir.isEmpty() || settings->lprCmd.isEmpty() + || settings->lcDataDir.isEmpty() || settings->lprCmd.isEmpty() || settings->postscriptViewer.isEmpty() || settings->ps2pdfCmd.isEmpty() || settings->rmCmd.isEmpty() || settings->vncViewer.isEmpty() ) { ui->VLManualPrintingSetup->setEnabled( false ); diff --git a/src/sessiondisplay.cpp b/src/sessiondisplay.cpp deleted file mode 100755 index 77a9ff2..0000000 --- a/src/sessiondisplay.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2014-2016 Markus Prasser - * - * This file is part of Labcontrol. - * - * Labcontrol is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Labcontrol is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Labcontrol. If not, see . - */ - -#include "sessiondisplay.h" -#include "ui_sessiondisplay.h" - -lc::SessionDisplay::SessionDisplay( QAbstractTableModel *argSessionsModel, - QWidget *argParent ) : - QWidget{ argParent }, - ui{ new Ui::SessionDisplay } -{ - ui->setupUi( this ); - ui->TVSessions->setModel( argSessionsModel ); -} - -lc::SessionDisplay::~SessionDisplay() { - delete ui; -} diff --git a/src/sessiondisplay.h b/src/sessiondisplay.h deleted file mode 100755 index a8e72af..0000000 --- a/src/sessiondisplay.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2014-2016 Markus Prasser - * - * This file is part of Labcontrol. - * - * Labcontrol is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Labcontrol is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Labcontrol. If not, see . - */ - -#ifndef SESSIONDISPLAY_H -#define SESSIONDISPLAY_H - -#include -#include - -namespace lc { - -namespace Ui { -class SessionDisplay; -} - -class SessionDisplay : public QWidget { - Q_OBJECT - -public: - explicit SessionDisplay( QAbstractTableModel *argSessionsModel, - QWidget *argParent = nullptr ); - ~SessionDisplay(); - -private: - Ui::SessionDisplay *ui = nullptr; -}; - -} - -#endif // SESSIONDISPLAY_H diff --git a/src/sessiondisplay.ui b/src/sessiondisplay.ui deleted file mode 100755 index aa796c1..0000000 --- a/src/sessiondisplay.ui +++ /dev/null @@ -1,24 +0,0 @@ - - - lc::SessionDisplay - - - - 0 - 0 - 400 - 300 - - - - Session Display - - - - - - - - - - diff --git a/src/sessionstarter.cpp b/src/sessionstarter.cpp deleted file mode 100755 index 44f9940..0000000 --- a/src/sessionstarter.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright 2014-2016 Markus Prasser - * - * This file is part of Labcontrol. - * - * Labcontrol is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Labcontrol is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Labcontrol. If not, see . - */ - -#include - -#include -#include -#include - -#include "sessionstarter.h" -#include "ui_sessionstarter.h" -#include "Lib/settings.h" - -extern std::unique_ptr< lc::Settings > settings; - -lc::SessionStarter::SessionStarter( const QVector< quint16 > &argOccupiedPorts, - QWidget *argParent ) : - QWidget{ argParent }, - clientsViewModel{ new QStandardItemModel{ this } }, - occupiedPorts{ argOccupiedPorts }, - ui{ new Ui::SessionStarter } -{ - ui->setupUi( this ); - - CheckIfPortIsOccupied( settings->GetChosenZTreePort() ); - - if ( settings->dvipsCmd.isEmpty() || settings->latexCmd.isEmpty() - || settings->lcInstDir.isEmpty() || settings->lprCmd.isEmpty() - || settings->postscriptViewer.isEmpty() || settings->ps2pdfCmd.isEmpty() - || settings->rmCmd.isEmpty() || settings->vncViewer.isEmpty() ) { - ui->GBReceipts->setEnabled( false ); - QMessageBox::information( this, tr( "Receipts printing will not work" ), - tr( "Some component essential for receipts creation and" - " printing is missing. No receipts will be created or" - " printed." ), QMessageBox::Ok ); - } else { - ui->CBReceiptsHeader->addItems( settings->installedLaTeXHeaders ); - - if ( settings->defaultReceiptIndex - && settings->defaultReceiptIndex < ui->CBReceiptsHeader->count() ) { - ui->CBReceiptsHeader->setCurrentIndex( settings->defaultReceiptIndex ); - } - } - - ui->CBzTreeVersion->addItem( tr( "Please choose a version:" ) ); - ui->CBzTreeVersion->addItems( settings->installedZTreeVersions ); - - ui->CBDataTargetPath->addItem( tr( "Set a new path HERE" ) ); - ui->CBDataTargetPath->addItem( QDir::homePath() ); - ui->CBDataTargetPath->addItem( QDir::homePath() + "/zTreeData" ); - ui->CBDataTargetPath->setCurrentIndex( 2 ); - connect( this, &SessionStarter::RequestNewDataTargetPath, - this, &SessionStarter::GetNewDataTargetPath ); - - for ( auto *s : settings->GetClients() ) { - int tempXPos = s->xPosition - 1, tempYPos = s->yPosition; - - if ( clientsViewModel->item( tempYPos, tempXPos ) ) { - QMessageBox::information( this, tr( "Double assignment to one position" ), - tr( "Two client where set for the same position. Client" - " '%1' will be dropped." ).arg( s->name ) ); - continue; - } - - QStandardItem *item = new QStandardItem( s->name ); - item->setEditable( false ); - const QString sessionPort{ QString::number( s->GetSessionPort() ) }; - if ( sessionPort == "0" ) { - item->setText( s->name ); - } else { - item->setBackground( QBrush{ QColor{ 196, 196, 255 } } ); - item->setSelectable( false ); - item->setText( QString{ "(" + sessionPort + ") " + s->name } ); - } - QVariant v = qVariantFromValue( static_cast< void* >( s ) ); - item->setData( v, Qt::UserRole ); - clientsViewModel->setItem( tempYPos, tempXPos, item ); - } - ui->TVClients->setModel( clientsViewModel ); -} - -lc::SessionStarter::~SessionStarter() { - delete ui; -} -void lc::SessionStarter::CheckIfPortIsOccupied( quint16 argPort ) { - if ( occupiedPorts.contains( argPort ) ) { - CheckIfPortIsOccupied( argPort + 1 ); - } else { - ui->SBPort->setValue( argPort ); - } -} - -void lc::SessionStarter::GetNewDataTargetPath() { - QFileDialog fileDialog{ this }; - fileDialog.setFileMode( QFileDialog::Directory ); - fileDialog.setDirectory( QDir::homePath() ); - fileDialog.setOption( QFileDialog::ShowDirsOnly, true ); - fileDialog.setOption( QFileDialog::DontUseNativeDialog, true ); - if ( fileDialog.exec() ) { - const QString fileName = fileDialog.selectedFiles().at( 0 ); - ui->CBDataTargetPath->addItem( fileName ); - ui->CBDataTargetPath->setCurrentText( fileName ); - } -} - -void lc::SessionStarter::on_CBDataTargetPath_activated( int argIndex ) { - if ( !argIndex ) { - emit RequestNewDataTargetPath(); - } - - ui->CBDataTargetPath->setStyleSheet( "" ); -} - -void lc::SessionStarter::on_CBReceiptsHeader_activated( int argIndex ) { - Q_UNUSED( argIndex ); - ui->CBReceiptsHeader->setStyleSheet( "" ); -} - -void lc::SessionStarter::on_CBzTreeVersion_activated( int argIndex ) { - Q_UNUSED( argIndex ); - ui->CBzTreeVersion->setStyleSheet( "" ); -} - -void lc::SessionStarter::on_ChBPrintAnonymousReceipts_clicked( bool argChecked ) { - ui->ChBPrintAnonymousReceipts->setStyleSheet( "" ); - - ui->LReplaceParticipantNames->setEnabled( argChecked ); - ui->CBReplaceParticipantNames->setEnabled( argChecked ); -} - -void lc::SessionStarter::on_PBStartSession_clicked() { - if ( ui->CBzTreeVersion->currentIndex() == 0 ) { - QMessageBox::information( this, tr( "No z-Tree version chosen" ), - tr( "A z-Tree version was not chosen, yet. This setting is" - " mandatory." ), QMessageBox::Ok ); - return; - } - - const QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - if( !ui->ChBSessionWithoutClients->isChecked() ) { - if ( !activatedItems.length() ) { - QMessageBox::information( this, tr( "Canceled, no clients were chosen" ), - tr( "The start of a new session was canceled." - " Some clients have to be selected first or the" - " creation of sessions without clients must be" - " allowed with the checkbox close to the bottom" ) ); - return; - } - } - - QString anonymousReceiptsPlaceholder; - if ( ui->ChBPrintAnonymousReceipts->isChecked() ) { - anonymousReceiptsPlaceholder = ui->CBReplaceParticipantNames->currentText(); - } - - QVector< Client* > associatedClients; - for ( auto cit = activatedItems.cbegin(); cit != activatedItems.cend(); ++cit ) { - if ( ( *cit ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *cit ).data( Qt::UserRole ).value< void* >() ); - client->SetSessionPort( ui->SBPort->value() ); - client->SetzLeafVersion( ui->CBzTreeVersion->currentText() ); - associatedClients.append( client ); - } - } - - emit RequestNewSession( associatedClients, anonymousReceiptsPlaceholder, - ui->ChBReceiptsForLocalClients->isChecked(), - ui->CBReceiptsHeader->currentText(), - ui->CBDataTargetPath->currentText(), - static_cast< quint16 >( ui->SBPort->value() ), - ui->CBzTreeVersion->currentText() ); - - //Start z-Leaf on selected clients if checkbox is activated - if( ui->ChBautoStartClientZleaf->isChecked() ) { - for ( auto cit = activatedItems.cbegin(); cit != activatedItems.cend(); ++cit ) { - if ( ( *cit ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *cit ).data( Qt::UserRole ).value< void * >() ); - client->StartZLeaf( nullptr ); - } - } - } - - this->deleteLater(); -} - -void lc::SessionStarter::on_SBPort_editingFinished() { - ui->SBPort->setStyleSheet( "" ); - - CheckIfPortIsOccupied( ui->SBPort->value() ); -} diff --git a/src/sessionstarter.h b/src/sessionstarter.h deleted file mode 100755 index dea501e..0000000 --- a/src/sessionstarter.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2014-2016 Markus Prasser - * - * This file is part of Labcontrol. - * - * Labcontrol is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Labcontrol is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Labcontrol. If not, see . - */ - -#ifndef SESSIONSTARTER_H -#define SESSIONSTARTER_H - -#include - -class QStandardItemModel; - -namespace lc { - -class Client; - -namespace Ui { -class SessionStarter; -} - -class SessionStarter : public QWidget { - Q_OBJECT - -public: - explicit SessionStarter( const QVector< quint16 > &argOccupiedPorts, - QWidget *argParent = nullptr ); - ~SessionStarter(); - -signals: - void RequestNewDataTargetPath(); - void RequestNewSession( QVector< Client* > argAssocCl, QString argParticipNameReplacement, - bool argPrintLocalReceipts, QString argReceiptsHeader, - QString argzTreeDataTargetPath, quint16 argzTreePort, - QString argzTreeVersion ); - -private: - void CheckIfPortIsOccupied( quint16 argPort ); - - QStandardItemModel *clientsViewModel = nullptr; - const QVector< quint16 > &occupiedPorts; - Ui::SessionStarter *ui = nullptr; - -private slots: - void GetNewDataTargetPath(); - void on_CBDataTargetPath_activated( int argIndex ); - void on_CBReceiptsHeader_activated( int argIndex ); - void on_CBzTreeVersion_activated( int argIndex ); - void on_ChBPrintAnonymousReceipts_clicked( bool argChecked ); - void on_PBStartSession_clicked(); - void on_SBPort_editingFinished(); -}; - -} - -#endif // SESSIONSTARTER_H diff --git a/src/sessionstarter.ui b/src/sessionstarter.ui deleted file mode 100755 index 18ad722..0000000 --- a/src/sessionstarter.ui +++ /dev/null @@ -1,319 +0,0 @@ - - - lc::SessionStarter - - - - 0 - 0 - 640 - 600 - - - - Form - - - - - - - - z-Tree - - - - - - The z-Tree version which shall be used for the experiment. - - - z-Tree version: - - - - - - - The z-Tree version which shall be used for the experiment. - - - background: cyan; - - - 32 - - - - - - - The path where z-Tree shall store its data. - -Please take care that it does not contain any spaces or other special characters. - - - Data target path: - - - - - - - The path where z-Tree shall store its data. - -Please take care that it does not contain any spaces or other special characters. - - - background: cyan; - - - - - - - - - The port which will be used by started z-Tree and z-Leaf instances. This only matters if multiple experiments shall be run in parallel. - - - Port: - - - - - - - true - - - The port which will be used by started z-Tree and z-Leaf instances. This only matters if multiple experiments shall be run in parallel. - - - background: cyan; - - - 7000 - - - 65535 - - - - - - - - - false - - - This function is not implemented, yet. - - - Use ramdisk for gamesafe file - - - - - - - - - - Receipts - - - - - - Choose the LaTeX template which shall be used for receipts creation. - - - Template for receipts: - - - - - - - Choose the LaTeX template which shall be used for receipts creation. - - - background: cyan; - - - - - - - Check this if you want the created receipts to be anonymous. - - - background: cyan; - - - Print anonymous receipts - - - - - - - false - - - Choose a string which shall replace the participant name on the anonymous receipts. - - - Substitute participants' names with: - - - - - - - false - - - Choose a string which shall replace the participant name on the anonymous receipts. - - - true - - - \hspace{5cm} - - - 0 - - - - \hspace{5cm} - - - - - anonym - - - - - anonymous - - - - - nicht ausfüllen - - - - - - - - This decides if receipts shall be printed for any z-Leaf instance running locally on the server. - -Warning: If this is disabled no receipts will be printed for ANY participant whose name contains the character string "local"! - - - Print receipts for local clients - - - true - - - - - - - - - - - - Select the clients which shall be attached to this session: - - - Select the clients which shall be attached to this session: - - - - - - - Select the clients which shall be attached to this session. - - - false - - - false - - - - - - - - 0 - 0 - - - - This allows an experimenter to override the normally hard requirement of choosing clients to be attached to the started session and start a session without attached clients. - - - Allow session without attached clients - - - - - - - Start z-Leaf on clients with the session - - - - - - - Start a new session according to the above made settings. - - - Start session - - - - - - - Cancel the creation of a new session. - - - Cancel - - - - - - - - - PBCancel - clicked() - lc::SessionStarter - deleteLater() - - - 319 - 552 - - - 319 - 287 - - - - - From 7563780a791baf24238717682ed777b29d240b12 Mon Sep 17 00:00:00 2001 From: markuspg Date: Sat, 17 Feb 2018 19:31:08 +0100 Subject: [PATCH 02/30] Add code formatting definition to project Enable "Automatic Formatting on File Save" in Qt Creator to utilize this. --- Labcontrol.pro | 3 +++ codingStyle.astylerc | 10 ++++++++++ 2 files changed, 13 insertions(+) create mode 100644 codingStyle.astylerc diff --git a/Labcontrol.pro b/Labcontrol.pro index 64cf3b4..e38b6ce 100755 --- a/Labcontrol.pro +++ b/Labcontrol.pro @@ -42,6 +42,9 @@ FORMS += src/localzleafstarter.ui \ QMAKE_CXXFLAGS += -std=c++11 +DISTFILES += \ + codingStyle.astylerc + OTHER_FILES += \ labcontrol.desktop \ LICENSE \ diff --git a/codingStyle.astylerc b/codingStyle.astylerc new file mode 100644 index 0000000..b639594 --- /dev/null +++ b/codingStyle.astylerc @@ -0,0 +1,10 @@ +--style=kr +--indent=spaces=4 +--align-pointer=name +--align-reference=name +--convert-tabs +--attach-namespaces +--max-code-length=100 +--max-instatement-indent=120 +--pad-header +--pad-oper From 4e090a771ad3956dc8efdd7a8790b298ee872b86 Mon Sep 17 00:00:00 2001 From: markuspg Date: Sat, 17 Feb 2018 19:31:52 +0100 Subject: [PATCH 03/30] Remove static C++11 application Since almost all Linux distribution nowadays default to >=C++11 this manual setting is not needed anymore. --- Labcontrol.pro | 2 -- 1 file changed, 2 deletions(-) diff --git a/Labcontrol.pro b/Labcontrol.pro index e38b6ce..0fb2715 100755 --- a/Labcontrol.pro +++ b/Labcontrol.pro @@ -40,8 +40,6 @@ FORMS += src/localzleafstarter.ui \ src/mainwindow.ui \ src/manualprintingsetup.ui -QMAKE_CXXFLAGS += -std=c++11 - DISTFILES += \ codingStyle.astylerc From a506443ed7faf8d788621e16fa2ef1a7560e147d Mon Sep 17 00:00:00 2001 From: markuspg Date: Sat, 17 Feb 2018 20:10:51 +0100 Subject: [PATCH 04/30] Minor adjustments to main.cpp --- src/main.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index ba01477..da2f43e 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser * * This file is part of Labcontrol. * @@ -17,20 +17,22 @@ * along with Labcontrol. If not, see . */ -#include +#include "mainwindow.h" +#include "Lib/settings.h" #include -#include "mainwindow.h" -#include "Lib/settings.h" +#include -std::unique_ptr< lc::Settings > settings; +std::unique_ptr settings; -int main( int argc, char *argv[] ) { - QApplication a{ argc, argv }; - settings.reset( new lc::Settings{ QSettings{ "Labcontrol", "Labcontrol" } } ); +int main(int argc, char *argv[]) +{ + QApplication a{argc, argv}; + settings = std::make_unique(QSettings{"Labcontrol", + "Labcontrol"}); lc::MainWindow w; w.show(); - + return a.exec(); } From 42d7e76435564eba29ea068ae77c74e99738f8a0 Mon Sep 17 00:00:00 2001 From: markuspg Date: Mon, 12 Mar 2018 19:13:40 +0100 Subject: [PATCH 05/30] Reformat LocalzLeafStarter --- src/localzleafstarter.cpp | 54 +++++++++++++++++++++------------------ src/localzleafstarter.h | 16 +++++++----- src/localzleafstarter.ui | 0 3 files changed, 38 insertions(+), 32 deletions(-) mode change 100755 => 100644 src/localzleafstarter.cpp mode change 100755 => 100644 src/localzleafstarter.h mode change 100755 => 100644 src/localzleafstarter.ui diff --git a/src/localzleafstarter.cpp b/src/localzleafstarter.cpp old mode 100755 new mode 100644 index 2c25413..9455524 --- a/src/localzleafstarter.cpp +++ b/src/localzleafstarter.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -17,53 +17,57 @@ * along with Labcontrol. If not, see . */ -#include - -#include - #include "localzleafstarter.h" #include "ui_localzleafstarter.h" #include "Lib/settings.h" -extern std::unique_ptr< lc::Settings > settings; +#include + +#include + +extern std::unique_ptr settings; -lc::LocalzLeafStarter::LocalzLeafStarter( QWidget *argParent ) : - QWidget{ argParent }, - ui{ new Ui::LocalzLeafStarter } +lc::LocalzLeafStarter::LocalzLeafStarter(QWidget *argParent) : + QWidget{argParent}, + ui{new Ui::LocalzLeafStarter} { - ui->setupUi( this ); + ui->setupUi(this); //Choose initial port from settings - if ( settings->GetChosenZTreePort() ) { - ui->SBzLeafPort->setValue( settings->GetChosenZTreePort() ); + if (settings->GetChosenZTreePort()) { + ui->SBzLeafPort->setValue(settings->GetChosenZTreePort()); } //Choose initial z-Leave size from settings - ui->LELocalzLeafSize->setText( settings->GetLocalzLeafSize() ); + ui->LELocalzLeafSize->setText(settings->GetLocalzLeafSize()); - ui->CBzLeafVersion->addItem( tr( "Please choose a version" ) ); - if ( !settings->installedZTreeVersions.isEmpty() ) { - ui->CBzLeafVersion->addItems( settings->installedZTreeVersions ); + ui->CBzLeafVersion->addItem(tr("Please choose a version")); + if (!settings->installedZTreeVersions.isEmpty()) { + ui->CBzLeafVersion->addItems(settings->installedZTreeVersions); } } -lc::LocalzLeafStarter::~LocalzLeafStarter() { +lc::LocalzLeafStarter::~LocalzLeafStarter() +{ delete ui; } -void lc::LocalzLeafStarter::on_PBStartLocalzLeaf_clicked() { - if ( ui->CBzLeafVersion->currentIndex() == 0 ) { - QMessageBox::information( this, tr( "No z-Tree version chosen" ), - tr( "The was not chosen a z-Tree version, yet. This is" - " mandatory, so please set one" ) , QMessageBox::Ok ); +void lc::LocalzLeafStarter::on_PBStartLocalzLeaf_clicked() +{ + if (ui->CBzLeafVersion->currentIndex() == 0) { + QMessageBox::information(this, tr("No z-Tree version chosen"), + tr("The was not chosen a z-Tree version, yet." + " This is mandatory, so please set one"), + QMessageBox::Ok); return; } //Set chosen z-Leaf size - settings->SetLocalzLeafSize( ui->LELocalzLeafSize->text() ); + settings->SetLocalzLeafSize(ui->LELocalzLeafSize->text()); //Emit start local z-Leaf request to main window - emit LocalzLeafRequested( ui->LEzLeafName->text(), ui->CBzLeafVersion->currentText(), - ui->SBzLeafPort->value() ); + emit LocalzLeafRequested(ui->LEzLeafName->text(), + ui->CBzLeafVersion->currentText(), + ui->SBzLeafPort->value()); } diff --git a/src/localzleafstarter.h b/src/localzleafstarter.h old mode 100755 new mode 100644 index ba4a951..d8704ac --- a/src/localzleafstarter.h +++ b/src/localzleafstarter.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -26,20 +26,22 @@ namespace lc { namespace Ui { class LocalzLeafStarter; -} +} // namespace Ui -class LocalzLeafStarter : public QWidget { +class LocalzLeafStarter : public QWidget +{ Q_OBJECT public: - explicit LocalzLeafStarter( QWidget *argParent = nullptr ); - ~LocalzLeafStarter(); + explicit LocalzLeafStarter(QWidget *argParent = nullptr); + ~LocalzLeafStarter() override; signals: - void LocalzLeafRequested( QString argzLeafName, QString argzLeafVersion, int argzTreePort ); + void LocalzLeafRequested(QString argzLeafName, QString argzLeafVersion, + int argzTreePort); private: - Ui::LocalzLeafStarter *ui = nullptr; + Ui::LocalzLeafStarter *const ui = nullptr; private slots: void on_PBStartLocalzLeaf_clicked(); diff --git a/src/localzleafstarter.ui b/src/localzleafstarter.ui old mode 100755 new mode 100644 From 7f532cbd211f3ef068be631b092bf1f5505a4b35 Mon Sep 17 00:00:00 2001 From: markuspg Date: Mon, 12 Mar 2018 19:25:03 +0100 Subject: [PATCH 06/30] Reformat ManualPrintingSetup --- src/manualprintingsetup.cpp | 103 +++++++++++++++++++----------------- src/manualprintingsetup.h | 27 +++++----- src/manualprintingsetup.ui | 0 3 files changed, 68 insertions(+), 62 deletions(-) mode change 100755 => 100644 src/manualprintingsetup.cpp mode change 100755 => 100644 src/manualprintingsetup.h mode change 100755 => 100644 src/manualprintingsetup.ui diff --git a/src/manualprintingsetup.cpp b/src/manualprintingsetup.cpp old mode 100755 new mode 100644 index 2eda978..5b67514 --- a/src/manualprintingsetup.cpp +++ b/src/manualprintingsetup.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -17,83 +17,88 @@ * along with Labcontrol. If not, see . */ -#include - -#include - #include "manualprintingsetup.h" #include "ui_manualprintingsetup.h" #include "Lib/settings.h" -extern std::unique_ptr< lc::Settings > settings; +#include + +#include -lc::ManualPrintingSetup::ManualPrintingSetup( QWidget *argParent ) : - QWidget{ argParent }, - ui{ new Ui::ManualPrintingSetup } +extern std::unique_ptr settings; + +lc::ManualPrintingSetup::ManualPrintingSetup(QWidget *argParent) : + QWidget{argParent}, + ui{new Ui::ManualPrintingSetup} { - ui->setupUi( this ); + ui->setupUi(this); - if ( settings->dvipsCmd.isEmpty() || settings->latexCmd.isEmpty() - || settings->lcDataDir.isEmpty() || settings->lprCmd.isEmpty() - || settings->postscriptViewer.isEmpty() || settings->ps2pdfCmd.isEmpty() - || settings->rmCmd.isEmpty() || settings->vncViewer.isEmpty() ) { - ui->VLManualPrintingSetup->setEnabled( false ); - QMessageBox::information( this, tr( "Receipts printing will not work" ), - tr( "Some component essential for receipts creation and" - " printing is missing. No receipts will be created or" - " printed." ), QMessageBox::Ok ); + if (settings->dvipsCmd.isEmpty() || settings->latexCmd.isEmpty() + || settings->lcDataDir.isEmpty() || settings->lprCmd.isEmpty() + || settings->postscriptViewer.isEmpty() || settings->ps2pdfCmd.isEmpty() + || settings->rmCmd.isEmpty() || settings->vncViewer.isEmpty()) { + ui->VLManualPrintingSetup->setEnabled(false); + QMessageBox::information(this, tr("Receipts printing will not work"), + tr("Some component essential for receipts creation and" + " printing is missing. No receipts will be created or" + " printed."), QMessageBox::Ok); } else { - ui->CBReceiptsHeader->addItems( settings->installedLaTeXHeaders ); + ui->CBReceiptsHeader->addItems(settings->installedLaTeXHeaders); - if ( settings->defaultReceiptIndex - && settings->defaultReceiptIndex < ui->CBReceiptsHeader->count() ) { - ui->CBReceiptsHeader->setCurrentIndex( settings->defaultReceiptIndex ); + if (settings->defaultReceiptIndex + && settings->defaultReceiptIndex < ui->CBReceiptsHeader->count()) { + ui->CBReceiptsHeader->setCurrentIndex(settings->defaultReceiptIndex); } } } -lc::ManualPrintingSetup::~ManualPrintingSetup() { +lc::ManualPrintingSetup::~ManualPrintingSetup() +{ delete ui; } -void lc::ManualPrintingSetup::on_PBSelectFile_clicked() { - QFileDialog fileDialog{ this, tr( "Please choose a payment file to print." ), - QDir::homePath(), "*.pay" }; - fileDialog.setFileMode( QFileDialog::ExistingFile ); - fileDialog.setOption( QFileDialog::ReadOnly, true ); - if ( fileDialog.exec() ) { - ui->PBSelectFile->setStyleSheet( "" ); - const QString tmpFileName{ fileDialog.selectedFiles().at( 0 ) }; - dateString = tmpFileName.split( '/', QString::KeepEmptyParts, - Qt::CaseInsensitive ).last() - .split( '.', QString::KeepEmptyParts, - Qt::CaseInsensitive ).first(); +void lc::ManualPrintingSetup::on_PBSelectFile_clicked() +{ + QFileDialog fileDialog{this, tr("Please choose a payment file to print."), + QDir::homePath(), "*.pay"}; + fileDialog.setFileMode(QFileDialog::ExistingFile); + fileDialog.setOption(QFileDialog::ReadOnly, true); + if (fileDialog.exec()) { + ui->PBSelectFile->setStyleSheet(""); + const QString tmpFileName{fileDialog.selectedFiles().at(0)}; + dateString = tmpFileName.split('/', QString::KeepEmptyParts, + Qt::CaseInsensitive).last() + .split('.', QString::KeepEmptyParts, + Qt::CaseInsensitive).first(); workPath = tmpFileName; - workPath.truncate( workPath.lastIndexOf( '/' ) ); + workPath.truncate(workPath.lastIndexOf('/')); } } -void lc::ManualPrintingSetup::on_CBReceiptsHeader_activated( int argIndex ) { - Q_UNUSED( argIndex ); - ui->CBReceiptsHeader->setStyleSheet( "" ); +void lc::ManualPrintingSetup::on_CBReceiptsHeader_activated(const int argIndex) +{ + Q_UNUSED(argIndex); + ui->CBReceiptsHeader->setStyleSheet(""); } -void lc::ManualPrintingSetup::on_ChBPrintAnonymousReceipts_clicked( bool argChecked ) { - ui->ChBPrintAnonymousReceipts->setStyleSheet( "" ); +void lc::ManualPrintingSetup::on_ChBPrintAnonymousReceipts_clicked(const bool argChecked) +{ + ui->ChBPrintAnonymousReceipts->setStyleSheet(""); - ui->LReplaceParticipantNames->setEnabled( argChecked ); - ui->CBReplaceParticipantNames->setEnabled( argChecked ); + ui->LReplaceParticipantNames->setEnabled(argChecked); + ui->CBReplaceParticipantNames->setEnabled(argChecked); } -void lc::ManualPrintingSetup::on_PBPrint_clicked() { +void lc::ManualPrintingSetup::on_PBPrint_clicked() +{ QString anonymousReceiptsPlaceholder; - if ( ui->ChBPrintAnonymousReceipts->isChecked() ) { + if (ui->ChBPrintAnonymousReceipts->isChecked()) { anonymousReceiptsPlaceholder = ui->CBReplaceParticipantNames->currentText(); } - emit RequestReceiptsHandler( workPath, ui->ChBReceiptsForLocalClients->isChecked(), - anonymousReceiptsPlaceholder, - ui->CBReceiptsHeader->currentText(), dateString ); + emit RequestReceiptsHandler(workPath, ui->ChBReceiptsForLocalClients->isChecked(), + anonymousReceiptsPlaceholder, + ui->CBReceiptsHeader->currentText(), dateString); this->deleteLater(); } diff --git a/src/manualprintingsetup.h b/src/manualprintingsetup.h old mode 100755 new mode 100644 index beec904..bcb7529 --- a/src/manualprintingsetup.h +++ b/src/manualprintingsetup.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -26,21 +26,22 @@ namespace lc { namespace Ui { class ManualPrintingSetup; -} +} // namespace Ui -class ManualPrintingSetup : public QWidget { +class ManualPrintingSetup : public QWidget +{ Q_OBJECT public: - explicit ManualPrintingSetup( QWidget *argParent = nullptr ); - ~ManualPrintingSetup(); + explicit ManualPrintingSetup(QWidget *argParent = nullptr); + ~ManualPrintingSetup() override; signals: - void RequestReceiptsHandler( QString argzTreeDataTargetPath, - bool argReceiptsForLocalClients, - QString argAnonymousReceiptsPlaceholder, - QString argLatexHeaderName, - QString argDateString ); + void RequestReceiptsHandler(QString argzTreeDataTargetPath, + bool argReceiptsForLocalClients, + QString argAnonymousReceiptsPlaceholder, + QString argLatexHeaderName, + QString argDateString); private: QString dateString; @@ -48,12 +49,12 @@ private: QString workPath; private slots: - void on_CBReceiptsHeader_activated( int argIndex ); - void on_ChBPrintAnonymousReceipts_clicked( bool argChecked ); + void on_CBReceiptsHeader_activated(const int argIndex); + void on_ChBPrintAnonymousReceipts_clicked(const bool argChecked); void on_PBPrint_clicked(); void on_PBSelectFile_clicked(); }; -} +} // namespace lc #endif // MANUALPRINTINGSETUP_H diff --git a/src/manualprintingsetup.ui b/src/manualprintingsetup.ui old mode 100755 new mode 100644 From 688c1ee3fde607f16ac73585ccf3f09a70e2007a Mon Sep 17 00:00:00 2001 From: markuspg Date: Mon, 12 Mar 2018 19:36:47 +0100 Subject: [PATCH 07/30] Reformat ZTree --- src/Lib/session.cpp | 27 +++++++++++++++---------- src/Lib/ztree.cpp | 48 ++++++++++++++++++++++----------------------- src/Lib/ztree.h | 21 ++++++++++---------- 3 files changed, 51 insertions(+), 45 deletions(-) mode change 100755 => 100644 src/Lib/session.cpp mode change 100755 => 100644 src/Lib/ztree.cpp mode change 100755 => 100644 src/Lib/ztree.h diff --git a/src/Lib/session.cpp b/src/Lib/session.cpp old mode 100755 new mode 100644 index 0e79879..ea9e93e --- a/src/Lib/session.cpp +++ b/src/Lib/session.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -17,14 +17,16 @@ * along with Labcontrol. If not, see . */ -#include - #include "session.h" #include "settings.h" +#include + +#include + extern std::unique_ptr< lc::Settings > settings; -lc::Session::Session( QVector< Client* > &&argAssocClients, +lc::Session::Session( QVector< Client * > &&argAssocClients, const QString &argZTreeDataTargetPath, const quint16 argZTreePort, const QString &argZTreeVersionPath, bool argPrintReceiptsForLocalClients, const QString &argAnonymousReceiptsPlaceholder, @@ -54,14 +56,16 @@ lc::Session::Session( QVector< Client* > &&argAssocClients, } } -lc::Session::~Session() { +lc::Session::~Session() +{ for ( auto &client : assocClients ) { client->SetSessionPort( 0 ); client->SetzLeafVersion( "" ); } } -QVariant lc::Session::GetDataItem( int argIndex ) { +QVariant lc::Session::GetDataItem( int argIndex ) +{ switch ( argIndex ) { case 0: return QVariant{ zTreeVersionPath.split( '_', QString::KeepEmptyParts, Qt::CaseInsensitive )[ 1 ] }; @@ -72,7 +76,8 @@ QVariant lc::Session::GetDataItem( int argIndex ) { } } -void lc::Session::InitializeClasses() { +void lc::Session::InitializeClasses() +{ // Create the new data directory QDir dir{ zTreeDataTargetPath }; QString date_string( QDateTime::currentDateTime().toString( "yyMMdd_hhmm" ) ); @@ -87,7 +92,7 @@ void lc::Session::InitializeClasses() { this, &Session::OnzTreeClosed ); // Only create a 'Receipts_Handler' instance, if all neccessary variables were set if ( latexHeaderName != "None found" && !settings->dvipsCmd.isEmpty() - && !settings->latexCmd.isEmpty() ) { + && !settings->latexCmd.isEmpty() ) { new ReceiptsHandler{ zTreeDataTargetPath, printReceiptsForLocalClients, anonymousReceiptsPlaceholder, latexHeaderName, this }; } else { @@ -95,12 +100,14 @@ void lc::Session::InitializeClasses() { } } -void lc::Session::OnzTreeClosed( int argExitCode ) { +void lc::Session::OnzTreeClosed( int argExitCode ) +{ qDebug() << "z-Tree running on port" << zTreePort << "closed with exit code" << argExitCode; emit SessionFinished( this ); } -void lc::Session::RenameWindow() { +void lc::Session::RenameWindow() +{ // Example: wmctrl -r -T QStringList arguments; diff --git a/src/Lib/ztree.cpp b/src/Lib/ztree.cpp old mode 100755 new mode 100644 index 706d11b..4c1c3e5 --- a/src/Lib/ztree.cpp +++ b/src/Lib/ztree.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -17,35 +17,35 @@ * along with Labcontrol. If not, see . */ -#include +#include "settings.h" +#include "ztree.h" #include +#include -#include "settings.h" -#include "ztree.h" +#include -extern std::unique_ptr< lc::Settings > settings; +extern std::unique_ptr settings; -lc::ZTree::ZTree( const QString &argZTreeDataTargetPath, const int &argZTreePort, - const QString &argZTreeVersionPath, QObject *argParent ) : - QObject{ argParent } +lc::ZTree::ZTree(const QString &argZTreeDataTargetPath, const int argZTreePort, + const QString &argZTreeVersionPath, QObject *argParent) : + QObject{argParent} { - QStringList arguments{ QStringList{} << "-c" << "0" << settings->wineCmd - << QString{ settings->zTreeInstDir + "/zTree_" - + argZTreeVersionPath + "/ztree.exe" } - << "/datadir" << QString{ "Z:/" + argZTreeDataTargetPath } - << "/privdir" << QString{ "Z:/" + argZTreeDataTargetPath } - << "/gsfdir" << QString{ "Z:/" + argZTreeDataTargetPath } - << "/tempdir" << QString{ "Z:/" + argZTreeDataTargetPath } - << "/leafdir" << QString{ "Z:/" + argZTreeDataTargetPath } - << "/channel" << QString::number( argZTreePort - 7000 ) }; + QStringList arguments{QStringList{} << "-c" << "0" << settings->wineCmd + << QString{settings->zTreeInstDir + "/zTree_" + + argZTreeVersionPath + "/ztree.exe"} + << "/datadir" << QString{"Z:/" + argZTreeDataTargetPath} + << "/privdir" << QString{"Z:/" + argZTreeDataTargetPath} + << "/gsfdir" << QString{"Z:/" + argZTreeDataTargetPath} + << "/tempdir" << QString{"Z:/" + argZTreeDataTargetPath} + << "/leafdir" << QString{"Z:/" + argZTreeDataTargetPath} + << "/channel" << QString::number(argZTreePort - 7000)}; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - zTreeInstance.setProcessEnvironment( env ); - zTreeInstance.setWorkingDirectory( QDir::homePath() ); - zTreeInstance.start( settings->tasksetCmd, arguments, QIODevice::NotOpen ); - connect( &zTreeInstance, SIGNAL( finished( int ) ), - this, SIGNAL( ZTreeClosed( int ) ) ); + zTreeInstance.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + zTreeInstance.setWorkingDirectory(QDir::homePath()); + zTreeInstance.start(settings->tasksetCmd, arguments, QIODevice::NotOpen); + connect(&zTreeInstance, SIGNAL(finished(int)), + this, SIGNAL(ZTreeClosed(int))); - qDebug() << settings->tasksetCmd << arguments.join( " " ); + qDebug() << settings->tasksetCmd << arguments.join(" "); } diff --git a/src/Lib/ztree.h b/src/Lib/ztree.h old mode 100755 new mode 100644 index 2935189..1684b07 --- a/src/Lib/ztree.h +++ b/src/Lib/ztree.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -20,33 +20,32 @@ #ifndef ZTREE_H #define ZTREE_H -#include -#include -#include - #include "global.h" +#include + namespace lc { //! A class to contain running zTree instances. /*! This class is element of every session and is used to handle all zTree related data. */ -class ZTree: public QObject { +class ZTree: public QObject +{ Q_OBJECT public: - ZTree( const QString &argZTreeDataTargetPath, - const int &argZTreePort, const QString &argZTreeVersionPath, - QObject *argParent = nullptr ); + ZTree(const QString &argZTreeDataTargetPath, + const int argZTreePort, const QString &argZTreeVersionPath, + QObject *argParent = nullptr); signals: - void ZTreeClosed( int argExitCode ); + void ZTreeClosed(int argExitCode); private: QProcess zTreeInstance; }; -} +} // namespace lc #endif // ZTREE_H From c3e623f236b78a9147771e5f6b8d788b0108f831 Mon Sep 17 00:00:00 2001 From: markuspg Date: Mon, 12 Mar 2018 21:01:25 +0100 Subject: [PATCH 08/30] Reformat Session --- src/Lib/sessionsmodel.cpp | 39 ++++++++++++++++++++++++--------------- src/Lib/sessionsmodel.h | 26 ++++++++++++-------------- 2 files changed, 36 insertions(+), 29 deletions(-) mode change 100755 => 100644 src/Lib/sessionsmodel.cpp mode change 100755 => 100644 src/Lib/sessionsmodel.h diff --git a/src/Lib/sessionsmodel.cpp b/src/Lib/sessionsmodel.cpp old mode 100755 new mode 100644 index 4829097..1420254 --- a/src/Lib/sessionsmodel.cpp +++ b/src/Lib/sessionsmodel.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -19,23 +19,27 @@ #include +#include "session.h" #include "sessionsmodel.h" -lc::SessionsModel::SessionsModel( QObject *argParent ) : - QAbstractTableModel{ argParent } +lc::SessionsModel::SessionsModel(QObject *argParent) : + QAbstractTableModel{argParent} { } -lc::Session *lc::SessionsModel::back() const { +lc::Session *lc::SessionsModel::back() const +{ return sessionsList.back(); } -int lc::SessionsModel::columnCount(const QModelIndex &parent) const { +int lc::SessionsModel::columnCount(const QModelIndex &parent) const +{ Q_UNUSED(parent); return 2; } -QVariant lc::SessionsModel::data(const QModelIndex &index, int role) const { +QVariant lc::SessionsModel::data(const QModelIndex &index, int role) const +{ if (!index.isValid()) return QVariant{}; @@ -43,14 +47,16 @@ QVariant lc::SessionsModel::data(const QModelIndex &index, int role) const { return QVariant{}; if (role == Qt::DisplayRole) - return sessionsList.at( index.row() )->GetDataItem( index.column() ); + return sessionsList.at(index.row())->GetDataItem(index.column()); return QVariant{}; } -QVariant lc::SessionsModel::headerData(int section, Qt::Orientation orientation, int role) const { +QVariant lc::SessionsModel::headerData(int section, Qt::Orientation orientation, + int role) const +{ if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { - switch(section) { + switch (section) { case 0: return tr("zTree Version"); case 1: @@ -66,21 +72,24 @@ QVariant lc::SessionsModel::headerData(int section, Qt::Orientation orientation, return QVariant{}; } -void lc::SessionsModel::push_back( Session *argSession ) { +void lc::SessionsModel::push_back(Session *argSession) +{ connect( argSession, &Session::SessionFinished, this, &SessionsModel::RemoveSession ); - argSession->setParent( this ); - sessionsList.push_back( argSession ); + argSession->setParent(this); + sessionsList.push_back(argSession); } -void lc::SessionsModel::RemoveSession( Session *argSession ) { - if ( sessionsList.removeAll( argSession ) ) { +void lc::SessionsModel::RemoveSession(Session *argSession) +{ + if (sessionsList.removeAll(argSession)) { qDebug() << "Successfully removed" << argSession << "from lc::SessionsModel"; argSession->deleteLater(); } } -int lc::SessionsModel::rowCount(const QModelIndex &parent) const { +int lc::SessionsModel::rowCount(const QModelIndex &parent) const +{ Q_UNUSED(parent); return sessionsList.length(); } diff --git a/src/Lib/sessionsmodel.h b/src/Lib/sessionsmodel.h old mode 100755 new mode 100644 index 22e0bca..cdda6e1 --- a/src/Lib/sessionsmodel.h +++ b/src/Lib/sessionsmodel.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -22,33 +22,31 @@ #include -#include "session.h" - namespace lc { -class SessionsModel : public QAbstractTableModel { +class Session; + +class SessionsModel : public QAbstractTableModel +{ Q_OBJECT + public: - explicit SessionsModel(QObject *parent = 0); - SessionsModel(const SessionsModel&) = delete; + explicit SessionsModel(QObject *parent = nullptr); + SessionsModel(const SessionsModel &) = delete; Session *back() const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; - void push_back( Session *argSession ); + void push_back(Session *argSession); int rowCount(const QModelIndex &parent) const; -signals: - -public slots: - private: - QList< Session* > sessionsList; + QList sessionsList; private slots: - void RemoveSession( Session *argSession ); + void RemoveSession(Session *argSession); }; -} +} // namespace lc #endif // SESSIONSMODEL_H From c2d4f6024c78effa4d7ef610067a718b2ede842f Mon Sep 17 00:00:00 2001 From: markuspg Date: Mon, 12 Mar 2018 21:10:52 +0100 Subject: [PATCH 09/30] Reformat NetstatAgent --- src/Lib/netstatagent.cpp | 42 +++++++++++++++++++--------------------- src/Lib/netstatagent.h | 28 ++++++++++++++++----------- 2 files changed, 37 insertions(+), 33 deletions(-) mode change 100755 => 100644 src/Lib/netstatagent.cpp mode change 100755 => 100644 src/Lib/netstatagent.h diff --git a/src/Lib/netstatagent.cpp b/src/Lib/netstatagent.cpp old mode 100755 new mode 100644 index 44caed5..6685c26 --- a/src/Lib/netstatagent.cpp +++ b/src/Lib/netstatagent.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -19,33 +19,31 @@ #include "netstatagent.h" -lc::NetstatAgent::NetstatAgent( const QString &argNetstatCommand, QObject *argParent ) : - QObject{ argParent }, - extractionRegexp{ "\\d+\\.\\d+\\.\\d+\\.\\d+" }, - netstatArguments{ QStringList{} << "-anp" << "--tcp" }, - netstatCommand{ argNetstatCommand }, - netstatQueryProcess{ this }, - searchRegexp{ "\\W(ESTABLISHED|VERBUNDEN)( +)(\\d+)(/ztree.exe)\\W", QRegularExpression::CaseInsensitiveOption } +lc::NetstatAgent::NetstatAgent(const QString &argNetstatCommand, + QObject *argParent) : + QObject{argParent}, + netstatCommand{argNetstatCommand} { - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - netstatQueryProcess.setProcessEnvironment( env ); + netstatQueryProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); } -void lc::NetstatAgent::QueryClientConnections() { - netstatQueryProcess.start( netstatCommand, netstatArguments ); - if ( !netstatQueryProcess.waitForFinished( 400 ) ) { - emit QueryFinished( nullptr ); +void lc::NetstatAgent::QueryClientConnections() +{ + netstatQueryProcess.start(netstatCommand, netstatArguments); + if (!netstatQueryProcess.waitForFinished(400)) { + emit QueryFinished(nullptr); } else { // Get all 'netstat_query_process' standard output and store it temporarily in 'temp_strings' - QByteArray netstatQueryProcessOutputByteArray = netstatQueryProcess.readAllStandardOutput(); - QString netstatQueryProcessOutputString( netstatQueryProcessOutputByteArray ); - QStringList tempStrings = netstatQueryProcessOutputString.split( '\n', QString::SkipEmptyParts ); + const QString netstatQueryProcessOutputString{netstatQueryProcess.readAllStandardOutput()}; + const QStringList tempStrings{ + netstatQueryProcessOutputString.split('\n', QString::SkipEmptyParts)}; - QStringList *netstatQueryProcessOutput = new QStringList; - for ( auto s: tempStrings ) { - if ( s.contains( searchRegexp ) ) { - QRegularExpressionMatch match = extractionRegexp.match( s, s.indexOf( ':', 0, Qt::CaseInsensitive ) ); - netstatQueryProcessOutput->append( match.captured() ); + const auto netstatQueryProcessOutput = new QStringList; + for (const auto &s : tempStrings) { + if (s.contains(searchRegexp)) { + QRegularExpressionMatch match{extractionRegexp.match(s, s.indexOf(':', 0, + Qt::CaseInsensitive))}; + netstatQueryProcessOutput->append(match.captured()); } } diff --git a/src/Lib/netstatagent.h b/src/Lib/netstatagent.h old mode 100755 new mode 100644 index f295c6b..a057ae4 --- a/src/Lib/netstatagent.h +++ b/src/Lib/netstatagent.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -31,27 +31,33 @@ namespace lc { /*! This class is just used for repetive executions of netstat. */ -class NetstatAgent : public QObject { +class NetstatAgent : public QObject +{ Q_OBJECT public: - explicit NetstatAgent( const QString &argNetstatCommand, QObject *argParent = nullptr ); - + explicit NetstatAgent(const QString &argNetstatCommand, + QObject *argParent = nullptr); + signals: //! This signal is emitted if the query of the currently active zLeaf connections finished void QueryFinished(QStringList *argActiveZLeafConnections); - + public slots: void QueryClientConnections(); - + private: - const QRegularExpression extractionRegexp; - const QStringList netstatArguments; - const QString &netstatCommand; + const QRegularExpression extractionRegexp + = QRegularExpression{"\\d+\\.\\d+\\.\\d+\\.\\d+"}; + const QStringList netstatArguments + = QStringList{"-anp", "--tcp"}; + const QString netstatCommand; QProcess netstatQueryProcess; - const QRegularExpression searchRegexp; + const QRegularExpression searchRegexp + = QRegularExpression{"\\W(ESTABLISHED|VERBUNDEN)( +)(\\d+)(/ztree.exe)\\W", + QRegularExpression::CaseInsensitiveOption}; }; -} +} // namespace lc #endif // NETSTATAGENT_H From 385a42dedfa44d7825c23364fbe82c12ff146381 Mon Sep 17 00:00:00 2001 From: markuspg Date: Mon, 12 Mar 2018 21:57:25 +0100 Subject: [PATCH 10/30] Reformat ClientPinger --- src/Lib/clientpinger.cpp | 43 ++++++++++++++++++++-------------------- src/Lib/clientpinger.h | 34 ++++++++++++++++++------------- 2 files changed, 41 insertions(+), 36 deletions(-) mode change 100755 => 100644 src/Lib/clientpinger.cpp mode change 100755 => 100644 src/Lib/clientpinger.h diff --git a/src/Lib/clientpinger.cpp b/src/Lib/clientpinger.cpp old mode 100755 new mode 100644 index 65d6f0e..8f4a9d6 --- a/src/Lib/clientpinger.cpp +++ b/src/Lib/clientpinger.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -19,45 +19,44 @@ #include "clientpinger.h" -lc::ClientPinger::ClientPinger( const QString &argIP, - const QString &argPingCommand, QObject *argParent ) : - QObject{ argParent }, +lc::ClientPinger::ClientPinger(const QString &argIP, + const QString &argPingCommand, + QObject *argParent) : + QObject{argParent}, // Arguments: -c 1 (send 1 ECHO_REQUEST packet) -w 1 (timeout after 1 second) -q (quiet output) - pingArguments{ QStringList{} << "-c" << "1" << "-w" << "1" << "-q" << argIP }, - pingCommand{ argPingCommand }, - pingProcess{ new QProcess{ this } }, - state{ state_t::UNINITIALIZED } + pingArguments{"-c", "1", "-w", "1", "-q", argIP}, + pingCommand{argPingCommand}, + pingProcess{std::make_unique()} { - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - pingProcess->setProcessEnvironment(env); + pingProcess->setProcessEnvironment(QProcessEnvironment::systemEnvironment()); // emit ping_string(new QString(*ping_command + " " + ping_arguments->join(" "))); } -lc::ClientPinger::~ClientPinger() { - delete pingProcess; -} - -void lc::ClientPinger::doPing() { +void lc::ClientPinger::doPing() +{ // Initialize the new state to be queried state_t newState = state_t::UNINITIALIZED; // Query the current state of the client - pingProcess->start( pingCommand, pingArguments ); - if ( !pingProcess->waitForFinished( 2500 ) ) + pingProcess->start(pingCommand, pingArguments); + if (!pingProcess->waitForFinished(2500) + || pingProcess->exitStatus() != QProcess::NormalExit) newState = state_t::ERROR; else { - if ( pingProcess->exitCode() == 0 ) + if (pingProcess->exitCode() == 0) { newState = state_t::RESPONDING; - else + } else { newState = state_t::NOT_RESPONDING; + } } - if ( newState != state ) { + if (newState != state) { state = newState; - emit PingFinished( newState ); + emit PingFinished(state); } } -void lc::ClientPinger::setStateToZLEAF_RUNNING() { +void lc::ClientPinger::setStateToZLEAF_RUNNING() +{ state = state_t::ZLEAF_RUNNING; } diff --git a/src/Lib/clientpinger.h b/src/Lib/clientpinger.h old mode 100755 new mode 100644 index 4b10490..30b14eb --- a/src/Lib/clientpinger.h +++ b/src/Lib/clientpinger.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -20,11 +20,14 @@ #ifndef CLIENTPINGER_H #define CLIENTPINGER_H +#include "global.h" + #include #include -#include -#include "global.h" +#include + +class QProcess; namespace lc { @@ -32,7 +35,8 @@ namespace lc { /*! This class is just used for executing repetitive pings. */ -class ClientPinger : public QObject { +class ClientPinger : public QObject +{ Q_OBJECT public: @@ -42,10 +46,8 @@ public: @param argPingCommand The path were the command to be executed for pings resides @param argParent The ClientPinger's parent owning this instance of it */ - explicit ClientPinger( const QString &argIP, const QString &argPingCommand, - QObject *argParent = nullptr ); - //! ClientPinger's destructor - ~ClientPinger(); + explicit ClientPinger(const QString &argIP, const QString &argPingCommand, + QObject *argParent = nullptr); public slots: //! This slot executes a ping when called. @@ -54,17 +56,21 @@ public slots: void setStateToZLEAF_RUNNING(); private: - const QStringList pingArguments; //! The arguments for the 'ping' command - const QString pingCommand; //! The 'ping' command itself - QProcess * pingProcess; //! The 'ping' process which will be executed on every call of 'do_ping()' - state_t state; //! Stores the current state of the client + //! The arguments for the 'ping' command + const QStringList pingArguments; + //! The 'ping' command itself + const QString pingCommand; + //! The 'ping' process which will be executed on every call of 'do_ping()' + std::unique_ptr pingProcess; + //! Stores the current state of the client + state_t state = state_t::UNINITIALIZED; signals: //! This signal was just implemented for testing purposes //! This signal is emitted if the ping finished and the state of the client changed - void PingFinished( state_t state ); + void PingFinished(state_t state); }; -} +} // namespace lc #endif // CLIENTPINGER_H From e533ede28bc4a03e6cd2abcb326a23285ccacf0c Mon Sep 17 00:00:00 2001 From: markuspg Date: Mon, 12 Mar 2018 22:23:10 +0100 Subject: [PATCH 11/30] Reformat Client --- src/Lib/client.cpp | 334 ++++++++++++++++++------------------ src/Lib/client.h | 72 +++++--- src/manualprintingsetup.cpp | 8 + src/manualprintingsetup.h | 2 +- 4 files changed, 221 insertions(+), 195 deletions(-) mode change 100755 => 100644 src/Lib/client.cpp mode change 100755 => 100644 src/Lib/client.h diff --git a/src/Lib/client.cpp b/src/Lib/client.cpp old mode 100755 new mode 100644 index bd6d109..bc83671 --- a/src/Lib/client.cpp +++ b/src/Lib/client.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -17,53 +17,52 @@ * along with Labcontrol. If not, see . */ -#include - -#include - -#include "client.h" -#include "settings.h" +#include "clientpinger.h" #include "lablib.h" -extern std::unique_ptr< lc::Settings > settings; -extern std::unique_ptr< lc::Lablib > lablib; - -lc::Client::Client( const QString &argIP, const QString &argMAC, const QString &argName, - unsigned short int argXPosition, unsigned short int argYPosition, - const QString &argPingCmd ): - ip{ argIP }, - mac{ argMAC }, - name{ argName }, - xPosition{ argXPosition }, - yPosition{ argYPosition }, - protectedCycles{ 0 } +#include + +extern std::unique_ptr settings; +extern std::unique_ptr lablib; + +lc::Client::Client(const QString &argIP, const QString &argMAC, const QString &argName, + const unsigned short int argXPosition, + const unsigned short int argYPosition, + const QString &argPingCmd): + ip{argIP}, + mac{argMAC}, + name{argName}, + xPosition{argXPosition}, + yPosition{argYPosition}, + protectedCycles{0} { - qRegisterMetaType< state_t >( "STATE" ); - - if ( !argPingCmd.isEmpty() ) { - pinger = new ClientPinger{ ip, argPingCmd }; - pinger->moveToThread( &pingerThread ); - connect( &pingerThread, &QThread::finished, - pinger, &QObject::deleteLater ); - connect( this, &Client::PingWanted, - pinger, &ClientPinger::doPing ); - connect( pinger, &ClientPinger::PingFinished, - this, &Client::GotStatusChanged ); + qRegisterMetaType("state_t"); + + if (!argPingCmd.isEmpty()) { + pinger = new ClientPinger{ip, argPingCmd}; + pinger->moveToThread(&pingerThread); + connect(&pingerThread, &QThread::finished, + pinger, &QObject::deleteLater); + connect(this, &Client::PingWanted, + pinger, &ClientPinger::doPing); + connect(pinger, &ClientPinger::PingFinished, + this, &Client::GotStatusChanged); pingerThread.start(); - pingTimer = new QTimer{ this }; - connect( pingTimer, &QTimer::timeout, - this, &Client::RequestAPing ) ; - pingTimer->start( 3000 ); + pingTimer = new QTimer{this}; + connect(pingTimer, &QTimer::timeout, + this, &Client::RequestAPing) ; + pingTimer->start(3000); } qDebug() << "Created client" << name << "with MAC" << mac << "and IP" << ip - << "at position" << QString{ QString::number( xPosition ) + "x" - + QString::number( yPosition ) }; + << "at position" << QString{QString::number(xPosition) + "x" + + QString::number(yPosition)}; } -lc::Client::~Client() { - if ( pingTimer ) { +lc::Client::~Client() +{ + if (pingTimer) { pingTimer->stop(); } delete pingTimer; @@ -71,274 +70,277 @@ lc::Client::~Client() { pingerThread.wait(); } -void lc::Client::BeamFile( const QString &argFileToBeam, const QString * const argPublickeyPathUser, const QString * const argUserNameOnClients ) { - if ( state < state_t::RESPONDING ) { +void lc::Client::BeamFile(const QString &argFileToBeam, + const QString *const argPublickeyPathUser, + const QString *const argUserNameOnClients) +{ + if (state < state_t::RESPONDING) { return; } - QStringList arguments; - arguments << "-2" << "-i" << *argPublickeyPathUser << "-l" << "32768" << "-r" - << argFileToBeam << QString{ *argUserNameOnClients + "@" + ip + ":media4ztree" }; + const QStringList arguments{"-2", "-i", *argPublickeyPathUser, "-l", + "32768", "-r", argFileToBeam, + QString{*argUserNameOnClients + "@" + ip + ":media4ztree"}}; // Start the process QProcess beamFileProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - beamFileProcess.setProcessEnvironment( env ); - beamFileProcess.startDetached( settings->scpCmd, arguments ); + beamFileProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + beamFileProcess.startDetached(settings->scpCmd, arguments); - qDebug() << settings->scpCmd << arguments.join( " " ); + qDebug() << settings->scpCmd << arguments.join(" "); } -void lc::Client::Boot() { - QStringList arguments{ QStringList{} << "-i" << settings->netwBrdAddr << mac }; +void lc::Client::Boot() +{ + const QStringList arguments{"-i", settings->netwBrdAddr, mac}; // Start the process QProcess wakeonlanProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - wakeonlanProcess.setProcessEnvironment( env ); - wakeonlanProcess.startDetached( settings->wakeonlanCmd, arguments ); + wakeonlanProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + wakeonlanProcess.startDetached(settings->wakeonlanCmd, arguments); // Output message via the debug messages tab - qDebug() << settings->wakeonlanCmd << arguments.join( " " ); + qDebug() << settings->wakeonlanCmd << arguments.join(" "); - pingTimer->start( 3000 ); + pingTimer->start(3000); protectedCycles = 7; - GotStatusChanged( state_t::BOOTING ); + GotStatusChanged(state_t::BOOTING); } -void lc::Client::GotStatusChanged( state_t argState ) { - if ( ( protectedCycles > 0 ) && ( state == state_t::BOOTING ) && ( argState != state_t::RESPONDING ) ) { +void lc::Client::GotStatusChanged(state_t argState) +{ + if ((protectedCycles > 0) && (state == state_t::BOOTING) + && (argState != state_t::RESPONDING)) { return; } - if ( ( protectedCycles > 0 ) && ( state == state_t::SHUTTING_DOWN ) && argState != state_t::NOT_RESPONDING ) { + if ((protectedCycles > 0) && (state == state_t::SHUTTING_DOWN) + && argState != state_t::NOT_RESPONDING) { return; } state = argState; - qDebug() << name << "status changed to:" << static_cast< unsigned short int >( argState ); + qDebug() << name << "status changed to:" + << static_cast(argState); } -void lc::Client::KillZLeaf() { - QStringList arguments; - arguments << "-i" << settings->pkeyPathUser - << QString{ settings->userNameOnClients + "@" + ip } - << settings->killallCmd << "-I" << "-q" << "zleaf.exe"; +void lc::Client::KillZLeaf() +{ + const QStringList arguments{"-i", settings->pkeyPathUser, + QString{settings->userNameOnClients + "@" + ip}, + settings->killallCmd, "-I", "-q", "zleaf.exe"}; // Start the process QProcess killZLeafProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - killZLeafProcess.setProcessEnvironment( env ); - killZLeafProcess.startDetached( settings->sshCmd, arguments ); + killZLeafProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + killZLeafProcess.startDetached(settings->sshCmd, arguments); // Output message via the debug messages tab - qDebug() << settings->sshCmd << arguments.join( " " ); + qDebug() << settings->sshCmd << arguments.join(" "); // Restart the ping_timer, because it is stopped when a zLeaf is started - pingTimer->start( 3000 ); + pingTimer->start(3000); } -void lc::Client::OpenFilesystem( const QString * const argUserToBeUsed ) { - if ( state < state_t::RESPONDING ) { +void lc::Client::OpenFilesystem(const QString *const argUserToBeUsed) +{ + if (state < state_t::RESPONDING) { return; } - QStringList arguments = QStringList{} << QString{ "sftp://" + *argUserToBeUsed + "@" + ip }; + const QStringList arguments{QString{ "sftp://" + *argUserToBeUsed + "@" + ip }}; QProcess openFilesystemProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - openFilesystemProcess.setProcessEnvironment( env ); - openFilesystemProcess.startDetached( settings->fileMngr, arguments ); - qDebug() << settings->fileMngr << arguments.join( " " ); + openFilesystemProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + openFilesystemProcess.startDetached(settings->fileMngr, arguments); + qDebug() << settings->fileMngr << arguments.join(" "); } -void lc::Client::OpenTerminal( const QString &argCommand, const bool &argOpenAsRoot ) { - if ( !settings->termEmulCmd.isEmpty() ) { - if ( state < state_t::RESPONDING ) { +void lc::Client::OpenTerminal(const QString &argCommand, + const bool argOpenAsRoot) +{ + if (!settings->termEmulCmd.isEmpty()) { + if (state < state_t::RESPONDING) { return; } - QStringList *arguments = nullptr; - arguments = new QStringList; - if ( !argOpenAsRoot ) { - *arguments << "-e" - << QString{ settings->sshCmd + " -i " + settings->pkeyPathUser + " " - + settings->userNameOnClients + "@" + ip }; + QStringList arguments; + if (!argOpenAsRoot) { + arguments << "-e" + << QString{settings->sshCmd + " -i " + settings->pkeyPathUser + " " + + settings->userNameOnClients + "@" + ip}; } else { - *arguments << "-e" << - QString{ settings->sshCmd + " -i " + settings->pkeyPathRoot - + " " + "root@" + ip}; + arguments << "-e" << + QString{settings->sshCmd + " -i " + settings->pkeyPathRoot + + " " + "root@" + ip}; } - if ( !argCommand.isEmpty() ) { - arguments->last().append( " '" + argCommand + "'" ); + if (!argCommand.isEmpty()) { + arguments.last().append(" '" + argCommand + "'"); } QProcess openTerminalProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - openTerminalProcess.setProcessEnvironment( env ); - openTerminalProcess.startDetached( settings->termEmulCmd, *arguments ); - qDebug() << settings->termEmulCmd << arguments->join( " " ); - delete arguments; + openTerminalProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + openTerminalProcess.startDetached(settings->termEmulCmd, arguments); + qDebug() << settings->termEmulCmd << arguments.join(" "); } } -void lc::Client::RequestAPing() { - if ( protectedCycles > 0 ) { +void lc::Client::RequestAPing() +{ + if (protectedCycles > 0) { --protectedCycles; } emit PingWanted(); } -void lc::Client::SetStateToZLEAF_RUNNING( QString argClientIP ) { +void lc::Client::SetStateToZLEAF_RUNNING(const QString &argClientIP) +{ if ( argClientIP != ip ) { return; } - if ( state != state_t::ZLEAF_RUNNING ) { + if (state != state_t::ZLEAF_RUNNING) { pingTimer->stop(); // Inform the ClientPinger instance, that zLeaf is now running pinger->setStateToZLEAF_RUNNING(); - this->GotStatusChanged( state_t::ZLEAF_RUNNING ); + this->GotStatusChanged(state_t::ZLEAF_RUNNING); qDebug() << "Client" << name << "got 'ZLEAF_RUNNING' signal."; } } -void lc::Client::ShowDesktopViewOnly() { - QStringList arguments; - arguments << ip; +void lc::Client::ShowDesktopViewOnly() +{ + QStringList arguments{ip}; QProcess showDesktopProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - showDesktopProcess.setProcessEnvironment( env ); - showDesktopProcess.startDetached( settings->vncViewer, arguments ); + showDesktopProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + showDesktopProcess.startDetached( settings->vncViewer, QStringList{ip}); // Output message via the debug messages tab qDebug() << settings->vncViewer << arguments.join( " " ); } -void lc::Client::ShowDesktopFullControl() { - QStringList arguments; - arguments << ip + ":5901"; +void lc::Client::ShowDesktopFullControl() +{ + const QStringList arguments{QString{ip + ":5901"}}; QProcess showDesktopProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - showDesktopProcess.setProcessEnvironment( env ); - showDesktopProcess.startDetached( settings->vncViewer, arguments ); + showDesktopProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + showDesktopProcess.startDetached(settings->vncViewer, arguments); // Output message via the debug messages tab - qDebug() << settings->vncViewer << arguments.join( " " ); + qDebug() << settings->vncViewer << arguments.join(" "); } -void lc::Client::Shutdown() { - if ( state == state_t::NOT_RESPONDING || state == state_t::BOOTING - || state == state_t::SHUTTING_DOWN ) { +void lc::Client::Shutdown() +{ + if (state == state_t::NOT_RESPONDING || state == state_t::BOOTING + || state == state_t::SHUTTING_DOWN) { return; } - QStringList arguments; - arguments << "-i" << settings->pkeyPathUser - << QString{ settings->userNameOnClients + "@" + ip } << "sudo shutdown -P now"; + const QStringList arguments{"-i", settings->pkeyPathUser, + QString{settings->userNameOnClients + "@" + ip}, + "sudo shutdown -P now"}; // Start the process QProcess shutdownProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - shutdownProcess.setProcessEnvironment( env ); - shutdownProcess.startDetached( settings->sshCmd, arguments ); + shutdownProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + shutdownProcess.startDetached(settings->sshCmd, arguments); // Output message via the debug messages tab - qDebug() << settings->sshCmd << arguments.join( " " ); + qDebug() << settings->sshCmd << arguments.join(" "); // This additional 'ping_timer' start is needed for the case that the clients are shut down without prior closing of zLeaves - pingTimer->start( 3000 ); + pingTimer->start(3000); protectedCycles = 3; - GotStatusChanged( state_t::SHUTTING_DOWN ); + GotStatusChanged(state_t::SHUTTING_DOWN); } -void lc::Client::StartZLeaf( const QString * argFakeName, QString cmd ) { - if ( state < state_t::RESPONDING || zLeafVersion.isEmpty() || GetSessionPort() < 7000 ) { +void lc::Client::StartZLeaf(const QString *argFakeName, QString cmd) +{ + if (state < state_t::RESPONDING + || zLeafVersion.isEmpty() + || GetSessionPort() < 7000) { return; } // Create a QMessageBox for user interaction if there is already a zLeaf running - std::unique_ptr< QMessageBox > messageBoxRunningZLeafFound; - if ( state == state_t::ZLEAF_RUNNING ) { - messageBoxRunningZLeafFound.reset( new QMessageBox{ QMessageBox::Warning, "Running zLeaf found", - QString{ "There is already a zLeaf running on " + name + "." }, - QMessageBox::No | QMessageBox::Yes } ); - messageBoxRunningZLeafFound->setInformativeText( "Do you want to start a zLeaf on client " - + name + " nonetheless?" ); - messageBoxRunningZLeafFound->setDefaultButton( QMessageBox::No ); + std::unique_ptr messageBoxRunningZLeafFound; + if (state == state_t::ZLEAF_RUNNING) { + messageBoxRunningZLeafFound.reset(new QMessageBox{QMessageBox::Warning, "Running zLeaf found", + QString{"There is already a zLeaf running on " + name + "."}, + QMessageBox::No | QMessageBox::Yes}); + messageBoxRunningZLeafFound->setInformativeText("Do you want to start a zLeaf on client " + + name + " nonetheless?"); + messageBoxRunningZLeafFound->setDefaultButton(QMessageBox::No); messageBoxRunningZLeafFound->exec(); } - if ( ( messageBoxRunningZLeafFound.get() != nullptr - && messageBoxRunningZLeafFound->clickedButton() - == messageBoxRunningZLeafFound->button( QMessageBox::Yes ) ) - || state != state_t::ZLEAF_RUNNING ) { + if ((messageBoxRunningZLeafFound.get() != nullptr + && messageBoxRunningZLeafFound->clickedButton() + == messageBoxRunningZLeafFound->button(QMessageBox::Yes)) + || state != state_t::ZLEAF_RUNNING) { QStringList arguments; - if ( argFakeName == nullptr ) { + if (argFakeName == nullptr) { arguments << "-i" << settings->pkeyPathUser - << QString{ settings->userNameOnClients + "@" + ip } + << QString{settings->userNameOnClients + "@" + ip} << cmd; } else { arguments << "-i" << settings->pkeyPathUser - << QString{ settings->userNameOnClients + "@" + ip } + << QString{settings->userNameOnClients + "@" + ip} << cmd << "/name" << *argFakeName; } // Start the process QProcess startZLeafProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - startZLeafProcess.setProcessEnvironment( env ); - startZLeafProcess.startDetached( settings->sshCmd, arguments ); + startZLeafProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + startZLeafProcess.startDetached(settings->sshCmd, arguments); // Output message via the debug messages tab - qDebug() << settings->sshCmd << arguments.join( " " ); + qDebug() << settings->sshCmd << arguments.join(" "); } } -void lc::Client::StartClientBrowser( const QString * const argURL, const bool * const argFullscreen ) { +void lc::Client::StartClientBrowser(const QString *const argURL, + const bool *const argFullscreen) +{ //Declarations QStringList arguments; // Build arguments list for SSH command arguments << "-i" << settings->pkeyPathUser - << QString{ settings->userNameOnClients + "@" + ip } + << QString{settings->userNameOnClients + "@" + ip} << "DISPLAY=:0.0" << settings->clientBrowserCmd << *argURL; // Add fullscreen toggle if checked - if (*argFullscreen == true){ + if (*argFullscreen == true) { arguments << "& sleep 3 && DISPLAY=:0.0 xdotool key --clearmodifiers F11"; } // Start the process QProcess startClientBrowserProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - startClientBrowserProcess.setProcessEnvironment( env ); - startClientBrowserProcess.startDetached( settings->sshCmd, arguments ); + startClientBrowserProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + startClientBrowserProcess.startDetached(settings->sshCmd, arguments); // Output message via the debug messages tab - qDebug() << settings->sshCmd << arguments.join( " " ); + qDebug() << settings->sshCmd << arguments.join(" "); } -void lc::Client::StopClientBrowser() { +void lc::Client::StopClientBrowser() +{ //Declarations - QStringList arguments; - - //Build arguments list - arguments << "-i" << settings->pkeyPathUser - << QString{ settings->userNameOnClients + "@" + ip } - << "killall" - << settings->clientBrowserCmd - << "& sleep 1 && rm -R /home/ewfuser/.mozilla/firefox/*"; + QStringList arguments{"-i", settings->pkeyPathUser, + QString{settings->userNameOnClients + "@" + ip}, + "killall", settings->clientBrowserCmd, + "& sleep 1 && rm -R /home/ewfuser/.mozilla/firefox/*"}; // Start the process QProcess startClientBrowserProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - startClientBrowserProcess.setProcessEnvironment( env ); - startClientBrowserProcess.startDetached( settings->sshCmd, arguments ); + startClientBrowserProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + startClientBrowserProcess.startDetached(settings->sshCmd, arguments); // Output message via the debug messages tab - qDebug() << settings->sshCmd << arguments.join( " " ); + qDebug() << settings->sshCmd << arguments.join(" "); } diff --git a/src/Lib/client.h b/src/Lib/client.h old mode 100755 new mode 100644 index 2b75897..d4b0278 --- a/src/Lib/client.h +++ b/src/Lib/client.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -20,29 +20,27 @@ #ifndef CLIENT_H #define CLIENT_H -#include -#include -#include -#include -#include +#include "global.h" + #include -#include -#include "global.h" -#include "clientpinger.h" +class QTimer; namespace lc { +class ClientPinger; + //! Class which represents the clients in the lab /*! This class contains elements and functions needed to represent all functions of a client. */ -class Client : public QObject { +class Client : public QObject +{ Q_OBJECT public slots: //! Sets the STATE of the client to 'ZLEAF_RUNNING' - void SetStateToZLEAF_RUNNING( QString argClientIP ); + void SetStateToZLEAF_RUNNING(const QString &argClientIP); public: const QString ip; @@ -59,18 +57,20 @@ public: * \param argXPosition The client's x coordinate in the lab's grid * \param argYPosition The client's y coordinate in the lab's grid */ - Client( const QString &argIP, const QString &argMAC, const QString &argName, - unsigned short int argXPosition, unsigned short int argYPosition, - const QString &argPingCmd ); + Client(const QString &argIP, const QString &argMAC, const QString &argName, + const unsigned short int argXPosition, + const unsigned short int argYPosition, + const QString &argPingCmd); //! Client's destructor - ~Client(); + ~Client() override; //! Beams the chosen file to the client's 'media4ztree' directory /*! @param argFileToBeam The file which shall be beamed to the client's 'media4ztree' directory @param argPublickeyPathUser The path to the publickey for user login on the clients @param argUserNameOnClients The name of the user on the clients */ - void BeamFile( const QString &argFileToBeam, const QString * const argPublickeyPathUser, const QString * const argUserNameOnClients ); + void BeamFile(const QString &argFileToBeam, const QString *const argPublickeyPathUser, + const QString *const argUserNameOnClients); /*! * \brief Boots the client */ @@ -83,8 +83,14 @@ public: /*! @return The current state of the client */ - state_t GetClientState() const { return state; } - int GetSessionPort() const { return sessionPort; } + state_t GetClientState() const + { + return state; + } + int GetSessionPort() const + { + return sessionPort; + } /*! * \brief Kills all processes 'zleaf.exe' on the client */ @@ -93,15 +99,21 @@ public: /*! @param argUserToBeUsed The name of the user on the clients */ - void OpenFilesystem( const QString * const argUserToBeUsed ); + void OpenFilesystem(const QString *const argUserToBeUsed); /*! * \brief Opens a terminal for the client * \param argCommand A command which shall be executed in the terminal window (Pass an empty QString if not wanted) * \param argOpenAsRoot Run the terminal session as root (true) or as normal user (false) */ - void OpenTerminal( const QString &argCommand, const bool &argOpenAsRoot ); - void SetSessionPort( int argSP ) { sessionPort = argSP; } - void SetzLeafVersion( const QString &argzLeafV ) { zLeafVersion = argzLeafV; } + void OpenTerminal(const QString &argCommand, const bool argOpenAsRoot); + void SetSessionPort(const int argSP) + { + sessionPort = argSP; + } + void SetzLeafVersion(const QString &argzLeafV) + { + zLeafVersion = argzLeafV; + } //! Shows the desktop of the given client void ShowDesktopViewOnly(); void ShowDesktopFullControl(); @@ -114,13 +126,13 @@ public: * \brief Starts a zLeaf instance on the client * @param argFakeName The name the zLeaf instance shall have (if not the default, which is the hostname of the client) */ - void StartZLeaf(const QString *argFakeName = nullptr, QString cmd = "" ); + void StartZLeaf(const QString *argFakeName = nullptr, QString cmd = ""); /*! * \brief Opens a browser window on the client * @param argURL URL to open in clients browser */ - void StartClientBrowser( const QString *argURL = nullptr, const bool *argFullscreen = nullptr ); + void StartClientBrowser(const QString *argURL = nullptr, const bool *argFullscreen = nullptr); /*! * \brief Closes all browser instances @@ -128,24 +140,28 @@ public: void StopClientBrowser(); private: - const QString &GetzLeafVersion() const { return zLeafVersion; } + const QString &GetzLeafVersion() const + { + return zLeafVersion; + } unsigned short int protectedCycles; ClientPinger *pinger = nullptr; QThread pingerThread; state_t state = state_t::UNINITIALIZED; - QTimer *pingTimer = nullptr; //! QTimer used to trigger pings by pinger's ClientPinger instance + //! QTimer used to trigger pings by pinger's ClientPinger instance + QTimer *pingTimer = nullptr; int sessionPort = 0; QString zLeafVersion; private slots: - void GotStatusChanged( state_t argState ); + void GotStatusChanged(const state_t argState); void RequestAPing(); signals: void PingWanted(); }; -} +} // namespace lc #endif // CLIENT_H diff --git a/src/manualprintingsetup.cpp b/src/manualprintingsetup.cpp index 5b67514..30ed20c 100644 --- a/src/manualprintingsetup.cpp +++ b/src/manualprintingsetup.cpp @@ -17,11 +17,19 @@ * along with Labcontrol. If not, see . */ +/* #include "manualprintingsetup.h" +#include "ui_manualprintingsetup.h" +#include "Lib/settings.h" + +#include + */ + #include "manualprintingsetup.h" #include "ui_manualprintingsetup.h" #include "Lib/settings.h" #include +#include #include diff --git a/src/manualprintingsetup.h b/src/manualprintingsetup.h index bcb7529..3561983 100644 --- a/src/manualprintingsetup.h +++ b/src/manualprintingsetup.h @@ -45,7 +45,7 @@ signals: private: QString dateString; - Ui::ManualPrintingSetup *ui = nullptr; + Ui::ManualPrintingSetup *const ui = nullptr; QString workPath; private slots: From d839f7f227f4aa15c9b6d81574567bf6c3ea7625 Mon Sep 17 00:00:00 2001 From: markuspg Date: Mon, 12 Mar 2018 22:37:07 +0100 Subject: [PATCH 12/30] Reformat ClientHelpNotificationServer --- src/Lib/clienthelpnotificationserver.cpp | 106 +++++++++++++---------- src/Lib/clienthelpnotificationserver.h | 22 ++--- 2 files changed, 70 insertions(+), 58 deletions(-) mode change 100755 => 100644 src/Lib/clienthelpnotificationserver.cpp mode change 100755 => 100644 src/Lib/clienthelpnotificationserver.h diff --git a/src/Lib/clienthelpnotificationserver.cpp b/src/Lib/clienthelpnotificationserver.cpp old mode 100755 new mode 100644 index 40938c0..4b4f8b3 --- a/src/Lib/clienthelpnotificationserver.cpp +++ b/src/Lib/clienthelpnotificationserver.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -17,98 +17,114 @@ * along with Labcontrol. If not, see . */ -#include - #include "clienthelpnotificationserver.h" #include "settings.h" -extern std::unique_ptr< lc::Settings > settings; +#include +#include +#include +#include +#include + +#include -lc::ClientHelpNotificationServer::ClientHelpNotificationServer( QObject *argParent ) : - QObject{ argParent }, - hostAddress{ settings->serverIP } +extern std::unique_ptr settings; + +lc::ClientHelpNotificationServer::ClientHelpNotificationServer(QObject *argParent) : + QObject{argParent}, + hostAddress{settings->serverIP} { QNetworkConfigurationManager manager; - if ( manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired ) { + if (manager.capabilities() + & QNetworkConfigurationManager::NetworkSessionRequired) { // Get saved network configuration - QSettings settings{ QSettings::UserScope, QLatin1String{ "QtProject" } }; - settings.beginGroup( QLatin1String{ "QtNetwork" } ); - const QString id = settings.value( QLatin1String{ "DefaultNetworkConfiguration" } ).toString(); + QSettings settings{QSettings::UserScope, QLatin1String{"QtProject"}}; + settings.beginGroup(QLatin1String{"QtNetwork"}); + const QString id{settings.value(QLatin1String{"DefaultNetworkConfiguration"}).toString()}; settings.endGroup(); // If the saved network configuration is not currently discovered use the system default - QNetworkConfiguration config = manager.configurationFromIdentifier( id ); - if ( ( config.state() & QNetworkConfiguration::Discovered ) != QNetworkConfiguration::Discovered ) { + QNetworkConfiguration config{manager.configurationFromIdentifier(id)}; + if ((config.state() & QNetworkConfiguration::Discovered) + != QNetworkConfiguration::Discovered) { config = manager.defaultConfiguration(); } - networkSession = new QNetworkSession{ config, this }; - connect( networkSession, &QNetworkSession::opened, - this, &ClientHelpNotificationServer::OpenSession ); + networkSession = new QNetworkSession{config, this}; + connect(networkSession, &QNetworkSession::opened, + this, &ClientHelpNotificationServer::OpenSession); networkSession->open(); } else { OpenSession(); } - connect( helpMessageServer, &QTcpServer::newConnection, - this, &ClientHelpNotificationServer::SendReply ); + connect(helpMessageServer, &QTcpServer::newConnection, + this, &ClientHelpNotificationServer::SendReply); } -void lc::ClientHelpNotificationServer::OpenSession() { +void lc::ClientHelpNotificationServer::OpenSession() +{ // Save the used configuration - if ( networkSession ) { - QNetworkConfiguration config = networkSession->configuration(); + if (networkSession) { + QNetworkConfiguration config{networkSession->configuration()}; QString id; - if ( config.type() == QNetworkConfiguration::UserChoice ) { - id = networkSession->sessionProperty( QLatin1String{ "UserChoiceConfiguration" } ).toString(); + if (config.type() == QNetworkConfiguration::UserChoice) { + id = networkSession->sessionProperty(QLatin1String{"UserChoiceConfiguration"}).toString(); } else { id = config.identifier(); } - QSettings settings( QSettings::UserScope, QLatin1String{ "QtProject" } ); - settings.beginGroup( QLatin1String{ "QtNetwork" } ); - settings.setValue( QLatin1String{ "DefaultNetworkConfiguration" }, id ); + QSettings settings{QSettings::UserScope, QLatin1String{"QtProject"}}; + settings.beginGroup(QLatin1String{"QtNetwork"}); + settings.setValue(QLatin1String{"DefaultNetworkConfiguration"}, id); settings.endGroup(); } - helpMessageServer = new QTcpServer{ this }; + helpMessageServer = new QTcpServer{this}; if ( !helpMessageServer->listen( hostAddress, settings->clientHelpNotificationServerPort ) ) { QMessageBox messageBox{ QMessageBox::Critical, tr( "Unable to start the client help notification server" ), - tr( "Unable to start the client help notification server.\nThe following error occurred:\n\n%1." ).arg( helpMessageServer->errorString() ), QMessageBox::Ok }; + tr( "Unable to start the client help notification server.\nThe following error occurred:\n\n%1." ).arg( helpMessageServer->errorString() ), QMessageBox::Ok }; messageBox.exec(); return; } } -void lc::ClientHelpNotificationServer::SendReply() { +void lc::ClientHelpNotificationServer::SendReply() +{ QByteArray block; - QDataStream out{ &block, QIODevice::WriteOnly }; - out.setVersion( QDataStream::Qt_5_2 ); - out << ( quint16 )0; - out << QString{ "Help demand retrieved." }; - out.device()->seek( 0 ); - out << ( quint16 )( block.size() - sizeof( quint16 ) ); + QDataStream out{&block, QIODevice::WriteOnly}; + out.setVersion(QDataStream::Qt_5_2); + out << static_cast(0); + out << QString{"Help demand retrieved."}; + out.device()->seek(0); + out << static_cast(block.size() - sizeof(quint16)); - QTcpSocket *clientConnection = helpMessageServer->nextPendingConnection(); + auto clientConnection = helpMessageServer->nextPendingConnection(); QString peerAddress = clientConnection->peerAddress().toString(); QString peerName; bool unknownClient = false; - if ( settings->clIPsToClMap.contains( peerAddress ) ) { - peerName = settings->clIPsToClMap[ peerAddress ]->name; + if (settings->clIPsToClMap.contains(peerAddress)) { + peerName = settings->clIPsToClMap[peerAddress]->name; } else { unknownClient = true; } - connect( clientConnection, &QTcpSocket::disconnected, clientConnection, &QTcpSocket::deleteLater ); - clientConnection->write( block ); + connect(clientConnection, &QTcpSocket::disconnected, + clientConnection, &QTcpSocket::deleteLater); + clientConnection->write(block); clientConnection->disconnectFromHost(); - if ( unknownClient ) { - QMessageBox requestReceivedBox{ QMessageBox::Information, tr( "Unknown client asked for help."), - tr( "An unknown client with IP '%1' asked for help.").arg( peerAddress ), QMessageBox::Ok }; + if (unknownClient) { + QMessageBox requestReceivedBox{QMessageBox::Information, + tr("Unknown client asked for help."), + tr("An unknown client with IP '%1' asked" + " for help.").arg(peerAddress), + QMessageBox::Ok}; requestReceivedBox.exec(); } else { - QMessageBox requestReceivedBox{ QMessageBox::Information, tr( "'%1' asked for help.").arg( peerName ), - tr( "'%1' asked for help.").arg( peerName ), QMessageBox::Ok }; + QMessageBox requestReceivedBox{QMessageBox::Information, + tr("'%1' asked for help.").arg( peerName ), + tr("'%1' asked for help.").arg(peerName), + QMessageBox::Ok}; requestReceivedBox.exec(); } } diff --git a/src/Lib/clienthelpnotificationserver.h b/src/Lib/clienthelpnotificationserver.h old mode 100755 new mode 100644 index d46e9d7..c1d704c --- a/src/Lib/clienthelpnotificationserver.h +++ b/src/Lib/clienthelpnotificationserver.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -20,23 +20,19 @@ #ifndef CLIENTHELPNOTIFICATIONSERVER_H #define CLIENTHELPNOTIFICATIONSERVER_H -#include "src/Lib/client.h" - -#include #include -#include -#include + +class QNetworkSession; +class QTcpServer; namespace lc { -class ClientHelpNotificationServer : public QObject { +class ClientHelpNotificationServer : public QObject +{ Q_OBJECT -public: - explicit ClientHelpNotificationServer( QObject *argParent = nullptr ); -signals: - -public slots: +public: + explicit ClientHelpNotificationServer(QObject *argParent = nullptr); private: QTcpServer *helpMessageServer = nullptr; @@ -48,6 +44,6 @@ private slots: void SendReply(); }; -} +} // namespace lc #endif // CLIENTHELPNOTIFICATIONSERVER_H From bca1a0d4230f28e254f7ce7bc4fb73c9acf33f0d Mon Sep 17 00:00:00 2001 From: markuspg Date: Tue, 13 Mar 2018 20:04:39 +0100 Subject: [PATCH 13/30] Reformat global.h --- src/Lib/global.h | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) mode change 100755 => 100644 src/Lib/global.h diff --git a/src/Lib/global.h b/src/Lib/global.h old mode 100755 new mode 100644 index b5334cd..7f834bd --- a/src/Lib/global.h +++ b/src/Lib/global.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -25,19 +25,20 @@ //! Opens a terminal for the client enum class state_t : unsigned short int { //! The client is booting but not yet responding - BOOTING, + BOOTING = 1 << 0, //! An error occurred determining the client's state - ERROR, + ERROR = 1 << 1, //! The client is not responding to pings - NOT_RESPONDING, + NOT_RESPONDING = 1 << 2, //! The client is shutting down but not yet stopped responding - SHUTTING_DOWN, + SHUTTING_DOWN = 1 << 3, //! The client's state is not yet defined (should only occur directly after client creation) - UNINITIALIZED, + UNINITIALIZED = 1 << 4, //! The client is responding to pings - RESPONDING, + RESPONDING = 1 << 5, //! The client is running a zLeaf - ZLEAF_RUNNING}; -Q_DECLARE_METATYPE( state_t ) + ZLEAF_RUNNING = 1 << 6, +}; +Q_DECLARE_METATYPE(state_t) #endif // GLOBAL_H From 2ec99238fea0b615c8e236cc18692c92062525ce Mon Sep 17 00:00:00 2001 From: markuspg Date: Tue, 13 Mar 2018 22:28:22 +0100 Subject: [PATCH 14/30] Reformat Lablib --- src/Lib/lablib.cpp | 187 +++++++++++++++++++++++---------------------- src/Lib/lablib.h | 49 +++++++----- 2 files changed, 127 insertions(+), 109 deletions(-) mode change 100755 => 100644 src/Lib/lablib.cpp mode change 100755 => 100644 src/Lib/lablib.h diff --git a/src/Lib/lablib.cpp b/src/Lib/lablib.cpp old mode 100755 new mode 100644 index 78fa67a..c4a2d54 --- a/src/Lib/lablib.cpp +++ b/src/Lib/lablib.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -24,39 +24,41 @@ #include "lablib.h" -lc::Lablib::Lablib( QObject *argParent ) : - QObject{ argParent }, - labSettings{ "Labcontrol", "Labcontrol", this }, - sessionsModel{ new SessionsModel{ this } } +lc::Lablib::Lablib(QObject *argParent) : + QObject{argParent}, + labSettings{"Labcontrol", "Labcontrol", this}, + sessionsModel{new SessionsModel{this}} { - for ( const auto &s : settings->GetClients() ) { - connect( this, &Lablib::ZLEAF_RUNNING, - s, &Client::SetStateToZLEAF_RUNNING ); + for (const auto &s : settings->GetClients()) { + connect(this, &Lablib::ZLEAF_RUNNING, + s, &Client::SetStateToZLEAF_RUNNING); } DetectInstalledZTreeVersionsAndLaTeXHeaders(); // Initialize all 'netstat' query mechanisms - if ( !settings->netstatCmd.isEmpty() ) { - netstatAgent = new NetstatAgent{ settings->netstatCmd }; - netstatAgent->moveToThread( &netstatThread ); - connect( &netstatThread, &QThread::finished, netstatAgent, &QObject::deleteLater ); - connect( netstatAgent, &NetstatAgent::QueryFinished, - this, &Lablib::GotNetstatQueryResult ); + if (!settings->netstatCmd.isEmpty()) { + netstatAgent = new NetstatAgent{settings->netstatCmd}; + netstatAgent->moveToThread(&netstatThread); + connect(&netstatThread, &QThread::finished, netstatAgent, &QObject::deleteLater); + connect(netstatAgent, &NetstatAgent::QueryFinished, + this, &Lablib::GotNetstatQueryResult); netstatThread.start(); - netstatTimer = new QTimer{ this }; - connect( netstatTimer, &QTimer::timeout, - netstatAgent, &NetstatAgent::QueryClientConnections ); - netstatTimer->start( 500 ); + netstatTimer = new QTimer{this}; + connect(netstatTimer, &QTimer::timeout, + netstatAgent, &NetstatAgent::QueryClientConnections); + netstatTimer->start(500); } // Initialize the server for client help requests retrieval - if ( settings->clientHelpNotificationServerPort && !settings->serverIP.isEmpty() ) { - clientHelpNotificationServer = new ClientHelpNotificationServer{ this }; + if (settings->clientHelpNotificationServerPort + && !settings->serverIP.isEmpty()) { + clientHelpNotificationServer = new ClientHelpNotificationServer{this}; } } -lc::Lablib::~Lablib () { - if ( netstatTimer ) { +lc::Lablib::~Lablib () +{ + if (netstatTimer) { netstatTimer->stop(); delete netstatTimer; } @@ -64,122 +66,127 @@ lc::Lablib::~Lablib () { netstatThread.wait(); } -bool lc::Lablib::CheckIfUserIsAdmin() const { - for ( const auto &s : settings->adminUsers ) { - if ( s == settings->localUserName ) { - qDebug() << "User" << settings->localUserName << "has administrative rights."; +bool lc::Lablib::CheckIfUserIsAdmin() const +{ + for (const auto &s : settings->adminUsers) { + if (s == settings->localUserName) { + qDebug() << "User" << settings->localUserName + << "has administrative rights."; return true; } } return false; } -void lc::Lablib::DetectInstalledZTreeVersionsAndLaTeXHeaders() { +void lc::Lablib::DetectInstalledZTreeVersionsAndLaTeXHeaders() +{ } -void lc::Lablib::GotNetstatQueryResult( QStringList *argActiveZLeafConnections ) { - if ( argActiveZLeafConnections != nullptr ) { - for ( auto s: *argActiveZLeafConnections ) { +void lc::Lablib::GotNetstatQueryResult(QStringList *argActiveZLeafConnections) +{ + if (argActiveZLeafConnections != nullptr) { + for (auto s : *argActiveZLeafConnections) { // Set all given clients' statuses to 'ZLEAF_RUNNING' emit ZLEAF_RUNNING( s ); } - } - else + } else qDebug() << "Netstat status query failed."; delete argActiveZLeafConnections; } -void lc::Lablib::ShowOrsee() { +void lc::Lablib::ShowOrsee() +{ QProcess showOrseeProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - showOrseeProcess.setProcessEnvironment( env ); - QString program{ settings->browserCmd }; - QStringList arguments{ QStringList{} << settings->orseeUrl }; - showOrseeProcess.startDetached( program, arguments ); + showOrseeProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + QString program{settings->browserCmd}; + const QStringList arguments{settings->orseeUrl}; + showOrseeProcess.startDetached(program, arguments); // Output message via the debug messages tab - qDebug() << program << arguments.join( " " ); + qDebug() << program << arguments.join(" "); } -void lc::Lablib::ShowPreprints() { +void lc::Lablib::ShowPreprints() +{ // Start the process QProcess showPreprintsProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - showPreprintsProcess.setProcessEnvironment( env ); - QString program{ settings->fileMngr }; - QStringList arguments{ QStringList{} << settings->lcDataDir + "/preprints" }; - showPreprintsProcess.startDetached( program, arguments ); + showPreprintsProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + const QString program{settings->fileMngr}; + const QStringList arguments{settings->lcDataDir + "/preprints"}; + showPreprintsProcess.startDetached(program, arguments); // Output message via the debug messages tab - qDebug() << program << arguments.join( " " ); + qDebug() << program << arguments.join(" "); } -void lc::Lablib::StartNewSession( QVector< Client* > argAssocCl, - QString argParticipNameReplacement, - bool argPrintLocalReceipts, QString argReceiptsHeader, - QString argzTreeDataTargetPath, quint16 argzTreePort, - QString argzTreeVersion ) { - if ( !QDir( argzTreeDataTargetPath ).exists() ) { - QMessageBox messageBox{ QMessageBox::Critical, tr( "Data target path does not exist" ), - tr( "Your chosen data target path does not exist." - " Do you want it to be created automatically?" ), - QMessageBox::Yes | QMessageBox::No }; +void lc::Lablib::StartNewSession(QVector argAssocCl, + QString argParticipNameReplacement, + bool argPrintLocalReceipts, QString argReceiptsHeader, + QString argzTreeDataTargetPath, quint16 argzTreePort, + QString argzTreeVersion) +{ + if (!QDir(argzTreeDataTargetPath).exists()) { + QMessageBox messageBox{QMessageBox::Critical, tr("Data target path does not exist"), + tr("Your chosen data target path does not exist." + " Do you want it to be created automatically?"), + QMessageBox::Yes | QMessageBox::No}; messageBox.exec(); - if ( messageBox.clickedButton() == messageBox.button( QMessageBox::No ) ) { - QMessageBox messageBox{ QMessageBox::Critical, tr( "Data target directory will not" - " be created" ), - tr( "Your chosen data target directory does not exist and" - " will not be created. Please choose another one." ), - QMessageBox::Ok }; + if (messageBox.clickedButton() == messageBox.button(QMessageBox::No)) { + QMessageBox messageBox{QMessageBox::Critical, + tr("Data target directory will not be created"), + tr("Your chosen data target directory does not exist and" + " will not be created. Please choose another one."), + QMessageBox::Ok}; messageBox.exec(); return; } else { - if ( !QDir().mkpath( argzTreeDataTargetPath ) ) { - QMessageBox messageBox{ QMessageBox::Critical, tr( "Data target directory could" - " not be created" ), - tr( "Your chosen data target directory does not exist" - " and could not be created. Please choose another" - " one." ), QMessageBox::Ok }; + if (!QDir().mkpath(argzTreeDataTargetPath)) { + QMessageBox messageBox{QMessageBox::Critical, + tr("Data target directory could not be created"), + tr("Your chosen data target directory does not exist" + " and could not be created. Please choose another" + " one."), QMessageBox::Ok}; messageBox.exec(); return; } } } try { - sessionsModel->push_back( new Session{ std::move( argAssocCl ), - argzTreeDataTargetPath, - argzTreePort, argzTreeVersion, - argPrintLocalReceipts, - argParticipNameReplacement, - argReceiptsHeader } ); - occupiedPorts.append( sessionsModel->back()->zTreePort ); - } - catch ( Session::lcDataTargetPathCreationFailed ) { - QMessageBox::information( nullptr, tr( "Chosen data target path could not be created" ), - tr( "The path specified by your chosen data target path '%1'" - " could not be created. Please check if it is a valid" - " location and you have all needed permissions." ) - .arg( argzTreeDataTargetPath ) ); + sessionsModel->push_back(new Session{std::move(argAssocCl), + argzTreeDataTargetPath, + argzTreePort, argzTreeVersion, + argPrintLocalReceipts, + argParticipNameReplacement, + argReceiptsHeader}); + occupiedPorts.append(sessionsModel->back()->zTreePort); + } catch (Session::lcDataTargetPathCreationFailed) { + QMessageBox::information(nullptr, tr("Chosen data target path could not be created"), + tr("The path specified by your chosen data target path '%1'" + " could not be created. Please check if it is a valid" + " location and you have all needed permissions.") + .arg(argzTreeDataTargetPath)); } } -void lc::Lablib::SetLocalZLeafDefaultName( const QString &argName ) { - settings->SetLocalzLeafName( argName ); - labSettings.setValue( "local_zLeaf_name", argName ); +void lc::Lablib::SetLocalZLeafDefaultName(const QString &argName) +{ + settings->SetLocalzLeafName(argName); + labSettings.setValue("local_zLeaf_name", argName); } //Returns the commandline that is issued on the client when zleaf is started -QStringList lc::Lablib::getzLeafArgs( int sessionPort, QString zleafVersion ){ +QStringList lc::Lablib::getzLeafArgs(int sessionPort, QString zleafVersion) +{ QStringList arguments; - if ( sessionPort == 7000 ) { + if (sessionPort == 7000) { arguments << "DISPLAY=:0.0" << settings->tasksetCmd << "0x00000001" << settings->wineCmd - << QString{ settings->zTreeInstDir + "/zTree_" + zleafVersion + "/zleaf.exe" } + << QString{settings->zTreeInstDir + "/zTree_" + zleafVersion + "/zleaf.exe"} << "/server" << settings->serverIP; } else { arguments << "DISPLAY=:0.0" << settings->tasksetCmd << "0x00000001" << settings->wineCmd - << QString{ settings->zTreeInstDir + "/zTree_" + zleafVersion + "/zleaf.exe" } + << QString{settings->zTreeInstDir + "/zTree_" + zleafVersion + "/zleaf.exe"} << "/server" << settings->serverIP << "/channel" - << QString::number( sessionPort- 7000 ); + << QString::number(sessionPort - 7000); } //Return the crafted QStringList diff --git a/src/Lib/lablib.h b/src/Lib/lablib.h old mode 100755 new mode 100644 index 68764aa..d7530bf --- a/src/Lib/lablib.h +++ b/src/Lib/lablib.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -45,7 +45,7 @@ #include "sessionsmodel.h" #include "settings.h" -extern std::unique_ptr< lc::Settings > settings; +extern std::unique_ptr settings; namespace lc { @@ -56,15 +56,16 @@ namespace lc { class Lablib : public QObject { Q_OBJECT + public: /*! * \brief Lablib's constructor * \param[in] argParent This 'lcLablib' instance's parent QObject */ - Lablib( QObject *argParent = nullptr ); + Lablib(QObject *argParent = nullptr); /** Lablib's destructor */ - ~Lablib(); + ~Lablib() override; /*! * \brief CheckIfUserIsAdmin checks if the account with the passed user name has administrative rights * \param argUserName The account name which shall checked for administrative rights @@ -75,40 +76,46 @@ public: * * @return A pointer to a QVector containing all occupied ports */ - const QVector< quint16 > &GetOccupiedPorts () const { return occupiedPorts; } + const QVector &GetOccupiedPorts () const + { + return occupiedPorts; + } /** Returns a pointer to the QAbstractTableModel storing the Session instances * * @return A pointer to the QAbstractTableModel storing the Session instances */ - SessionsModel *GetSessionsModel () const { return sessionsModel; } + SessionsModel *GetSessionsModel () const + { + return sessionsModel; + } //! Sets the default name of local zLeaf instances /** * @param argName The default name local zLeaf instances shall have */ - void SetLocalZLeafDefaultName( const QString &argName ); + void SetLocalZLeafDefaultName(const QString &argName); void ShowOrsee(); void ShowPreprints(); - void StartNewSession( QVector< Client* > argAssocCl, QString argParticipNameReplacement, - bool argPrintLocalReceipts, QString argReceiptsHeader, - QString argzTreeDataTargetPath, quint16 argzTreePort, - QString argzTreeVersion ); + void StartNewSession(QVector argAssocCl, QString argParticipNameReplacement, + bool argPrintLocalReceipts, QString argReceiptsHeader, + QString argzTreeDataTargetPath, quint16 argzTreePort, + QString argzTreeVersion); /*! * \brief Returns the commandline to issue on the client(s) in order to start zLeaf * @param sessionPort The port zLeaf shall connect to * @param zLeafVersion zLeaf Version to start */ - QStringList getzLeafArgs( int sessionPort, QString zleafVersion ); + QStringList getzLeafArgs(int sessionPort, QString zleafVersion); public slots: signals: - void ZLEAF_RUNNING( QString argClientIP ); + void ZLEAF_RUNNING(QString argClientIP); private slots: //! Gets the output from NetstatAgent - void GotNetstatQueryResult( QStringList *argActiveZLeafConnections ); + void GotNetstatQueryResult(QStringList *argActiveZLeafConnections); private: //! Detects installed zTree version and LaTeX headers @@ -117,15 +124,19 @@ private: */ void ReadSettings(); - ClientHelpNotificationServer *clientHelpNotificationServer = nullptr; //! A server to retrieve help requests from the clients + //! A server to retrieve help requests from the clients + ClientHelpNotificationServer *clientHelpNotificationServer = nullptr; QSettings labSettings; - NetstatAgent *netstatAgent = nullptr; //! Tries to detect active zLeaf connections from the clients + //! Tries to detect active zLeaf connections from the clients + NetstatAgent *netstatAgent = nullptr; QThread netstatThread; - QTimer *netstatTimer = nullptr; //! A timer for regular execution of the NetstatAgent instance's request mechanism + //! A timer for regular execution of the NetstatAgent instance's request mechanism + QTimer *netstatTimer = nullptr; QVector< quint16 > occupiedPorts; - SessionsModel *sessionsModel = nullptr; //! A derivation from QAbstractTableModel used to store the single Session instances + //! A derivation from QAbstractTableModel used to store the single Session instances + SessionsModel *sessionsModel = nullptr; }; -} +} // namespace lc #endif // LABLIB_H From f5f32c4bcf849e4210cce5bed120fc76c0933f61 Mon Sep 17 00:00:00 2001 From: markuspg Date: Tue, 13 Mar 2018 22:35:32 +0100 Subject: [PATCH 15/30] Reformat ReceiptsHandler --- src/Lib/receipts_handler.cpp | 238 +++++++++++++++++++---------------- src/Lib/receipts_handler.h | 64 ++++++---- 2 files changed, 168 insertions(+), 134 deletions(-) mode change 100755 => 100644 src/Lib/receipts_handler.cpp mode change 100755 => 100644 src/Lib/receipts_handler.h diff --git a/src/Lib/receipts_handler.cpp b/src/Lib/receipts_handler.cpp old mode 100755 new mode 100644 index c7f0f1b..69120fa --- a/src/Lib/receipts_handler.cpp +++ b/src/Lib/receipts_handler.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -24,57 +24,58 @@ #include "receipts_handler.h" #include "settings.h" -extern std::unique_ptr< lc::Settings > settings; - -lc::ReceiptsHandler::ReceiptsHandler( const QString &argZTreeDataTargetPath, - bool argPrintReceiptsForLocalClients, - const QString &argAnonymousReceiptsPlaceholder, - const QString &argLatexHeaderName, - QObject *argParent ) : - QObject{ argParent }, - anonymousReceiptsPlaceholder{ argAnonymousReceiptsPlaceholder }, - dateString{ QDateTime::currentDateTime().toString( "yyMMdd_hhmm" ) }, - expectedPaymentFileName{ dateString + ".pay" }, - expectedPaymentFilePath{ argZTreeDataTargetPath + "/" + dateString + ".pay" }, - latexHeaderName{ argLatexHeaderName }, - paymentFile{ expectedPaymentFilePath }, - printReceiptsForLocalClients{ argPrintReceiptsForLocalClients }, - timer{ new QTimer{ this } }, - zTreeDataTargetPath{ argZTreeDataTargetPath } +extern std::unique_ptr settings; + +lc::ReceiptsHandler::ReceiptsHandler(const QString &argZTreeDataTargetPath, + bool argPrintReceiptsForLocalClients, + const QString &argAnonymousReceiptsPlaceholder, + const QString &argLatexHeaderName, + QObject *argParent) : + QObject{argParent}, + anonymousReceiptsPlaceholder{argAnonymousReceiptsPlaceholder}, + dateString{QDateTime::currentDateTime().toString("yyMMdd_hhmm")}, + expectedPaymentFileName{dateString + ".pay"}, + expectedPaymentFilePath{argZTreeDataTargetPath + "/" + dateString + ".pay"}, + latexHeaderName{argLatexHeaderName}, + paymentFile{expectedPaymentFilePath}, + printReceiptsForLocalClients{argPrintReceiptsForLocalClients}, + timer{new QTimer{this}}, +zTreeDataTargetPath{argZTreeDataTargetPath} { qDebug() << "Expected payment file name is:" << expectedPaymentFilePath; // Create a QTimer regularly checking if the payment file was created and print it if so - connect( timer, &QTimer::timeout, - this, &ReceiptsHandler::PrintReceipts ); - timer->start( 2000 ); + connect(timer, &QTimer::timeout, + this, &ReceiptsHandler::PrintReceipts); + timer->start(2000); } -lc::ReceiptsHandler::ReceiptsHandler( const QString &argZTreeDataTargetPath, - bool argPrintReceiptsForLocalClients, - const QString &argAnonymousReceiptsPlaceholder, - const QString &argLatexHeaderName, - const QString &argDateString, QObject *argParent ) : - QObject{ argParent }, - anonymousReceiptsPlaceholder{ argAnonymousReceiptsPlaceholder }, - dateString{ argDateString }, - expectedPaymentFileName{ argDateString + ".pay" }, - expectedPaymentFilePath{ argZTreeDataTargetPath + "/" + argDateString + ".pay" }, - latexHeaderName{ argLatexHeaderName }, - paymentFile{ expectedPaymentFilePath }, - printReceiptsForLocalClients{ argPrintReceiptsForLocalClients }, - zTreeDataTargetPath{ argZTreeDataTargetPath } +lc::ReceiptsHandler::ReceiptsHandler(const QString &argZTreeDataTargetPath, + bool argPrintReceiptsForLocalClients, + const QString &argAnonymousReceiptsPlaceholder, + const QString &argLatexHeaderName, + const QString &argDateString, QObject *argParent) : + QObject{argParent}, + anonymousReceiptsPlaceholder{argAnonymousReceiptsPlaceholder}, + dateString{argDateString}, + expectedPaymentFileName{argDateString + ".pay"}, + expectedPaymentFilePath{argZTreeDataTargetPath + "/" + argDateString + ".pay"}, + latexHeaderName{argLatexHeaderName}, + paymentFile{expectedPaymentFilePath}, + printReceiptsForLocalClients{argPrintReceiptsForLocalClients}, + zTreeDataTargetPath{argZTreeDataTargetPath} { qDebug() << "Expected payment file name is:" << expectedPaymentFilePath; PrintReceipts(); } -void lc::ReceiptsHandler::PrintReceipts() { +void lc::ReceiptsHandler::PrintReceipts() +{ // If the payment file exists, print it - if ( paymentFile.exists() ) { + if (paymentFile.exists()) { qDebug() << "The payment file has been created and will be printed"; - if ( timer ) { + if (timer) { timer->stop(); } @@ -82,28 +83,30 @@ void lc::ReceiptsHandler::PrintReceipts() { } } -void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() { +void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() +{ // Get the data needed for receipts creation from the payment file QVector *rawParticipantsData = nullptr; rawParticipantsData = GetParticipantsDataFromPaymentFile(); - for ( int i = 0; i < rawParticipantsData->size(); i++ ) { - qDebug() << "Payment file line" << QString::number( i ) << ":\t" << rawParticipantsData->at( i ); + for (int i = 0; i < rawParticipantsData->size(); i++) { + qDebug() << "Payment file line" << QString::number(i) + << ":\t" << rawParticipantsData->at(i); } // Extract the data of the participant's whose receipts shall be printed /* The tab separated fields in the payment file are: * SUBJECT COMPUTER INTERESTED NAME PROFIT SIGNATURE */ - QVector *participants = new QVector; + QVector *participants = new QVector; double overall_payoff = 0.0; - for ( QVector::iterator it = rawParticipantsData->begin(); it != rawParticipantsData->end() - 1; ++it ) { + for (QVector::iterator it = rawParticipantsData->begin(); + it != rawParticipantsData->end() - 1; ++it) { // Split the lines containing the participants' data into their inidivual parts QStringList temp_participant_data = it->split('\t', QString::KeepEmptyParts); - qDebug() << temp_participant_data.join( " - " ); - if ( !printReceiptsForLocalClients && temp_participant_data.at( 3 ).contains( "local" ) ) { - qDebug() << "Receipt for local client" << temp_participant_data.at( 1 ) << "will not be printed."; - } - else { + qDebug() << temp_participant_data.join(" - "); + if (!printReceiptsForLocalClients && temp_participant_data.at(3).contains("local")) { + qDebug() << "Receipt for local client" << temp_participant_data.at(1) << "will not be printed."; + } else { // Create a new struct instance for participant data and fill it paymentEntry_t *participant = new paymentEntry_t; participant->computer = temp_participant_data.at(1); @@ -117,14 +120,14 @@ void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() { rawParticipantsData = nullptr; // Make receipts overview anonymous if requested (at this stage just names are removed, so that the overview still containts the client names - if ( !anonymousReceiptsPlaceholder.isEmpty() ) { - MakeReceiptsAnonymous( participants, false ); + if (!anonymousReceiptsPlaceholder.isEmpty()) { + MakeReceiptsAnonymous(participants, false); } // Load the LaTeX header QString *latexText = LoadLatexHeader(); - if ( latexText == nullptr ) { - for ( auto s : *participants ) { + if (latexText == nullptr) { + for (auto s : *participants) { delete s; } delete participants; @@ -133,12 +136,13 @@ void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() { } // Write the comprehension table - latexText->append( "\n\\COMPREHENSION{\n" ); + latexText->append("\n\\COMPREHENSION{\n"); unsigned short int zeile = 0; - for ( auto s : *participants ) { - latexText->append( expectedPaymentFileName + " & " + s->computer + " & " + s->name + " & " + QString::number( s->payoff, 'f', 2 ) + " \\EUR\\\\\n" ); - if ( zeile % 2 == 0 ) { - latexText->append( "\\rowcolor[gray]{0.9}\n" ); + for (auto s : *participants) { + latexText->append(expectedPaymentFileName + " & " + s->computer + " & " + s->name + " & " + + QString::number(s->payoff, 'f', 2) + " \\EUR\\\\\n"); + if (zeile % 2 == 0) { + latexText->append("\\rowcolor[gray]{0.9}\n"); } ++zeile; } @@ -146,20 +150,21 @@ void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() { // MISSING: Appending show up entries to the overview // Make also the clients on the receipts anonymous. This is done as second step, so that the beforehand created overview still contains the clients - if ( !anonymousReceiptsPlaceholder.isEmpty() ) { - MakeReceiptsAnonymous( participants, true ); + if (!anonymousReceiptsPlaceholder.isEmpty()) { + MakeReceiptsAnonymous(participants, true); } // Add the LaTeX middle sequence - latexText->append( "}{" + QString::number( overall_payoff, 'f', 2 ) + "}\n\n%%Einzelquittungen\n" ); + latexText->append("}{" + QString::number(overall_payoff, 'f', 2) + "}\n\n%%Einzelquittungen\n"); // Write the single receipts - for ( auto s : *participants ) { - if ( s->payoff >= 0 ) { - latexText->append( "\\GAINRECEIPT{" + expectedPaymentFileName + "}{" + s->computer + "}{" + s->name + "}{" + QString::number( s->payoff, 'f', 2 ) + "}\n" ); - } - else { - latexText->append( "\\LOSSRECEIPT{" + expectedPaymentFileName + "}{" + s->computer + "}{" + s->name + "}{" + QString::number( s->payoff, 'f', 2 ) + "}\n" ); + for (auto s : *participants) { + if (s->payoff >= 0) { + latexText->append("\\GAINRECEIPT{" + expectedPaymentFileName + "}{" + s->computer + "}{" + s->name + + "}{" + QString::number(s->payoff, 'f', 2) + "}\n"); + } else { + latexText->append("\\LOSSRECEIPT{" + expectedPaymentFileName + "}{" + s->computer + "}{" + s->name + + "}{" + QString::number(s->payoff, 'f', 2) + "}\n"); } delete s; } @@ -172,44 +177,47 @@ void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() { qDebug() << *latexText; // Create the tex file - QFile *texFile = new QFile{ zTreeDataTargetPath + "/" + dateString + ".tex" }; + QFile *texFile = new QFile{zTreeDataTargetPath + "/" + dateString + ".tex"}; qDebug() << "Tex file" << texFile->fileName() << "will be created for receipts printing."; // Clean up any already existing files - if ( texFile->exists() ) { - if ( !texFile->remove() ) { - QMessageBox messageBox( QMessageBox::Critical, "Tex file removing failed", "There already exists a tex file at '" + texFile->fileName() - + "' which cannot be removed. The creation of the receipts printout may fail.", QMessageBox::Ok ); + if (texFile->exists()) { + if (!texFile->remove()) { + QMessageBox messageBox(QMessageBox::Critical, "Tex file removing failed", + "There already exists a tex file at '" + texFile->fileName() + + "' which cannot be removed. The creation of the receipts printout may fail.", QMessageBox::Ok); messageBox.exec(); } } // Create a new file - if ( !texFile->open( QIODevice::Text | QIODevice::WriteOnly ) ) { - QMessageBox messageBox( QMessageBox::Critical, "Tex file creation failed", "The creation of the tex file for receipts printing at '" + texFile->fileName() - + "' failed. Receipts printing will not work.", QMessageBox::Ok ); + if (!texFile->open(QIODevice::Text | QIODevice::WriteOnly)) { + QMessageBox messageBox( QMessageBox::Critical, "Tex file creation failed", + "The creation of the tex file for receipts printing at '" + texFile->fileName() + + "' failed. Receipts printing will not work.", QMessageBox::Ok); messageBox.exec(); return; } // Open a QTextStream to write to the file - QTextStream out( texFile ); + QTextStream out(texFile); out << *latexText; delete latexText; latexText = nullptr; - receiptsPrinter = new ReceiptsPrinter{ dateString, zTreeDataTargetPath, this }; + receiptsPrinter = new ReceiptsPrinter{dateString, zTreeDataTargetPath, this}; receiptsPrinter->start(); - connect( receiptsPrinter, &ReceiptsPrinter::PrintingFinished, - this, &ReceiptsHandler::DeleteReceiptsPrinterInstance ); - connect( receiptsPrinter, &ReceiptsPrinter::ErrorOccurred, - this, &ReceiptsHandler::DisplayMessageBox ); + connect(receiptsPrinter, &ReceiptsPrinter::PrintingFinished, + this, &ReceiptsHandler::DeleteReceiptsPrinterInstance); + connect(receiptsPrinter, &ReceiptsPrinter::ErrorOccurred, + this, &ReceiptsHandler::DisplayMessageBox); // Clean up texFile->close(); delete texFile; } -void lc::ReceiptsHandler::DeleteReceiptsPrinterInstance() { +void lc::ReceiptsHandler::DeleteReceiptsPrinterInstance() +{ receiptsPrinter->quit(); receiptsPrinter->wait(); receiptsPrinter->deleteLater(); @@ -219,33 +227,37 @@ void lc::ReceiptsHandler::DeleteReceiptsPrinterInstance() { emit PrintingFinished(); } -void lc::ReceiptsHandler::DisplayMessageBox( QString *argErrorMessage, QString *argHeading ) { - QMessageBox messageBox( QMessageBox::Warning, *argHeading, *argErrorMessage, QMessageBox::Ok ); +void lc::ReceiptsHandler::DisplayMessageBox(QString *argErrorMessage, + QString *argHeading) +{ + QMessageBox messageBox(QMessageBox::Warning, *argHeading, + *argErrorMessage, QMessageBox::Ok); delete argHeading; delete argErrorMessage; messageBox.exec(); } -QVector *lc::ReceiptsHandler::GetParticipantsDataFromPaymentFile() { +QVector *lc::ReceiptsHandler::GetParticipantsDataFromPaymentFile() +{ // Create the vector to store the single lines of the file QVector *participantsData = new QVector; // Open the payment file for reading and create a QTextStream - paymentFile.open( QIODevice::ReadOnly | QIODevice::Text ); - QTextStream in( &paymentFile ); - in.setCodec( "ISO 8859-1" ); + paymentFile.open(QIODevice::ReadOnly | QIODevice::Text); + QTextStream in(&paymentFile); + in.setCodec("ISO 8859-1"); // Read the file line by line and store them in the vector - while ( true ) { + while (true) { QString line = in.readLine(); - if ( line.isNull() ) { + if (line.isNull()) { break; } - participantsData->append( line ); + participantsData->append(line); } // Remove the first line, since it is not needed - participantsData->erase( participantsData->begin() ); + participantsData->erase(participantsData->begin()); // Close the file afterwards paymentFile.close(); @@ -253,38 +265,44 @@ QVector *lc::ReceiptsHandler::GetParticipantsDataFromPaymentFile() { return participantsData; } -QString *lc::ReceiptsHandler::LoadLatexHeader() { +QString *lc::ReceiptsHandler::LoadLatexHeader() +{ // Prepare all facilities to read the latex header file - QFile latexHeaderFile( settings->lcDataDir + "/" + latexHeaderName + "_header.tex" ); - if ( !latexHeaderFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) { - QMessageBox messageBox{ QMessageBox::Critical, tr( "LaTeX header could not be loaded" ), - tr( "The LaTeX header at '%1/%2_header.tex' could not be loaded. Receipts printing will not work." ) - .arg( settings->lcDataDir ).arg( latexHeaderName ), QMessageBox::Ok }; + QFile latexHeaderFile(settings->lcDataDir + "/" + latexHeaderName + "_header.tex"); + if (!latexHeaderFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + QMessageBox messageBox{QMessageBox::Critical, + tr("LaTeX header could not be loaded"), + tr("The LaTeX header at '%1/%2_header.tex' could" + " not be loaded. Receipts printing will not work.") + .arg(settings->lcDataDir).arg(latexHeaderName), QMessageBox::Ok}; messageBox.exec(); return nullptr; } - QTextStream in( &latexHeaderFile ); + QTextStream in(&latexHeaderFile); QString *header = nullptr; - header = new QString( in.readAll() ); + header = new QString(in.readAll()); latexHeaderFile.close(); return header; } -void lc::ReceiptsHandler::MakeReceiptsAnonymous( QVector *argDataVector, bool argAlsoAnonymizeClients ) { - if ( !argAlsoAnonymizeClients ) { +void lc::ReceiptsHandler::MakeReceiptsAnonymous(QVector *argDataVector, + bool argAlsoAnonymizeClients) +{ + if (!argAlsoAnonymizeClients) { qDebug() << "Names are made anonymous"; - for ( QVector< paymentEntry_t* >::iterator it = argDataVector->begin(); it != argDataVector->end(); ++it ) { - ( *it )->name = anonymousReceiptsPlaceholder; + for (QVector::iterator it = argDataVector->begin(); it != argDataVector->end(); + ++it) { + (*it)->name = anonymousReceiptsPlaceholder; + } + } else { + qDebug() << "Clients and names are made anonymous"; + for (QVector::iterator it = argDataVector->begin(); it != argDataVector->end(); + ++it) { + (*it)->name = anonymousReceiptsPlaceholder; + (*it)->computer = "\\hspace{1cm}"; } - } - else { - qDebug() << "Clients and names are made anonymous"; - for ( QVector< paymentEntry_t* >::iterator it = argDataVector->begin(); it != argDataVector->end(); ++it ) { - ( *it )->name = anonymousReceiptsPlaceholder; - ( *it )->computer = "\\hspace{1cm}"; - } } } diff --git a/src/Lib/receipts_handler.h b/src/Lib/receipts_handler.h old mode 100755 new mode 100644 index 68b0841..8260103 --- a/src/Lib/receipts_handler.h +++ b/src/Lib/receipts_handler.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -36,25 +36,30 @@ namespace lc { /*! This class represents a single payoff entry which will be used in the receipts creation process. Multiple instances of this will be used to represent the individual participants' outcomes. */ -struct paymentEntry_t {QString computer; QString name; double payoff;}; +struct paymentEntry_t { + QString computer; + QString name; + double payoff; +}; //! A class to handle receipts printing. /*! This class is element of every session and is used to handle the receipts printing. */ -class ReceiptsHandler : public QObject { +class ReceiptsHandler : public QObject +{ Q_OBJECT public: - explicit ReceiptsHandler( const QString &argZTreeDataTargetPath, - bool argPrintReceiptsForLocalClients, - const QString &argAnonymousReceiptsPlaceholder, - const QString &argLatexHeaderName, QObject *argParent = nullptr ); - explicit ReceiptsHandler( const QString &argZTreeDataTargetPath, - bool argPrintReceiptsForLocalClients, - const QString &argAnonymousReceiptsPlaceholder, - const QString &argLatexHeaderName, - const QString &argDateString, QObject *argParent = nullptr ); + explicit ReceiptsHandler(const QString &argZTreeDataTargetPath, + bool argPrintReceiptsForLocalClients, + const QString &argAnonymousReceiptsPlaceholder, + const QString &argLatexHeaderName, QObject *argParent = nullptr); + explicit ReceiptsHandler(const QString &argZTreeDataTargetPath, + bool argPrintReceiptsForLocalClients, + const QString &argAnonymousReceiptsPlaceholder, + const QString &argLatexHeaderName, + const QString &argDateString, QObject *argParent = nullptr); signals: void PrintingFinished(); @@ -74,20 +79,31 @@ private: void CreateReceiptsFromPaymentFile(); QVector *GetParticipantsDataFromPaymentFile(); QString *LoadLatexHeader(); - void MakeReceiptsAnonymous( QVector *argDataVector, bool argAlsoAnonymizeClients ); + void MakeReceiptsAnonymous(QVector *argDataVector, + bool argAlsoAnonymizeClients); - const QString anonymousReceiptsPlaceholder; //!< Placeholder which shall be inserted for participant names if anonymous printing is desired (QString != "") - const QString dateString; //!< The expected date string of the payment file in form 'yyMMdd_hhmm' - const QString expectedPaymentFileName; //!< The name of the expected payment file - const QString expectedPaymentFilePath; //!< The path of the expected payment file - const QString latexHeaderName; //!< The name of the chosen LaTeX header template - QFile paymentFile; //!< A pointer to the '*.pay' file being watched for existance and starting the printing process - const bool printReceiptsForLocalClients; //!< Stores if receipts shall be printed for local clients - ReceiptsPrinter *receiptsPrinter = nullptr; //!< Creates new thread for receipts printing - QTimer *timer = nullptr; //!< Used for regular checking if the payment file was created - const QString zTreeDataTargetPath; //!< A reference to the data target path stored in the session class instance + //! Placeholder which shall be inserted for participant names if anonymous printing is desired (QString != "") + const QString anonymousReceiptsPlaceholder; + //! The expected date string of the payment file in form 'yyMMdd_hhmm' + const QString dateString; + //! The name of the expected payment file + const QString expectedPaymentFileName; + //! The path of the expected payment file + const QString expectedPaymentFilePath; + //! The name of the chosen LaTeX header template + const QString latexHeaderName; + //! A pointer to the '*.pay' file being watched for existance and starting the printing process + QFile paymentFile; + //! Stores if receipts shall be printed for local clients + const bool printReceiptsForLocalClients; + //! Creates new thread for receipts printing + ReceiptsPrinter *receiptsPrinter = nullptr; + //! Used for regular checking if the payment file was created + QTimer *timer = nullptr; + //! A reference to the data target path stored in the session class instance + const QString zTreeDataTargetPath; }; -} +} // namespace lc #endif // RECEIPTS_HANDLER_H From f345d88315afb9877ff98e789ae1b26b1daeac3e Mon Sep 17 00:00:00 2001 From: markuspg Date: Tue, 13 Mar 2018 22:39:51 +0100 Subject: [PATCH 16/30] Reformat ReceiptsPrinter --- src/Lib/receiptsprinter.cpp | 30 +++++----- src/Lib/receiptsprinter.h | 111 ++++++++++++++++++++---------------- 2 files changed, 76 insertions(+), 65 deletions(-) mode change 100755 => 100644 src/Lib/receiptsprinter.cpp mode change 100755 => 100644 src/Lib/receiptsprinter.h diff --git a/src/Lib/receiptsprinter.cpp b/src/Lib/receiptsprinter.cpp old mode 100755 new mode 100644 index 4cdfa2d..0a1f493 --- a/src/Lib/receiptsprinter.cpp +++ b/src/Lib/receiptsprinter.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -22,20 +22,20 @@ #include "receiptsprinter.h" #include "settings.h" -extern std::unique_ptr< lc::Settings > settings; +extern std::unique_ptr settings; -lc::ReceiptsPrinter::ReceiptsPrinter( const QString &argDateString, - const QString &argWorkpath, - QObject *argParent ) : - QThread{ argParent }, - dateString{ argDateString }, - dvipsCmd{ settings->dvipsCmd }, - latexCmd{ settings->latexCmd }, - lprCmd{ settings->lprCmd }, - postscriptViewer{ settings->postscriptViewer }, - ps2pdfCmd{ settings->ps2pdfCmd }, - rmCmd{ settings->rmCmd }, - vncViewer{ settings->vncViewer }, - workpath{ argWorkpath } +lc::ReceiptsPrinter::ReceiptsPrinter(const QString &argDateString, + const QString &argWorkpath, + QObject *argParent) : + QThread{argParent}, + dateString{argDateString}, + dvipsCmd{settings->dvipsCmd}, + latexCmd{settings->latexCmd}, + lprCmd{settings->lprCmd}, + postscriptViewer{ settings->postscriptViewer}, + ps2pdfCmd{settings->ps2pdfCmd}, + rmCmd{settings->rmCmd}, + vncViewer{settings->vncViewer}, + workpath{argWorkpath} { } diff --git a/src/Lib/receiptsprinter.h b/src/Lib/receiptsprinter.h old mode 100755 new mode 100644 index 1dbb882..38c46d1 --- a/src/Lib/receiptsprinter.h +++ b/src/Lib/receiptsprinter.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -32,22 +32,27 @@ namespace lc { /*! This class is used to do the actual printing of the receipts in an own thread. */ -class ReceiptsPrinter : public QThread { +class ReceiptsPrinter : public QThread +{ Q_OBJECT - void run() Q_DECL_OVERRIDE { + void run() override + { // Compile the TeX file to dvi QStringList arguments; - arguments << "-interaction" << "batchmode" << QString{ dateString + ".tex" }; + arguments << "-interaction" << "batchmode" << QString{dateString + ".tex"}; QProcess *process = nullptr; process = new QProcess{}; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - process->setProcessEnvironment( env ); - process->setWorkingDirectory( workpath ); - process->start( latexCmd, arguments ); - if( !process->waitForFinished( processTimeOut ) ) { - QMessageBox message_box{ QMessageBox::Warning, "dvi creation failed", "The creation of the receipts dvi timed out after 30 seconds. Automatic receipts creation will not work.", QMessageBox::Ok }; + const QProcessEnvironment env{QProcessEnvironment::systemEnvironment()}; + process->setProcessEnvironment(env); + process->setWorkingDirectory(workpath); + process->start(latexCmd, arguments); + if (!process->waitForFinished(processTimeOut)) { + QMessageBox message_box{QMessageBox::Warning, "dvi creation failed", + "The creation of the receipts dvi timed out" + " after 30 seconds. Automatic receipts creation will not work.", + QMessageBox::Ok}; message_box.exec(); delete process; process = nullptr; @@ -58,14 +63,15 @@ class ReceiptsPrinter : public QThread { // Convert the dvi file to postscript arguments = QStringList{}; - arguments << "-q*" << "-o" << QString{ dateString + ".ps" } << QString{ dateString + ".dvi" }; + arguments << "-q*" << "-o" << QString{dateString + ".ps"} << QString{dateString + ".dvi"}; process = new QProcess{}; - process->setProcessEnvironment( env ); - process->setWorkingDirectory( workpath ); - process->start( dvipsCmd, arguments ); - if( !process->waitForFinished( processTimeOut ) ) { - emit ErrorOccurred(new QString{ "The conversion of the receipts dvi to postscript timed out after 30 seconds. Automatic receipts creation will not work." }, new QString{ "dvi to postscript conversion failed" } ); + process->setProcessEnvironment(env); + process->setWorkingDirectory(workpath); + process->start(dvipsCmd, arguments); + if (!process->waitForFinished(processTimeOut)) { + emit ErrorOccurred(new QString{"The conversion of the receipts dvi to postscript timed out after 30 seconds. Automatic receipts creation will not work."}, + new QString{"dvi to postscript conversion failed"}); delete process; process = nullptr; return; @@ -74,75 +80,79 @@ class ReceiptsPrinter : public QThread { process = nullptr; // Print the postscript file - if ( !lprCmd.isEmpty() ) { + if (!lprCmd.isEmpty()) { arguments = QStringList{}; - arguments << QString{ workpath + "/" + dateString + ".ps" }; + arguments << QString{workpath + "/" + dateString + ".ps"}; process = new QProcess{}; - process->setProcessEnvironment( env ); - process->setWorkingDirectory( workpath ); - process->start( lprCmd, arguments ); - if( !process->waitForFinished( processTimeOut ) ) { - emit ErrorOccurred( new QString{ "The receipts postscript file was successfully created but could not be printed." }, new QString{ "Printing failed" } ); + process->setProcessEnvironment(env); + process->setWorkingDirectory(workpath); + process->start(lprCmd, arguments); + if ( !process->waitForFinished( processTimeOut ) ) { + emit ErrorOccurred(new QString{"The receipts postscript file was successfully created but could not be printed."}, + new QString{"Printing failed"}); } delete process; process = nullptr; } // Convert the postscript file to pdf - if ( !ps2pdfCmd.isEmpty() ) { + if (!ps2pdfCmd.isEmpty()) { arguments = QStringList{}; - arguments << QString{ workpath + "/" + dateString + ".ps" } << QString{ workpath + "/" + dateString + ".pdf" }; + arguments << QString{workpath + "/" + dateString + ".ps"} << QString{workpath + "/" + dateString + ".pdf"}; process = new QProcess{}; - process->setProcessEnvironment( env ); - process->setWorkingDirectory( workpath ); - process->start( ps2pdfCmd, arguments ); - if( !process->waitForFinished( processTimeOut ) ) { - emit ErrorOccurred( new QString{ "The receipts were successfully printed but the creation of the PDF file failed." }, new QString{ "PDF creation failed" } ); + process->setProcessEnvironment(env); + process->setWorkingDirectory(workpath); + process->start(ps2pdfCmd, arguments); + if (!process->waitForFinished(processTimeOut)) { + emit ErrorOccurred(new QString{"The receipts were successfully printed but the creation of the PDF file failed."}, + new QString{"PDF creation failed"}); } delete process; process = nullptr; // Show the postscript file if the conversion succeeded - if ( !postscriptViewer.isEmpty() ) { + if (!postscriptViewer.isEmpty()) { arguments = QStringList{}; - arguments << QString{ workpath + "/" + dateString + ".ps" }; + arguments << QString{workpath + "/" + dateString + ".ps"}; process = new QProcess{}; - process->setProcessEnvironment( env ); - process->setWorkingDirectory( workpath ); - process->startDetached( postscriptViewer, arguments ); + process->setProcessEnvironment(env); + process->setWorkingDirectory(workpath); + process->startDetached(postscriptViewer, arguments); delete process; process = nullptr; } } // Clean up the zTree working path - if ( !rmCmd.isEmpty() ) { + if (!rmCmd.isEmpty()) { arguments = QStringList{}; - arguments << QString{ workpath + "/" + dateString + ".aux" } - << QString{ workpath + "/" + dateString + ".dvi" } - << QString{ workpath + "/" + dateString + ".log" } - << QString{ workpath + "/" + dateString + ".tex" }; + arguments << QString{workpath + "/" + dateString + ".aux"} + << QString{workpath + "/" + dateString + ".dvi"} + << QString{workpath + "/" + dateString + ".log"} + << QString{workpath + "/" + dateString + ".tex"}; process = new QProcess{}; - process->setProcessEnvironment( env ); - process->setWorkingDirectory( workpath ); + process->setProcessEnvironment(env); + process->setWorkingDirectory(workpath); process->start( rmCmd, arguments); - if( !process->waitForFinished( processTimeOut ) ) { - emit ErrorOccurred(new QString("The cleanup of the temporary files for receipts creation timed out. Some spare files may be left in your zTree working directory."), new QString("Cleanup failed")); + if (!process->waitForFinished(processTimeOut)) { + emit ErrorOccurred(new + QString("The cleanup of the temporary files for receipts creation timed out. Some spare files may be left in your zTree working directory."), + new QString("Cleanup failed")); } delete process; process = nullptr; - } + } emit PrintingFinished(); } public: - explicit ReceiptsPrinter( const QString &argDateString, - const QString &argWorkpath, - QObject *argParent = nullptr ); + explicit ReceiptsPrinter(const QString &argDateString, + const QString &argWorkpath, + QObject *argParent = nullptr); signals: void ErrorOccurred(QString *error_message, QString *heading); @@ -154,13 +164,14 @@ private: const QString latexCmd; const QString lprCmd; const QString postscriptViewer; - const int processTimeOut = 15000; //! The maximum time which will be granted to a started process + const int processTimeOut = + 15000; //! The maximum time which will be granted to a started process const QString ps2pdfCmd; const QString rmCmd; const QString vncViewer; const QString workpath; //!< The path were zTree was ordered to store all its data }; -} +} // namespace lc #endif // RECEIPTSPRINTER_H From 847c83d2d4057282fd886a394440709e3b20fe42 Mon Sep 17 00:00:00 2001 From: markuspg Date: Tue, 13 Mar 2018 22:43:57 +0100 Subject: [PATCH 17/30] Reformat Session --- src/Lib/session.cpp | 88 +++++++++++++++++++++++---------------------- src/Lib/session.h | 46 ++++++++++++++---------- 2 files changed, 72 insertions(+), 62 deletions(-) mode change 100755 => 100644 src/Lib/session.h diff --git a/src/Lib/session.cpp b/src/Lib/session.cpp index ea9e93e..0e757b4 100644 --- a/src/Lib/session.cpp +++ b/src/Lib/session.cpp @@ -24,53 +24,54 @@ #include -extern std::unique_ptr< lc::Settings > settings; - -lc::Session::Session( QVector< Client * > &&argAssocClients, - const QString &argZTreeDataTargetPath, const quint16 argZTreePort, - const QString &argZTreeVersionPath, bool argPrintReceiptsForLocalClients, - const QString &argAnonymousReceiptsPlaceholder, - const QString &argLatexHeaderName, QObject *argParent ): - QObject{ argParent }, - zTreePort{ argZTreePort }, - anonymousReceiptsPlaceholder{ argAnonymousReceiptsPlaceholder }, - assocClients{ std::move( argAssocClients ) }, - latexHeaderName{ argLatexHeaderName }, - printReceiptsForLocalClients{ argPrintReceiptsForLocalClients }, - zTreeDataTargetPath{ argZTreeDataTargetPath }, - zTreeVersionPath{ argZTreeVersionPath } +extern std::unique_ptr settings; + +lc::Session::Session(QVector &&argAssocClients, + const QString &argZTreeDataTargetPath, const quint16 argZTreePort, + const QString &argZTreeVersionPath, bool argPrintReceiptsForLocalClients, + const QString &argAnonymousReceiptsPlaceholder, + const QString &argLatexHeaderName, QObject *argParent): + QObject{argParent}, + zTreePort{argZTreePort}, + anonymousReceiptsPlaceholder{argAnonymousReceiptsPlaceholder}, + assocClients{std::move(argAssocClients)}, + latexHeaderName{argLatexHeaderName}, + printReceiptsForLocalClients{argPrintReceiptsForLocalClients}, + zTreeDataTargetPath{argZTreeDataTargetPath}, + zTreeVersionPath{argZTreeVersionPath} { // This part ensures, that both class instances are created in the same minute, so that the payment file name can be guessed correctly QDateTime current_time; current_time = QDateTime::currentDateTime(); // If in the last three seconds of a minute, wait for the next one to start - if ( QTime::currentTime().second() > 56 ) { - QTimer::singleShot( 5000, this, SLOT( InitializeClasses() ) ); + if (QTime::currentTime().second() > 56) { + QTimer::singleShot(5000, this, SLOT(InitializeClasses())); } else { InitializeClasses(); } - if ( !settings->wmctrlCmd.isEmpty() ) { - QTimer::singleShot( 5000, this, SLOT( RenameWindow() ) ); + if (!settings->wmctrlCmd.isEmpty()) { + QTimer::singleShot(5000, this, SLOT(RenameWindow())); } } lc::Session::~Session() { - for ( auto &client : assocClients ) { - client->SetSessionPort( 0 ); - client->SetzLeafVersion( "" ); + for (auto &client : assocClients) { + client->SetSessionPort(0); + client->SetzLeafVersion(""); } } -QVariant lc::Session::GetDataItem( int argIndex ) +QVariant lc::Session::GetDataItem(int argIndex) { - switch ( argIndex ) { + switch (argIndex) { case 0: - return QVariant{ zTreeVersionPath.split( '_', QString::KeepEmptyParts, Qt::CaseInsensitive )[ 1 ] }; + return QVariant{zTreeVersionPath.split('_', QString::KeepEmptyParts, + Qt::CaseInsensitive)[1]}; case 1: - return QVariant{ zTreePort }; + return QVariant{zTreePort}; default: return QVariant{}; } @@ -79,31 +80,32 @@ QVariant lc::Session::GetDataItem( int argIndex ) void lc::Session::InitializeClasses() { // Create the new data directory - QDir dir{ zTreeDataTargetPath }; - QString date_string( QDateTime::currentDateTime().toString( "yyMMdd_hhmm" ) ); - if ( !dir.mkdir( zTreeDataTargetPath + "/" + date_string + "-" + QString::number( zTreePort ) ) ) { + QDir dir{zTreeDataTargetPath}; + QString date_string(QDateTime::currentDateTime().toString("yyMMdd_hhmm")); + if (!dir.mkdir(zTreeDataTargetPath + "/" + date_string + "-" + QString::number(zTreePort))) { throw lcDataTargetPathCreationFailed{}; } - zTreeDataTargetPath.append( "/" + date_string + "-" + QString::number( zTreePort ) ); + zTreeDataTargetPath.append("/" + date_string + "-" + QString::number(zTreePort)); qDebug() << "New session's chosen_zTree_data_target_path:" << zTreeDataTargetPath; - zTreeInstance = new ZTree{ zTreeDataTargetPath, zTreePort, zTreeVersionPath, this }; - connect( zTreeInstance, &ZTree::ZTreeClosed, - this, &Session::OnzTreeClosed ); + zTreeInstance = new ZTree{zTreeDataTargetPath, zTreePort, + zTreeVersionPath, this}; + connect(zTreeInstance, &ZTree::ZTreeClosed, + this, &Session::OnzTreeClosed); // Only create a 'Receipts_Handler' instance, if all neccessary variables were set - if ( latexHeaderName != "None found" && !settings->dvipsCmd.isEmpty() - && !settings->latexCmd.isEmpty() ) { - new ReceiptsHandler{ zTreeDataTargetPath, printReceiptsForLocalClients, - anonymousReceiptsPlaceholder, latexHeaderName, this }; + if (latexHeaderName != "None found" && !settings->dvipsCmd.isEmpty() + && !settings->latexCmd.isEmpty()) { + new ReceiptsHandler{zTreeDataTargetPath, printReceiptsForLocalClients, + anonymousReceiptsPlaceholder, latexHeaderName, this}; } else { qDebug() << "No 'ReceiptsHandler' instance was created."; } } -void lc::Session::OnzTreeClosed( int argExitCode ) +void lc::Session::OnzTreeClosed(int argExitCode) { qDebug() << "z-Tree running on port" << zTreePort << "closed with exit code" << argExitCode; - emit SessionFinished( this ); + emit SessionFinished(this); } void lc::Session::RenameWindow() @@ -111,13 +113,13 @@ void lc::Session::RenameWindow() // Example: wmctrl -r -T QStringList arguments; - arguments << "-r" << "zTree - Untitled Treatment 1" << "-T" << QString{ "zTree on port " + QString::number( zTreePort ) }; + arguments << "-r" << "zTree - Untitled Treatment 1" << "-T" + << QString{"zTree on port " + QString::number(zTreePort)}; // Start the process QProcess renameZTreeWindowProcess; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - renameZTreeWindowProcess.setProcessEnvironment( env ); - renameZTreeWindowProcess.startDetached( settings->wmctrlCmd, arguments ); + renameZTreeWindowProcess.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); + renameZTreeWindowProcess.startDetached(settings->wmctrlCmd, arguments); qDebug() << "Renamed window"; diff --git a/src/Lib/session.h b/src/Lib/session.h old mode 100755 new mode 100644 index 18c27e7..ed732ae --- a/src/Lib/session.h +++ b/src/Lib/session.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -34,48 +34,56 @@ class Client; /*! This class represents an entire session with its zTree instance and the corresponding lcReceiptsHandler instance. */ -class Session : public QObject { +class Session : public QObject +{ Q_OBJECT public: - const int zTreePort = 7000; //! The port this session's zTree instance is running on + //! The port this session's zTree instance is running on + const int zTreePort = 7000; - Session( QVector< Client* > &&argAssocClients, const QString &argZTreeDataTargetPath, - const quint16 argZTreePort, const QString &argZTreeVersionPath, - bool argPrintReceiptsForLocalClients, - const QString &argAnonymousReceiptsPlaceholder, - const QString &argLatexHeaderName, QObject *argParent = nullptr ); - ~Session(); + Session(QVector &&argAssocClients, const QString &argZTreeDataTargetPath, + const quint16 argZTreePort, const QString &argZTreeVersionPath, + bool argPrintReceiptsForLocalClients, + const QString &argAnonymousReceiptsPlaceholder, + const QString &argLatexHeaderName, QObject *argParent = nullptr); + ~Session() override; /*! Returns the data item with the given index * * @param argIndex The index of the desired item */ - QVariant GetDataItem( int argIndex ); + QVariant GetDataItem(int argIndex); //! This gets thrown as an exception if the chosen data target path could not be created. class lcDataTargetPathCreationFailed {}; signals: - void SessionFinished( Session *argSession ); + void SessionFinished(Session *argSession); private slots: /*! Starts the session by creating instances of the relevant classes */ void InitializeClasses(); - void OnzTreeClosed( int argExitCode ); + void OnzTreeClosed(int argExitCode); /*! Changes zTree's window title to contain its port number to make zTree windows distinguishable */ void RenameWindow(); private: - const QString anonymousReceiptsPlaceholder; //! Placeholder which shall be inserted for participant names if anonymous printing is desired (QString != "") - const QVector< Client* > assocClients; - const QString latexHeaderName; //! The name of the chosen LaTeX header - const bool printReceiptsForLocalClients = true; //! True if receipts shall be printed for local clients - QString zTreeDataTargetPath; //! The path were the data of this zTree instance's session will be saved - ZTree *zTreeInstance= nullptr; //! The session's zTree instance - const QString zTreeVersionPath; //! The path to the version of zTree used by this session's instance + //! Placeholder which shall be inserted for participant names if anonymous printing is desired (QString != "") + const QString anonymousReceiptsPlaceholder; + const QVector assocClients; + //! The name of the chosen LaTeX header + const QString latexHeaderName; + //! True if receipts shall be printed for local clients + const bool printReceiptsForLocalClients = true; + //! The path were the data of this zTree instance's session will be saved + QString zTreeDataTargetPath; + //! The session's zTree instance + ZTree *zTreeInstance = nullptr; + //! The path to the version of zTree used by this session's instance + const QString zTreeVersionPath; }; } From c2b72b48d7383e44d699681349acd5be27368403 Mon Sep 17 00:00:00 2001 From: markuspg Date: Tue, 13 Mar 2018 22:54:25 +0100 Subject: [PATCH 18/30] Reformat Settings --- src/Lib/settings.cpp | 436 ++++++++++++++++++++++--------------------- src/Lib/settings.h | 75 +++++--- 2 files changed, 269 insertions(+), 242 deletions(-) mode change 100755 => 100644 src/Lib/settings.cpp mode change 100755 => 100644 src/Lib/settings.h diff --git a/src/Lib/settings.cpp b/src/Lib/settings.cpp old mode 100755 new mode 100644 index 7214061..12fdd64 --- a/src/Lib/settings.cpp +++ b/src/Lib/settings.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -25,127 +25,127 @@ #include "client.h" #include "settings.h" -lc::Settings::Settings( const QSettings &argSettings, QObject *argParent ) : - QObject{ argParent }, - defaultReceiptIndex{ GetDefaultReceiptIndex( argSettings ) }, - browserCmd{ ReadSettingsItem( "browser_command", - "Opening ORSEE in a browser will not work.", - argSettings, true ) }, - clientBrowserCmd{ ReadSettingsItem( "client_browser_command", - "Opening a browser window on clients will not work.", - argSettings, false ) }, - dvipsCmd{ ReadSettingsItem( "dvips_command", - "Receipts creation will not work.", - argSettings, true ) }, - fileMngr{ ReadSettingsItem( "file_manager", - "The display of preprints will not work.", - argSettings, true ) }, - killallCmd{ ReadSettingsItem( "killall_command", - "Killing 'zleaf.exe' instances will not work.", - argSettings, true ) }, - latexCmd{ ReadSettingsItem( "latex_command", - "Receipts creation will not work.", - argSettings, true ) }, - lcDataDir{ ReadSettingsItem( "labcontrol_data_directory", - "Datapath not set. Labcontrol will missbehave with high propability.", - argSettings, true ) }, - localUserName{ GetLocalUserName() }, - localzLeafSize{ ReadSettingsItem( "local_zLeaf_size", - "Resolution of local zLeaf window", - argSettings, false ) }, - lprCmd{ ReadSettingsItem( "lpr_command", - "Receipts printing will not work.", - argSettings, true ) }, - netstatCmd{ ReadSettingsItem( "netstat_command", - "Detection of active zLeaf connections will not work.", - argSettings, true ) }, - netwBrdAddr{ ReadSettingsItem( "network_broadcast_address", - "Booting the clients will not work.", - argSettings, false ) }, - orseeUrl{ ReadSettingsItem( "orsee_url", +lc::Settings::Settings(const QSettings &argSettings, QObject *argParent) : + QObject{argParent}, + defaultReceiptIndex{GetDefaultReceiptIndex(argSettings)}, + browserCmd{ReadSettingsItem("browser_command", "Opening ORSEE in a browser will not work.", - argSettings, false ) }, - pingCmd{ ReadSettingsItem( "ping_command", - "Status updates for the clients will not work.", - argSettings, true ) }, - postscriptViewer{ ReadSettingsItem( "postscript_viewer", - "Viewing the generated receipts postscript file will not work.", - argSettings, true ) }, - ps2pdfCmd{ ReadSettingsItem( "ps2pdf_command", - "Converting and viewing the generated receipts file will not work.", - argSettings, true ) }, - pkeyPathRoot{ ReadSettingsItem( "pkey_path_root", - "Administration actions concerning the clients will not be available.", - argSettings, true ) }, - pkeyPathUser{ ReadSettingsItem( "pkey_path_user", - "Many actions concerning the clients will not be available.", - argSettings, true ) }, - rmCmd{ ReadSettingsItem( "rm_command", - "Cleanup of the zTree data target path will not work.", - argSettings, true ) }, - scpCmd{ ReadSettingsItem( "scp_command", - "Beaming files to the clients will not be possible.", - argSettings, true ) }, - serverIP{ ReadSettingsItem( "server_ip", - "Starting zLeaves and retrieving client help messages will not work.", - argSettings, false ) }, - sshCmd{ ReadSettingsItem( "ssh_command", - "All actions concerning the clients will not be possible.", - argSettings, true ) }, - tasksetCmd{ ReadSettingsItem( "taskset_command", - "Running z-Leaves or z-Tree will be possible.", - argSettings, true ) }, - termEmulCmd{ ReadSettingsItem( "terminal_emulator_command", - "Conducting administrative tasks will not be possible.", - argSettings, true ) }, - userNameOnClients{ ReadSettingsItem( "user_name_on_clients", - "All actions concerning the clients performed by the experiment user will not work.", - argSettings, false ) }, - vncViewer{ ReadSettingsItem( "vnc_viewer", - "Viewing the clients' screens will not work.", - argSettings, true ) }, - wakeonlanCmd{ ReadSettingsItem( "wakeonlan_command", - "Booting the clients will not work.", - argSettings, true ) }, - webcamDisplayCmd{ ReadSettingsItem( "webcam_command", - "Displaying the laboratory's webcams will not work.", - argSettings, true ) }, - webcams{ argSettings.value( "webcams", "" ).toString().split( '|', QString::SkipEmptyParts, - Qt::CaseInsensitive ) }, - webcams_names{ argSettings.value( "webcams_names", "" ).toString().split( '|', QString::SkipEmptyParts, - Qt::CaseInsensitive ) }, - wineCmd{ ReadSettingsItem( "wine_command", - "Running z-Leaves or z-Tree will be possible.", - argSettings, true ) }, - wmctrlCmd{ ReadSettingsItem( "wmctrl_command", - "Setting zTree's window title to its port number will not work.", - argSettings, true ) }, - xsetCmd{ ReadSettingsItem( "xset_command", - "Deactivating the screen saver on the clients will not be possible.", - argSettings, true ) }, - zTreeInstDir{ ReadSettingsItem( "ztree_installation_directory", - "zTree will not be available.", - argSettings, true ) }, - restartCrashedSessionScript{ ReadSettingsItem( "restart_crashed_session_script", - "Script to be called after session crash", - argSettings, false ) }, - adminUsers{ GetAdminUsers( argSettings ) }, - installedLaTeXHeaders{ DetectInstalledLaTeXHeaders() }, - installedZTreeVersions{ DetectInstalledzTreeVersions() }, - clientHelpNotificationServerPort{ GetClientHelpNotificationServerPort( argSettings ) }, - chosenzTreePort{ GetInitialPort( argSettings ) }, - clients{ CreateClients( argSettings, pingCmd ) }, - localzLeafName{ ReadSettingsItem( "local_zLeaf_name", - "The local zLeaf default name will default to 'local'.", - argSettings, false ) }, - clIPsToClMap{ CreateClIPsToClMap( clients ) } + argSettings, true)}, + clientBrowserCmd{ReadSettingsItem("client_browser_command", + "Opening a browser window on clients will not work.", + argSettings, false)}, + dvipsCmd{ReadSettingsItem("dvips_command", + "Receipts creation will not work.", + argSettings, true)}, + fileMngr{ReadSettingsItem("file_manager", + "The display of preprints will not work.", + argSettings, true)}, + killallCmd{ ReadSettingsItem("killall_command", + "Killing 'zleaf.exe' instances will not work.", + argSettings, true)}, + latexCmd{ReadSettingsItem("latex_command", + "Receipts creation will not work.", + argSettings, true)}, + lcDataDir{ReadSettingsItem("labcontrol_data_directory", + "Datapath not set. Labcontrol will missbehave with high propability.", + argSettings, true)}, + localUserName{GetLocalUserName()}, + localzLeafSize{ReadSettingsItem("local_zLeaf_size", + "Resolution of local zLeaf window", + argSettings, false)}, + lprCmd{ReadSettingsItem("lpr_command", + "Receipts printing will not work.", + argSettings, true)}, + netstatCmd{ReadSettingsItem("netstat_command", + "Detection of active zLeaf connections will not work.", + argSettings, true)}, + netwBrdAddr{ReadSettingsItem("network_broadcast_address", + "Booting the clients will not work.", + argSettings, false)}, + orseeUrl{ReadSettingsItem("orsee_url", + "Opening ORSEE in a browser will not work.", + argSettings, false)}, + pingCmd{ReadSettingsItem("ping_command", + "Status updates for the clients will not work.", + argSettings, true)}, + postscriptViewer{ReadSettingsItem("postscript_viewer", + "Viewing the generated receipts postscript file will not work.", + argSettings, true)}, + ps2pdfCmd{ReadSettingsItem("ps2pdf_command", + "Converting and viewing the generated receipts file will not work.", + argSettings, true)}, + pkeyPathRoot{ReadSettingsItem("pkey_path_root", + "Administration actions concerning the clients will not be available.", + argSettings, true)}, + pkeyPathUser{ReadSettingsItem("pkey_path_user", + "Many actions concerning the clients will not be available.", + argSettings, true)}, + rmCmd{ReadSettingsItem("rm_command", + "Cleanup of the zTree data target path will not work.", + argSettings, true)}, + scpCmd{ReadSettingsItem("scp_command", + "Beaming files to the clients will not be possible.", + argSettings, true)}, + serverIP{ReadSettingsItem("server_ip", + "Starting zLeaves and retrieving client help messages will not work.", + argSettings, false)}, + sshCmd{ReadSettingsItem("ssh_command", + "All actions concerning the clients will not be possible.", + argSettings, true)}, + tasksetCmd{ReadSettingsItem("taskset_command", + "Running z-Leaves or z-Tree will be possible.", + argSettings, true)}, + termEmulCmd{ReadSettingsItem("terminal_emulator_command", + "Conducting administrative tasks will not be possible.", + argSettings, true)}, + userNameOnClients{ReadSettingsItem("user_name_on_clients", + "All actions concerning the clients performed by the experiment user will not work.", + argSettings, false)}, + vncViewer{ReadSettingsItem("vnc_viewer", + "Viewing the clients' screens will not work.", + argSettings, true)}, + wakeonlanCmd{ReadSettingsItem("wakeonlan_command", + "Booting the clients will not work.", + argSettings, true)}, + webcamDisplayCmd{ReadSettingsItem("webcam_command", + "Displaying the laboratory's webcams will not work.", + argSettings, true)}, + webcams{argSettings.value("webcams", "").toString().split('|', QString::SkipEmptyParts, + Qt::CaseInsensitive)}, + webcams_names{argSettings.value("webcams_names", "").toString().split('|', QString::SkipEmptyParts, + Qt::CaseInsensitive)}, + wineCmd{ReadSettingsItem("wine_command", + "Running z-Leaves or z-Tree will be possible.", + argSettings, true)}, + wmctrlCmd{ReadSettingsItem("wmctrl_command", + "Setting zTree's window title to its port number will not work.", + argSettings, true)}, + xsetCmd{ReadSettingsItem("xset_command", + "Deactivating the screen saver on the clients will not be possible.", + argSettings, true)}, + zTreeInstDir{ReadSettingsItem("ztree_installation_directory", + "zTree will not be available.", + argSettings, true)}, + restartCrashedSessionScript{ReadSettingsItem("restart_crashed_session_script", + "Script to be called after session crash", + argSettings, false)}, + adminUsers{GetAdminUsers(argSettings ) }, + installedLaTeXHeaders{DetectInstalledLaTeXHeaders()}, + installedZTreeVersions{DetectInstalledzTreeVersions()}, + clientHelpNotificationServerPort{GetClientHelpNotificationServerPort(argSettings)}, + chosenzTreePort{GetInitialPort(argSettings)}, + clients{CreateClients(argSettings, pingCmd)}, + localzLeafName{ReadSettingsItem("local_zLeaf_name", + "The local zLeaf default name will default to 'local'.", + argSettings, false)}, + clIPsToClMap{CreateClIPsToClMap(clients)} { // Let the local zLeaf name default to 'local' if none was given in the settings - if ( localzLeafName.isEmpty() ) { + if (localzLeafName.isEmpty()) { qDebug() << "'local_zLeaf_name' was not set, defaulting to 'local'"; localzLeafName = "local"; } - if ( webcams.isEmpty() ) { + if (webcams.isEmpty()) { qDebug() << "'webcams' was not properly set. No stationary webcams will be available."; } else { qDebug() << "The following webcams where loaded:" << webcams; @@ -153,15 +153,17 @@ lc::Settings::Settings( const QSettings &argSettings, QObject *argParent ) : qDebug() << "Detected z-Tree versions" << installedZTreeVersions; } -lc::Settings::~Settings() { - for ( QVector< Client* >::iterator it = clients.begin(); it != clients.end(); ++it ) { +lc::Settings::~Settings() +{ + for (QVector::iterator it = clients.begin(); it != clients.end(); ++it) { delete *it; } } -bool lc::Settings::CheckPathAndComplain( const QString &argPath, const QString &argVariableName, - const QString &argMessage ) { - if ( !QFile::exists( argPath ) ) { +bool lc::Settings::CheckPathAndComplain(const QString &argPath, const QString &argVariableName, + const QString &argMessage) +{ + if (!QFile::exists(argPath)) { qDebug() << "The path" << argPath << "specified by" << argVariableName << "does not exist:" << argMessage; return false; @@ -170,89 +172,92 @@ bool lc::Settings::CheckPathAndComplain( const QString &argPath, const QString & return true; } -QVector< lc::Client* > lc::Settings::CreateClients( const QSettings &argSettings, - const QString &argPingCmd ) { - QVector< Client* > tempClientVec; +QVector lc::Settings::CreateClients(const QSettings &argSettings, + const QString &argPingCmd) +{ + QVector tempClientVec; // Get the client quantity to check the value lists for clients creation for correct length int clientQuantity = 0; - if ( !argSettings.contains("client_quantity" ) ) { + if (!argSettings.contains("client_quantity")) { qWarning() << "'client_quantity' was not set. The client quantity will be guessed" - " by the amount of client IPs set in 'client_ips'."; - clientQuantity = argSettings.value( "client_ips", "" ).toString() - .split( '/', QString::SkipEmptyParts, Qt::CaseSensitive ).length(); + " by the amount of client IPs set in 'client_ips'."; + clientQuantity = argSettings.value("client_ips", "").toString() + .split('/', QString::SkipEmptyParts, Qt::CaseSensitive).length(); qDebug() << "'clientQuantity':" << clientQuantity; } else { bool ok = true; - clientQuantity = argSettings.value( "client_quantity" ).toInt( &ok ); - if ( !ok ) { + clientQuantity = argSettings.value("client_quantity").toInt(&ok); + if (!ok) { qWarning() << "The variable 'client_quantity' was not convertible to int"; } qDebug() << "'clientQuantity':" << clientQuantity; } // Create all the clients in the lab - QStringList clientIPs = argSettings.value( "client_ips" ).toString() - .split( '|', QString::SkipEmptyParts, Qt::CaseSensitive ); - if ( clientIPs.length() != clientQuantity ) { + QStringList clientIPs = argSettings.value("client_ips").toString() + .split('|', QString::SkipEmptyParts, Qt::CaseSensitive); + if ( clientIPs.length() != clientQuantity) { qWarning() << "The quantity of client ips does not match the client quantity. Client" - " creation will fail. No clients will be available for interaction."; + " creation will fail. No clients will be available for interaction."; return tempClientVec; } qDebug() << "Client IPs:" << clientIPs.join( " / " ); - QStringList clientMACs = argSettings.value( "client_macs" ).toString() - .split( '|', QString::SkipEmptyParts, Qt::CaseSensitive ); - if ( clientMACs.length() != clientQuantity ) { + QStringList clientMACs = argSettings.value("client_macs").toString() + .split('|', QString::SkipEmptyParts, Qt::CaseSensitive); + if (clientMACs.length() != clientQuantity) { qWarning() << "The quantity of client macs does not match the client quantity. Client" - " creation will fail. No clients will be available for interaction."; + " creation will fail. No clients will be available for interaction."; return tempClientVec; } qDebug() << "Client MACs:" << clientMACs.join( " / " ); - QStringList clientNames = argSettings.value( "client_names" ).toString() - .split( '|', QString::SkipEmptyParts, Qt::CaseSensitive ); - if ( clientNames.length() != clientQuantity ) { + QStringList clientNames = argSettings.value("client_names").toString() + .split('|', QString::SkipEmptyParts, Qt::CaseSensitive); + if (clientNames.length() != clientQuantity) { qWarning() << "The quantity of client names does not match the client quantity. Client" - " creation will fail. No clients will be available for interaction."; + " creation will fail. No clients will be available for interaction."; return tempClientVec; } qDebug() << "Client names:" << clientNames.join( " / " ); - QStringList clientXPositions = argSettings.value( "client_xpos" ).toString() - .split( '|', QString::SkipEmptyParts, Qt::CaseSensitive ); - if ( clientXPositions.length() != clientQuantity ) { + QStringList clientXPositions = argSettings.value("client_xpos").toString() + .split('|', QString::SkipEmptyParts, Qt::CaseSensitive); + if (clientXPositions.length() != clientQuantity) { qWarning() << "The quantity of client x positions does not match the client quantity." - " Client creation will fail. No clients will be available for interaction."; + " Client creation will fail. No clients will be available for interaction."; return tempClientVec; } qDebug() << "clientXPositions:" << clientXPositions.join( " / " ); - QStringList clientYPositions = argSettings.value( "client_ypos" ).toString() - .split( '|', QString::SkipEmptyParts, Qt::CaseSensitive ); - if ( clientYPositions.length() != clientQuantity ) { + QStringList clientYPositions = argSettings.value("client_ypos").toString() + .split('|', QString::SkipEmptyParts, Qt::CaseSensitive); + if (clientYPositions.length() != clientQuantity) { qWarning() << "The quantity of client y positions does not match the client quantity." - " Client creation will fail. No clients will be available for interaction."; + " Client creation will fail. No clients will be available for interaction."; return tempClientVec; } - qDebug() << "clientYPositions:" << clientYPositions.join( " / " ); + qDebug() << "clientYPositions:" << clientYPositions.join(" / "); - for ( int i = 0; i < clientQuantity; i++ ) { - tempClientVec.append( new Client{ clientIPs[ i ], clientMACs[ i ], clientNames[ i ], - clientXPositions[ i ].toUShort(), - clientYPositions[ i ].toUShort(), argPingCmd } ); + for (int i = 0; i < clientQuantity; i++) { + tempClientVec.append(new Client{clientIPs[i], clientMACs[i], clientNames[i], + clientXPositions[i].toUShort(), + clientYPositions[i].toUShort(), argPingCmd}); } return tempClientVec; } -QMap< QString, lc::Client* > lc::Settings::CreateClIPsToClMap( const QVector< Client* > &argClients ) { - QMap< QString, Client* > tempMap; - for ( const auto &s : argClients ) { - tempMap.insert( s->ip, s ); +QMap< QString, lc::Client * > lc::Settings::CreateClIPsToClMap(const QVector + &argClients) +{ + QMap tempMap; + for (const auto &s : argClients) { + tempMap.insert(s->ip, s); // Get the address of the Client instance in RAM for display - const void *clientPtrAddr = static_cast< const void* >( tempMap[ s->ip ] ); + const void *clientPtrAddr = static_cast(tempMap[s->ip]); qDebug() << "Added" << s->name << "to 'clientIPsToClientsMap':" << clientPtrAddr; @@ -260,63 +265,67 @@ QMap< QString, lc::Client* > lc::Settings::CreateClIPsToClMap( const QVector< Cl return tempMap; } -QStringList lc::Settings::DetectInstalledLaTeXHeaders() const { - QStringList tempLaTeXHeaders{ "None found" }; +QStringList lc::Settings::DetectInstalledLaTeXHeaders() const +{ + QStringList tempLaTeXHeaders{"None found"}; // Detect the installed LaTeX headers - if ( !lcDataDir.isEmpty() ) { - QDir laTeXDirectory{ lcDataDir, "*_header.tex", QDir::Name, - QDir::CaseSensitive | QDir::Files | QDir::Readable }; - if ( !laTeXDirectory.exists() || laTeXDirectory.entryList().isEmpty() ) { + if (!lcDataDir.isEmpty()) { + QDir laTeXDirectory{lcDataDir, "*_header.tex", QDir::Name, + QDir::CaseSensitive | QDir::Files | QDir::Readable}; + if (!laTeXDirectory.exists() || laTeXDirectory.entryList().isEmpty()) { qDebug() << "Receipts printing will not work. No LaTeX headers could be found in" << lcDataDir; } else { tempLaTeXHeaders = laTeXDirectory.entryList(); - tempLaTeXHeaders.replaceInStrings( "_header.tex", "" ); - qDebug() << "LaTeX headers:" << tempLaTeXHeaders.join( " / " ); + tempLaTeXHeaders.replaceInStrings("_header.tex", ""); + qDebug() << "LaTeX headers:" << tempLaTeXHeaders.join(" / "); } } return tempLaTeXHeaders; } -QStringList lc::Settings::DetectInstalledzTreeVersions() const { +QStringList lc::Settings::DetectInstalledzTreeVersions() const +{ QStringList tempInstzTreeVersions; - if ( !zTreeInstDir.isEmpty() ) { - QDir zTreeDirectory{ zTreeInstDir, "zTree_*", QDir::Name, - QDir::NoDotAndDotDot | QDir::Dirs - | QDir::Readable | QDir::CaseSensitive }; - if ( zTreeDirectory.entryList().isEmpty() ) { + if (!zTreeInstDir.isEmpty()) { + QDir zTreeDirectory{zTreeInstDir, "zTree_*", QDir::Name, + QDir::NoDotAndDotDot | QDir::Dirs + | QDir::Readable | QDir::CaseSensitive}; + if (zTreeDirectory.entryList().isEmpty()) { qWarning() << "No zTree versions could be found in" << zTreeInstDir; } else { tempInstzTreeVersions = zTreeDirectory.entryList(); - tempInstzTreeVersions.replaceInStrings( "zTree_", "" ); + tempInstzTreeVersions.replaceInStrings("zTree_", ""); } } return tempInstzTreeVersions; } -QStringList lc::Settings::GetAdminUsers( const QSettings &argSettings ) { +QStringList lc::Settings::GetAdminUsers(const QSettings &argSettings) +{ // Read the list of users with administrative rights - if ( !argSettings.contains( "admin_users" ) ) { + if (!argSettings.contains("admin_users")) { qDebug() << "The 'admin_users' variable was not set." - " No users will be able to conduct administrative tasks."; + " No users will be able to conduct administrative tasks."; return QStringList{}; } else { - QStringList adminUsers{ argSettings.value( "admin_users", "" ).toString() - .split( '|', QString::SkipEmptyParts, Qt::CaseInsensitive ) }; - qDebug() << "'adminUsers':" << adminUsers.join( " / " ); + QStringList adminUsers{argSettings.value("admin_users", "").toString() + .split('|', QString::SkipEmptyParts, Qt::CaseInsensitive)}; + qDebug() << "'adminUsers':" << adminUsers.join(" / "); return adminUsers; } return QStringList{}; } -quint16 lc::Settings::GetClientHelpNotificationServerPort( const QSettings &argSettings ) { +quint16 lc::Settings::GetClientHelpNotificationServerPort(const QSettings &argSettings) +{ // Read the port the ClientHelpNotificationServer shall listen on - quint16 clientHelpNotificationServerPort = argSettings.value( "client_help_server_port", - 0 ).toUInt(); - if ( !clientHelpNotificationServerPort ) { + quint16 clientHelpNotificationServerPort = argSettings.value("client_help_server_port", + 0).toUInt(); + if (!clientHelpNotificationServerPort) { qDebug() << "The 'client_help_server_port' variable was not set or set to zero." - " The ClientHelpNotificationServer will be deactivated therefore." - " Clients' help requests will be ignored by the server."; + " The ClientHelpNotificationServer will be deactivated therefore." + " Clients' help requests will be ignored by the server."; return 0; } else { qDebug() << "'clientHelpNotificationServerPort':" << clientHelpNotificationServerPort; @@ -325,37 +334,40 @@ quint16 lc::Settings::GetClientHelpNotificationServerPort( const QSettings &argS return 0; } -int lc::Settings::GetDefaultReceiptIndex( const QSettings &argSettings ) { +int lc::Settings::GetDefaultReceiptIndex( const QSettings &argSettings ) +{ // Read the default receipt index for the 'CBReceipts' combobox - if ( !argSettings.contains( "default_receipt_index" ) ) { + if (!argSettings.contains("default_receipt_index")) { qDebug() << "'default_receipt_index' was not set. It will default to '0'."; return 0; } - int tempIndex = argSettings.value( "default_receipt_index", 0 ).toInt(); + int tempIndex = argSettings.value("default_receipt_index", 0).toInt(); qDebug() << "'defaultReceiptIndex':" << tempIndex; return tempIndex; } -int lc::Settings::GetInitialPort( const QSettings &argSettings ) { +int lc::Settings::GetInitialPort( const QSettings &argSettings ) +{ // Read the initial port number - if ( !argSettings.contains( "initial_port" ) ) { + if (!argSettings.contains("initial_port")) { qDebug() << "The 'initial_port' variable was not set." - " Labcontrol will default to port 7000 for new zTree instances."; + " Labcontrol will default to port 7000 for new zTree instances."; } - int initialPort = argSettings.value( "initial_port", 7000 ).toInt(); + int initialPort = argSettings.value("initial_port", 7000).toInt(); qDebug() << "'initial_port':" << initialPort; return initialPort; } -QString lc::Settings::GetLocalUserName() { - const QProcessEnvironment env{ QProcessEnvironment::systemEnvironment() }; +QString lc::Settings::GetLocalUserName() +{ + const QProcessEnvironment env{QProcessEnvironment::systemEnvironment()}; QString userName; // For Linux - if ( env.contains( "USER" ) ) { - userName = env.value( "USER", "" ); + if ( env.contains("USER")) { + userName = env.value("USER", ""); qDebug() << "The local user name is" << userName; - } else if ( env.contains( "USERNAME" ) ) { // For Windows - userName = env.value( "USERNAME", "" ); + } else if (env.contains("USERNAME")) { // For Windows + userName = env.value("USERNAME", ""); qDebug() << "The local user name is" << userName; } else { qWarning() << "The local user name could not be queried"; @@ -363,17 +375,18 @@ QString lc::Settings::GetLocalUserName() { return userName; } -QString lc::Settings::ReadSettingsItem( const QString &argVariableName, - const QString &argMessage, - const QSettings &argSettings, - bool argItemIsFile) { - if ( !argSettings.contains( argVariableName ) ) { +QString lc::Settings::ReadSettingsItem(const QString &argVariableName, + const QString &argMessage, + const QSettings &argSettings, + bool argItemIsFile) +{ + if (!argSettings.contains(argVariableName)) { qDebug() << argVariableName << "was not set." << argMessage; return QString{}; } else { - QString tempString{ argSettings.value( argVariableName ).toString() }; - if ( argItemIsFile - && !CheckPathAndComplain( tempString, argVariableName, argMessage ) ) { + QString tempString{argSettings.value(argVariableName).toString()}; + if (argItemIsFile + && !CheckPathAndComplain(tempString, argVariableName, argMessage)) { tempString.clear(); } return tempString; @@ -381,11 +394,12 @@ QString lc::Settings::ReadSettingsItem( const QString &argVariableName, return QString{}; } -void lc::Settings::SetLocalzLeafSize( QString arg) { +void lc::Settings::SetLocalzLeafSize(QString arg) +{ localzLeafSize = arg; } -void lc::Settings::SetChosenZTreePort( const int argPort ){ +void lc::Settings::SetChosenZTreePort(const int argPort) +{ chosenzTreePort = argPort; } - diff --git a/src/Lib/settings.h b/src/Lib/settings.h old mode 100755 new mode 100644 index 685f66b..838313a --- a/src/Lib/settings.h +++ b/src/Lib/settings.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -28,23 +28,30 @@ namespace lc { -class Settings : public QObject { +class Settings : public QObject +{ Q_OBJECT public: Settings() = delete; - explicit Settings( const QSettings &argSettings, QObject *argParent = nullptr ); - Settings( const Settings &argSettings ) = delete; - Settings& operator=( const Settings &argSettings ) = delete; - Settings( Settings &&argSettings ) = delete; - Settings& operator=( Settings &&argSettings ) = delete; + explicit Settings(const QSettings &argSettings, QObject *argParent = nullptr); + Settings(const Settings &argSettings) = delete; + Settings &operator=(const Settings &argSettings) = delete; + Settings(Settings &&argSettings ) = delete; + Settings &operator=(Settings &&argSettings) = delete; ~Settings(); - int GetChosenZTreePort() const { return chosenzTreePort; } - QVector< Client* > &GetClients() { return clients; } + int GetChosenZTreePort() const + { + return chosenzTreePort; + } + QVector< Client * > &GetClients() + { + return clients; + } QString GetLocalzLeafName() const; - void SetChosenZTreePort( const int argPort ); - void SetLocalzLeafName( const QString &argLocalzLeafName ); + void SetChosenZTreePort(const int argPort); + void SetLocalzLeafName(const QString &argLocalzLeafName); const int defaultReceiptIndex = 0; const QString browserCmd; @@ -56,8 +63,11 @@ public: const QString lcDataDir; const QString localUserName; QString localzLeafSize; - void SetLocalzLeafSize( QString arg); - QString GetLocalzLeafSize() const { return localzLeafSize; } + void SetLocalzLeafSize(QString arg); + QString GetLocalzLeafSize() const + { + return localzLeafSize; + } const QString lprCmd; const QString netstatCmd; const QString netwBrdAddr; @@ -90,38 +100,41 @@ public: const quint16 clientHelpNotificationServerPort = 0; private: - static bool CheckPathAndComplain( const QString &argPath, const QString &argVariableName, - const QString &argMessage ); - static QVector< Client* > CreateClients( const QSettings &argSettings, - const QString &argPingCmd ); - static QMap< QString, Client* > CreateClIPsToClMap( const QVector< Client* > &argClients ); + static bool CheckPathAndComplain(const QString &argPath, + const QString &argVariableName, + const QString &argMessage); + static QVector CreateClients(const QSettings &argSettings, + const QString &argPingCmd); + static QMap CreateClIPsToClMap(const QVector &argClients); QStringList DetectInstalledLaTeXHeaders() const; QStringList DetectInstalledzTreeVersions() const; - static QStringList GetAdminUsers( const QSettings &argSettings ); - static quint16 GetClientHelpNotificationServerPort( const QSettings &argSettings ); - static int GetDefaultReceiptIndex( const QSettings &argSettings ); - static int GetInitialPort( const QSettings &argSettings ); + static QStringList GetAdminUsers(const QSettings &argSettings); + static quint16 GetClientHelpNotificationServerPort(const QSettings &argSettings); + static int GetDefaultReceiptIndex(const QSettings &argSettings); + static int GetInitialPort(const QSettings &argSettings); static QString GetLocalUserName(); - static QString ReadSettingsItem( const QString &argVariableName, - const QString &argMessage, - const QSettings &argSettings, - bool argItemIsFile ); + static QString ReadSettingsItem(const QString &argVariableName, + const QString &argMessage, + const QSettings &argSettings, + bool argItemIsFile); int chosenzTreePort = 0; - QVector< Client* > clients; + QVector< Client * > clients; QString localzLeafName; public: - const QMap< QString, Client* > clIPsToClMap; + const QMap clIPsToClMap; }; -} +} // namespace lc -inline QString lc::Settings::GetLocalzLeafName() const { +inline QString lc::Settings::GetLocalzLeafName() const +{ return localzLeafName; } -inline void lc::Settings::SetLocalzLeafName( const QString &argLocalzLeafName ) { +inline void lc::Settings::SetLocalzLeafName(const QString &argLocalzLeafName) +{ localzLeafName = argLocalzLeafName; } From 826e34f9410686407a8ca0da60d2622c5021b78e Mon Sep 17 00:00:00 2001 From: markuspg Date: Tue, 13 Mar 2018 23:08:15 +0100 Subject: [PATCH 19/30] Fix file permissions --- CHANGELOG.md | 0 Doxyfile | 0 LICENSE | 0 Labcontrol.pro | 0 PROGRAMMING.md | 0 README.md | 0 data/Labcontrol.conf | 0 data/example_header.tex | 0 data/icons/boot.png | Bin data/icons/boot.svg | 0 data/icons/down.png | Bin data/icons/down.svg | 0 data/icons/icon.png | Bin data/icons/icon.svg | 0 data/icons/off.png | Bin data/icons/off.svg | 0 data/icons/on.png | Bin data/icons/on.svg | 0 data/icons/unknown.png | Bin data/icons/unknown.svg | 0 data/icons/zLeaf.png | Bin data/icons/zLeaf.svg | 0 doc/manual.tex | 0 doc/pictures/startup_screen.png | Bin labcontrol.desktop | 0 src/helpmessagesender/HelpMessageSender.pro | 0 src/helpmessagesender/helpmessagewindow.cpp | 0 src/helpmessagesender/helpmessagewindow.h | 0 src/helpmessagesender/helpmessagewindow.ui | 0 src/helpmessagesender/main.cpp | 0 src/main.cpp | 0 src/mainwindow.cpp | 0 src/mainwindow.h | 0 src/mainwindow.ui | 0 34 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 CHANGELOG.md mode change 100755 => 100644 Doxyfile mode change 100755 => 100644 LICENSE mode change 100755 => 100644 Labcontrol.pro mode change 100755 => 100644 PROGRAMMING.md mode change 100755 => 100644 README.md mode change 100755 => 100644 data/Labcontrol.conf mode change 100755 => 100644 data/example_header.tex mode change 100755 => 100644 data/icons/boot.png mode change 100755 => 100644 data/icons/boot.svg mode change 100755 => 100644 data/icons/down.png mode change 100755 => 100644 data/icons/down.svg mode change 100755 => 100644 data/icons/icon.png mode change 100755 => 100644 data/icons/icon.svg mode change 100755 => 100644 data/icons/off.png mode change 100755 => 100644 data/icons/off.svg mode change 100755 => 100644 data/icons/on.png mode change 100755 => 100644 data/icons/on.svg mode change 100755 => 100644 data/icons/unknown.png mode change 100755 => 100644 data/icons/unknown.svg mode change 100755 => 100644 data/icons/zLeaf.png mode change 100755 => 100644 data/icons/zLeaf.svg mode change 100755 => 100644 doc/manual.tex mode change 100755 => 100644 doc/pictures/startup_screen.png mode change 100755 => 100644 labcontrol.desktop mode change 100755 => 100644 src/helpmessagesender/HelpMessageSender.pro mode change 100755 => 100644 src/helpmessagesender/helpmessagewindow.cpp mode change 100755 => 100644 src/helpmessagesender/helpmessagewindow.h mode change 100755 => 100644 src/helpmessagesender/helpmessagewindow.ui mode change 100755 => 100644 src/helpmessagesender/main.cpp mode change 100755 => 100644 src/main.cpp mode change 100755 => 100644 src/mainwindow.cpp mode change 100755 => 100644 src/mainwindow.h mode change 100755 => 100644 src/mainwindow.ui diff --git a/CHANGELOG.md b/CHANGELOG.md old mode 100755 new mode 100644 diff --git a/Doxyfile b/Doxyfile old mode 100755 new mode 100644 diff --git a/LICENSE b/LICENSE old mode 100755 new mode 100644 diff --git a/Labcontrol.pro b/Labcontrol.pro old mode 100755 new mode 100644 diff --git a/PROGRAMMING.md b/PROGRAMMING.md old mode 100755 new mode 100644 diff --git a/README.md b/README.md old mode 100755 new mode 100644 diff --git a/data/Labcontrol.conf b/data/Labcontrol.conf old mode 100755 new mode 100644 diff --git a/data/example_header.tex b/data/example_header.tex old mode 100755 new mode 100644 diff --git a/data/icons/boot.png b/data/icons/boot.png old mode 100755 new mode 100644 diff --git a/data/icons/boot.svg b/data/icons/boot.svg old mode 100755 new mode 100644 diff --git a/data/icons/down.png b/data/icons/down.png old mode 100755 new mode 100644 diff --git a/data/icons/down.svg b/data/icons/down.svg old mode 100755 new mode 100644 diff --git a/data/icons/icon.png b/data/icons/icon.png old mode 100755 new mode 100644 diff --git a/data/icons/icon.svg b/data/icons/icon.svg old mode 100755 new mode 100644 diff --git a/data/icons/off.png b/data/icons/off.png old mode 100755 new mode 100644 diff --git a/data/icons/off.svg b/data/icons/off.svg old mode 100755 new mode 100644 diff --git a/data/icons/on.png b/data/icons/on.png old mode 100755 new mode 100644 diff --git a/data/icons/on.svg b/data/icons/on.svg old mode 100755 new mode 100644 diff --git a/data/icons/unknown.png b/data/icons/unknown.png old mode 100755 new mode 100644 diff --git a/data/icons/unknown.svg b/data/icons/unknown.svg old mode 100755 new mode 100644 diff --git a/data/icons/zLeaf.png b/data/icons/zLeaf.png old mode 100755 new mode 100644 diff --git a/data/icons/zLeaf.svg b/data/icons/zLeaf.svg old mode 100755 new mode 100644 diff --git a/doc/manual.tex b/doc/manual.tex old mode 100755 new mode 100644 diff --git a/doc/pictures/startup_screen.png b/doc/pictures/startup_screen.png old mode 100755 new mode 100644 diff --git a/labcontrol.desktop b/labcontrol.desktop old mode 100755 new mode 100644 diff --git a/src/helpmessagesender/HelpMessageSender.pro b/src/helpmessagesender/HelpMessageSender.pro old mode 100755 new mode 100644 diff --git a/src/helpmessagesender/helpmessagewindow.cpp b/src/helpmessagesender/helpmessagewindow.cpp old mode 100755 new mode 100644 diff --git a/src/helpmessagesender/helpmessagewindow.h b/src/helpmessagesender/helpmessagewindow.h old mode 100755 new mode 100644 diff --git a/src/helpmessagesender/helpmessagewindow.ui b/src/helpmessagesender/helpmessagewindow.ui old mode 100755 new mode 100644 diff --git a/src/helpmessagesender/main.cpp b/src/helpmessagesender/main.cpp old mode 100755 new mode 100644 diff --git a/src/main.cpp b/src/main.cpp old mode 100755 new mode 100644 diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp old mode 100755 new mode 100644 diff --git a/src/mainwindow.h b/src/mainwindow.h old mode 100755 new mode 100644 diff --git a/src/mainwindow.ui b/src/mainwindow.ui old mode 100755 new mode 100644 From 9704e65a0669444c072bb71178641cd6ed411a2b Mon Sep 17 00:00:00 2001 From: markuspg Date: Thu, 15 Mar 2018 00:02:16 +0100 Subject: [PATCH 20/30] Began getting rid of global "settings" variable --- src/Lib/clienthelpnotificationserver.cpp | 8 +- src/Lib/clienthelpnotificationserver.h | 6 +- src/Lib/lablib.cpp | 11 +- src/Lib/lablib.h | 5 +- src/Lib/receipts_handler.cpp | 15 +- src/Lib/receipts_handler.h | 9 +- src/Lib/receiptsprinter.cpp | 19 +- src/Lib/receiptsprinter.h | 3 + src/Lib/session.cpp | 11 +- src/Lib/session.h | 5 +- src/Lib/settings.h | 2 +- src/Lib/ztree.cpp | 8 +- src/Lib/ztree.h | 6 +- src/localzleafstarter.cpp | 6 +- src/localzleafstarter.h | 6 +- src/main.cpp | 2 +- src/mainwindow.cpp | 369 +++++++++++++---------- src/mainwindow.h | 60 ++-- src/manualprintingsetup.cpp | 13 +- src/manualprintingsetup.h | 6 +- 20 files changed, 328 insertions(+), 242 deletions(-) diff --git a/src/Lib/clienthelpnotificationserver.cpp b/src/Lib/clienthelpnotificationserver.cpp index 4b4f8b3..d18b15e 100644 --- a/src/Lib/clienthelpnotificationserver.cpp +++ b/src/Lib/clienthelpnotificationserver.cpp @@ -28,11 +28,11 @@ #include -extern std::unique_ptr settings; - -lc::ClientHelpNotificationServer::ClientHelpNotificationServer(QObject *argParent) : +lc::ClientHelpNotificationServer::ClientHelpNotificationServer(const Settings *const argSettings, + QObject *argParent) : QObject{argParent}, - hostAddress{settings->serverIP} + hostAddress{settings->serverIP}, + settings{argSettings} { QNetworkConfigurationManager manager; if (manager.capabilities() diff --git a/src/Lib/clienthelpnotificationserver.h b/src/Lib/clienthelpnotificationserver.h index c1d704c..b4516dc 100644 --- a/src/Lib/clienthelpnotificationserver.h +++ b/src/Lib/clienthelpnotificationserver.h @@ -27,17 +27,21 @@ class QTcpServer; namespace lc { +class Settings; + class ClientHelpNotificationServer : public QObject { Q_OBJECT public: - explicit ClientHelpNotificationServer(QObject *argParent = nullptr); + explicit ClientHelpNotificationServer(const Settings *const argSettings, + QObject *argParent = nullptr); private: QTcpServer *helpMessageServer = nullptr; const QHostAddress hostAddress; QNetworkSession *networkSession = nullptr; + const Settings *const settings = nullptr; private slots: void OpenSession(); diff --git a/src/Lib/lablib.cpp b/src/Lib/lablib.cpp index c4a2d54..3c4a453 100644 --- a/src/Lib/lablib.cpp +++ b/src/Lib/lablib.cpp @@ -24,10 +24,11 @@ #include "lablib.h" -lc::Lablib::Lablib(QObject *argParent) : +lc::Lablib::Lablib(Settings *const argSettings, QObject *argParent) : QObject{argParent}, labSettings{"Labcontrol", "Labcontrol", this}, - sessionsModel{new SessionsModel{this}} + sessionsModel{new SessionsModel{this}}, +settings{argSettings} { for (const auto &s : settings->GetClients()) { connect(this, &Lablib::ZLEAF_RUNNING, @@ -52,7 +53,8 @@ lc::Lablib::Lablib(QObject *argParent) : // Initialize the server for client help requests retrieval if (settings->clientHelpNotificationServerPort && !settings->serverIP.isEmpty()) { - clientHelpNotificationServer = new ClientHelpNotificationServer{this}; + clientHelpNotificationServer + = new ClientHelpNotificationServer{settings, this}; } } @@ -157,7 +159,8 @@ void lc::Lablib::StartNewSession(QVector argAssocCl, argzTreePort, argzTreeVersion, argPrintLocalReceipts, argParticipNameReplacement, - argReceiptsHeader}); + argReceiptsHeader, + settings}); occupiedPorts.append(sessionsModel->back()->zTreePort); } catch (Session::lcDataTargetPathCreationFailed) { QMessageBox::information(nullptr, tr("Chosen data target path could not be created"), diff --git a/src/Lib/lablib.h b/src/Lib/lablib.h index d7530bf..fd0070f 100644 --- a/src/Lib/lablib.h +++ b/src/Lib/lablib.h @@ -45,8 +45,6 @@ #include "sessionsmodel.h" #include "settings.h" -extern std::unique_ptr settings; - namespace lc { //! This class represents the entire lab and running sessions. @@ -62,7 +60,7 @@ public: * \brief Lablib's constructor * \param[in] argParent This 'lcLablib' instance's parent QObject */ - Lablib(QObject *argParent = nullptr); + Lablib(Settings *const argSettings, QObject *argParent = nullptr); /** Lablib's destructor */ ~Lablib() override; @@ -135,6 +133,7 @@ private: QVector< quint16 > occupiedPorts; //! A derivation from QAbstractTableModel used to store the single Session instances SessionsModel *sessionsModel = nullptr; + Settings *const settings = nullptr; }; } // namespace lc diff --git a/src/Lib/receipts_handler.cpp b/src/Lib/receipts_handler.cpp index 69120fa..0a7daf2 100644 --- a/src/Lib/receipts_handler.cpp +++ b/src/Lib/receipts_handler.cpp @@ -24,9 +24,8 @@ #include "receipts_handler.h" #include "settings.h" -extern std::unique_ptr settings; - -lc::ReceiptsHandler::ReceiptsHandler(const QString &argZTreeDataTargetPath, +lc::ReceiptsHandler::ReceiptsHandler(const Settings *const argSettings, + const QString &argZTreeDataTargetPath, bool argPrintReceiptsForLocalClients, const QString &argAnonymousReceiptsPlaceholder, const QString &argLatexHeaderName, @@ -39,6 +38,7 @@ lc::ReceiptsHandler::ReceiptsHandler(const QString &argZTreeDataTargetPath, latexHeaderName{argLatexHeaderName}, paymentFile{expectedPaymentFilePath}, printReceiptsForLocalClients{argPrintReceiptsForLocalClients}, + settings{argSettings}, timer{new QTimer{this}}, zTreeDataTargetPath{argZTreeDataTargetPath} { @@ -50,7 +50,8 @@ zTreeDataTargetPath{argZTreeDataTargetPath} timer->start(2000); } -lc::ReceiptsHandler::ReceiptsHandler(const QString &argZTreeDataTargetPath, +lc::ReceiptsHandler::ReceiptsHandler(const Settings *const argSettings, + const QString &argZTreeDataTargetPath, bool argPrintReceiptsForLocalClients, const QString &argAnonymousReceiptsPlaceholder, const QString &argLatexHeaderName, @@ -63,6 +64,7 @@ lc::ReceiptsHandler::ReceiptsHandler(const QString &argZTreeDataTargetPath, latexHeaderName{argLatexHeaderName}, paymentFile{expectedPaymentFilePath}, printReceiptsForLocalClients{argPrintReceiptsForLocalClients}, + settings{argSettings}, zTreeDataTargetPath{argZTreeDataTargetPath} { qDebug() << "Expected payment file name is:" << expectedPaymentFilePath; @@ -198,13 +200,14 @@ void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() } // Open a QTextStream to write to the file - QTextStream out(texFile); + QTextStream out{texFile}; out << *latexText; delete latexText; latexText = nullptr; - receiptsPrinter = new ReceiptsPrinter{dateString, zTreeDataTargetPath, this}; + receiptsPrinter = new ReceiptsPrinter{dateString, settings, + zTreeDataTargetPath, this}; receiptsPrinter->start(); connect(receiptsPrinter, &ReceiptsPrinter::PrintingFinished, this, &ReceiptsHandler::DeleteReceiptsPrinterInstance); diff --git a/src/Lib/receipts_handler.h b/src/Lib/receipts_handler.h index 8260103..aff2daf 100644 --- a/src/Lib/receipts_handler.h +++ b/src/Lib/receipts_handler.h @@ -42,6 +42,8 @@ struct paymentEntry_t { double payoff; }; +class Settings; + //! A class to handle receipts printing. /*! This class is element of every session and is used to handle the receipts printing. @@ -51,11 +53,13 @@ class ReceiptsHandler : public QObject Q_OBJECT public: - explicit ReceiptsHandler(const QString &argZTreeDataTargetPath, + explicit ReceiptsHandler(const Settings *const argSettings, + const QString &argZTreeDataTargetPath, bool argPrintReceiptsForLocalClients, const QString &argAnonymousReceiptsPlaceholder, const QString &argLatexHeaderName, QObject *argParent = nullptr); - explicit ReceiptsHandler(const QString &argZTreeDataTargetPath, + explicit ReceiptsHandler(const Settings *const argSettings, + const QString &argZTreeDataTargetPath, bool argPrintReceiptsForLocalClients, const QString &argAnonymousReceiptsPlaceholder, const QString &argLatexHeaderName, @@ -98,6 +102,7 @@ private: const bool printReceiptsForLocalClients; //! Creates new thread for receipts printing ReceiptsPrinter *receiptsPrinter = nullptr; + const Settings *const settings = nullptr; //! Used for regular checking if the payment file was created QTimer *timer = nullptr; //! A reference to the data target path stored in the session class instance diff --git a/src/Lib/receiptsprinter.cpp b/src/Lib/receiptsprinter.cpp index 0a1f493..6804107 100644 --- a/src/Lib/receiptsprinter.cpp +++ b/src/Lib/receiptsprinter.cpp @@ -17,25 +17,22 @@ * along with Labcontrol. If not, see . */ -#include - #include "receiptsprinter.h" #include "settings.h" -extern std::unique_ptr settings; - lc::ReceiptsPrinter::ReceiptsPrinter(const QString &argDateString, + const Settings *const argSettings, const QString &argWorkpath, QObject *argParent) : QThread{argParent}, dateString{argDateString}, - dvipsCmd{settings->dvipsCmd}, - latexCmd{settings->latexCmd}, - lprCmd{settings->lprCmd}, - postscriptViewer{ settings->postscriptViewer}, - ps2pdfCmd{settings->ps2pdfCmd}, - rmCmd{settings->rmCmd}, - vncViewer{settings->vncViewer}, + dvipsCmd{argSettings->dvipsCmd}, + latexCmd{argSettings->latexCmd}, + lprCmd{argSettings->lprCmd}, + postscriptViewer{argSettings->postscriptViewer}, + ps2pdfCmd{argSettings->ps2pdfCmd}, + rmCmd{argSettings->rmCmd}, + vncViewer{argSettings->vncViewer}, workpath{argWorkpath} { } diff --git a/src/Lib/receiptsprinter.h b/src/Lib/receiptsprinter.h index 38c46d1..5433d08 100644 --- a/src/Lib/receiptsprinter.h +++ b/src/Lib/receiptsprinter.h @@ -28,6 +28,8 @@ namespace lc { +class Settings; + //! A class for receipts creation. /*! This class is used to do the actual printing of the receipts in an own thread. @@ -151,6 +153,7 @@ class ReceiptsPrinter : public QThread } public: explicit ReceiptsPrinter(const QString &argDateString, + const Settings *const argSettings, const QString &argWorkpath, QObject *argParent = nullptr); diff --git a/src/Lib/session.cpp b/src/Lib/session.cpp index 0e757b4..4006ccf 100644 --- a/src/Lib/session.cpp +++ b/src/Lib/session.cpp @@ -24,19 +24,19 @@ #include -extern std::unique_ptr settings; - lc::Session::Session(QVector &&argAssocClients, const QString &argZTreeDataTargetPath, const quint16 argZTreePort, const QString &argZTreeVersionPath, bool argPrintReceiptsForLocalClients, const QString &argAnonymousReceiptsPlaceholder, - const QString &argLatexHeaderName, QObject *argParent): + const QString &argLatexHeaderName, + const Settings *const argSettings, QObject *argParent): QObject{argParent}, zTreePort{argZTreePort}, anonymousReceiptsPlaceholder{argAnonymousReceiptsPlaceholder}, assocClients{std::move(argAssocClients)}, latexHeaderName{argLatexHeaderName}, printReceiptsForLocalClients{argPrintReceiptsForLocalClients}, + settings{argSettings}, zTreeDataTargetPath{argZTreeDataTargetPath}, zTreeVersionPath{argZTreeVersionPath} { @@ -88,14 +88,15 @@ void lc::Session::InitializeClasses() zTreeDataTargetPath.append("/" + date_string + "-" + QString::number(zTreePort)); qDebug() << "New session's chosen_zTree_data_target_path:" << zTreeDataTargetPath; - zTreeInstance = new ZTree{zTreeDataTargetPath, zTreePort, + zTreeInstance = new ZTree{settings, zTreeDataTargetPath, zTreePort, zTreeVersionPath, this}; connect(zTreeInstance, &ZTree::ZTreeClosed, this, &Session::OnzTreeClosed); // Only create a 'Receipts_Handler' instance, if all neccessary variables were set if (latexHeaderName != "None found" && !settings->dvipsCmd.isEmpty() && !settings->latexCmd.isEmpty()) { - new ReceiptsHandler{zTreeDataTargetPath, printReceiptsForLocalClients, + new ReceiptsHandler{settings, zTreeDataTargetPath, + printReceiptsForLocalClients, anonymousReceiptsPlaceholder, latexHeaderName, this}; } else { qDebug() << "No 'ReceiptsHandler' instance was created."; diff --git a/src/Lib/session.h b/src/Lib/session.h index ed732ae..8bd278f 100644 --- a/src/Lib/session.h +++ b/src/Lib/session.h @@ -29,6 +29,7 @@ namespace lc { class Client; +class Settings; //! A class containing an entire session. /*! @@ -46,7 +47,8 @@ public: const quint16 argZTreePort, const QString &argZTreeVersionPath, bool argPrintReceiptsForLocalClients, const QString &argAnonymousReceiptsPlaceholder, - const QString &argLatexHeaderName, QObject *argParent = nullptr); + const QString &argLatexHeaderName, + const Settings *const argSettings, QObject *argParent = nullptr); ~Session() override; /*! Returns the data item with the given index @@ -78,6 +80,7 @@ private: const QString latexHeaderName; //! True if receipts shall be printed for local clients const bool printReceiptsForLocalClients = true; + const Settings *const settings; //! The path were the data of this zTree instance's session will be saved QString zTreeDataTargetPath; //! The session's zTree instance diff --git a/src/Lib/settings.h b/src/Lib/settings.h index 838313a..f34f697 100644 --- a/src/Lib/settings.h +++ b/src/Lib/settings.h @@ -45,7 +45,7 @@ public: { return chosenzTreePort; } - QVector< Client * > &GetClients() + const QVector &GetClients() const { return clients; } diff --git a/src/Lib/ztree.cpp b/src/Lib/ztree.cpp index 4c1c3e5..9369e99 100644 --- a/src/Lib/ztree.cpp +++ b/src/Lib/ztree.cpp @@ -25,11 +25,11 @@ #include -extern std::unique_ptr settings; - -lc::ZTree::ZTree(const QString &argZTreeDataTargetPath, const int argZTreePort, +lc::ZTree::ZTree(const Settings *const argSettings, + const QString &argZTreeDataTargetPath, const int argZTreePort, const QString &argZTreeVersionPath, QObject *argParent) : - QObject{argParent} + QObject{argParent}, + settings{argSettings} { QStringList arguments{QStringList{} << "-c" << "0" << settings->wineCmd << QString{settings->zTreeInstDir + "/zTree_" diff --git a/src/Lib/ztree.h b/src/Lib/ztree.h index 1684b07..9c00c56 100644 --- a/src/Lib/ztree.h +++ b/src/Lib/ztree.h @@ -26,6 +26,8 @@ namespace lc { +class Settings; + //! A class to contain running zTree instances. /*! This class is element of every session and is used to handle all zTree related data. @@ -35,7 +37,8 @@ class ZTree: public QObject Q_OBJECT public: - ZTree(const QString &argZTreeDataTargetPath, + ZTree(const Settings *const argSettings, + const QString &argZTreeDataTargetPath, const int argZTreePort, const QString &argZTreeVersionPath, QObject *argParent = nullptr); @@ -43,6 +46,7 @@ signals: void ZTreeClosed(int argExitCode); private: + const Settings *const settings = nullptr; QProcess zTreeInstance; }; diff --git a/src/localzleafstarter.cpp b/src/localzleafstarter.cpp index 9455524..bd8dc6c 100644 --- a/src/localzleafstarter.cpp +++ b/src/localzleafstarter.cpp @@ -25,10 +25,10 @@ #include -extern std::unique_ptr settings; - -lc::LocalzLeafStarter::LocalzLeafStarter(QWidget *argParent) : +lc::LocalzLeafStarter::LocalzLeafStarter(Settings *const argSettings, + QWidget *argParent) : QWidget{argParent}, + settings{argSettings}, ui{new Ui::LocalzLeafStarter} { ui->setupUi(this); diff --git a/src/localzleafstarter.h b/src/localzleafstarter.h index d8704ac..c13f7fd 100644 --- a/src/localzleafstarter.h +++ b/src/localzleafstarter.h @@ -28,12 +28,15 @@ namespace Ui { class LocalzLeafStarter; } // namespace Ui +class Settings; + class LocalzLeafStarter : public QWidget { Q_OBJECT public: - explicit LocalzLeafStarter(QWidget *argParent = nullptr); + explicit LocalzLeafStarter(Settings *const argSettings, + QWidget *argParent = nullptr); ~LocalzLeafStarter() override; signals: @@ -41,6 +44,7 @@ signals: int argzTreePort); private: + Settings *const settings = nullptr; Ui::LocalzLeafStarter *const ui = nullptr; private slots: diff --git a/src/main.cpp b/src/main.cpp index da2f43e..e00d6db 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -31,7 +31,7 @@ int main(int argc, char *argv[]) QApplication a{argc, argv}; settings = std::make_unique(QSettings{"Labcontrol", "Labcontrol"}); - lc::MainWindow w; + lc::MainWindow w{settings.get()}; w.show(); return a.exec(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index b0fb33d..c5db45f 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -17,8 +17,6 @@ * along with Labcontrol. If not, see . */ -#include - #include #include #include @@ -28,70 +26,73 @@ #include "manualprintingsetup.h" #include "Lib/settings.h" -extern std::unique_ptr< lc::Settings > settings; - -lc::MainWindow::MainWindow( QWidget *argParent ) : - QMainWindow{ argParent }, - icons( static_cast< int >( icons_t::ICON_QUANTITY ) ), - ui{ new Ui::MainWindow } +lc::MainWindow::MainWindow(Settings *const argSettings, + QWidget *argParent) : + QMainWindow{argParent}, + icons(static_cast(icons_t::ICON_QUANTITY)), + settings{argSettings}, + ui{new Ui::MainWindow} { - ui->setupUi( this ); - lablib = new Lablib{ this }; + ui->setupUi(this); + lablib = new Lablib{settings, this}; LoadIconPixmaps(); SetupWidgets(); - if ( valid_items ) { - gui_update_timer = new QTimer{ this }; + if (valid_items) { + gui_update_timer = new QTimer{this}; connect( gui_update_timer, &QTimer::timeout, this, &MainWindow::UpdateClientsTableView ); - gui_update_timer->start( 500 ); + gui_update_timer->start(500); } - /* session actions */ + /* session actions */ // Add z-Tree versions to the corresponding combo box - ui->CBzTreeVersion->addItem( tr( "Please choose a version:" ) ); - ui->CBzTreeVersion->addItems( settings->installedZTreeVersions ); + ui->CBzTreeVersion->addItem(tr("Please choose a version:")); + ui->CBzTreeVersion->addItems(settings->installedZTreeVersions); // Add default path to the corresponding combo box - ui->CBDataTargetPath->addItem( tr( "Set a new path HERE" ) ); - ui->CBDataTargetPath->addItem( QDir::homePath() ); - ui->CBDataTargetPath->addItem( QDir::homePath() + "/zTreeData" ); - ui->CBDataTargetPath->setCurrentIndex( 2 ); - connect( this, &MainWindow::RequestNewDataTargetPath, - this, &MainWindow::GetNewDataTargetPath ); - - if ( settings->dvipsCmd.isEmpty() || settings->latexCmd.isEmpty() - || settings->lcDataDir.isEmpty() || settings->lprCmd.isEmpty() - || settings->postscriptViewer.isEmpty() || settings->ps2pdfCmd.isEmpty() - || settings->rmCmd.isEmpty() || settings->vncViewer.isEmpty() ) { - QMessageBox::information( this, tr( "Receipts printing will not work" ), - tr( "Some component essential for receipts creation and" - " printing is missing. No receipts will be created or" - " printed." ), QMessageBox::Ok ); + ui->CBDataTargetPath->addItem(tr("Set a new path HERE")); + ui->CBDataTargetPath->addItem(QDir::homePath()); + ui->CBDataTargetPath->addItem(QDir::homePath() + "/zTreeData"); + ui->CBDataTargetPath->setCurrentIndex(2); + connect(this, &MainWindow::RequestNewDataTargetPath, + this, &MainWindow::GetNewDataTargetPath); + + if (settings->dvipsCmd.isEmpty() || settings->latexCmd.isEmpty() + || settings->lcDataDir.isEmpty() || settings->lprCmd.isEmpty() + || settings->postscriptViewer.isEmpty() || settings->ps2pdfCmd.isEmpty() + || settings->rmCmd.isEmpty() || settings->vncViewer.isEmpty()) { + QMessageBox::information(this, tr("Receipts printing will not work"), + tr("Some component essential for receipts creation and" + " printing is missing. No receipts will be created or" + " printed."), QMessageBox::Ok); } else { - ui->CBReceiptsHeader->addItems( settings->installedLaTeXHeaders ); + ui->CBReceiptsHeader->addItems(settings->installedLaTeXHeaders); - if ( settings->defaultReceiptIndex - && settings->defaultReceiptIndex < ui->CBReceiptsHeader->count() ) { - ui->CBReceiptsHeader->setCurrentIndex( settings->defaultReceiptIndex ); + if (settings->defaultReceiptIndex + && settings->defaultReceiptIndex < ui->CBReceiptsHeader->count()) { + ui->CBReceiptsHeader->setCurrentIndex(settings->defaultReceiptIndex); } } } -lc::MainWindow::~MainWindow() { +lc::MainWindow::~MainWindow() +{ delete ui; delete valid_items; } -bool lc::MainWindow::CheckIfUserIsAdmin() { - if ( settings->localUserName.isEmpty() ) { - QMessageBox messageBox{ QMessageBox::Warning, tr( "User not detectable" ), - tr( "Your user name could not be queryed. The admin tab will be" - " disabled. You won't be able to perform administrative" - " actions but can conduct experiments normally." ), - QMessageBox::Ok }; +bool lc::MainWindow::CheckIfUserIsAdmin() +{ + if (settings->localUserName.isEmpty()) { + QMessageBox messageBox{QMessageBox::Warning, tr("User not detectable"), + tr("Your user name could not be queryed. The" + " admin tab will be disabled. You won't be" + " able to perform administrative actions" + " but can conduct experiments normally."), + QMessageBox::Ok}; messageBox.exec(); return false; } @@ -101,7 +102,8 @@ bool lc::MainWindow::CheckIfUserIsAdmin() { return lablib->CheckIfUserIsAdmin(); } -void lc::MainWindow::DisableDisfunctionalWidgets() { +void lc::MainWindow::DisableDisfunctionalWidgets() +{ const QStringList &zTreeEntries = settings->installedZTreeVersions; if ( zTreeEntries.isEmpty() ) { ui->CBClientNames->setEnabled( false ); @@ -145,13 +147,13 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { // Disable 'PBShowORSEE', if 'orsee_command' was not set if ( settings->browserCmd.isEmpty() - || settings->orseeUrl.isEmpty() ) { + || settings->orseeUrl.isEmpty() ) { ui->PBShowORSEE->setEnabled( false ); } // Disable all widgets needless if 'public_key_path_user' or 'user_name_on_clients' was not set if ( settings->pkeyPathUser.isEmpty() - || settings->userNameOnClients.isEmpty() ) { + || settings->userNameOnClients.isEmpty() ) { ui->CBClientNames->setEnabled( false ); ui->LEFilePath->setEnabled( false ); ui->L_FakeName->setEnabled( false ); @@ -172,7 +174,7 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { } if ( settings->pkeyPathRoot.isEmpty() - && settings->pkeyPathUser.isEmpty() ) { + && settings->pkeyPathUser.isEmpty() ) { ui->GBExecuteOnEveryClient->setEnabled( false ); ui->GBOptionsForAdminActions->setEnabled( false ); ui->PBOpenTerminal->setEnabled( false ); @@ -234,7 +236,7 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { // Deactivate the webcam choosing interface if no webcams are available or the viewer is missing if ( settings->webcamDisplayCmd.isEmpty() - || settings->webcams.isEmpty() ) { + || settings->webcams.isEmpty() ) { ui->CBWebcamChooser->setEnabled( false ); ui->L_WebcamChooser->setEnabled( false ); } @@ -258,18 +260,19 @@ void lc::MainWindow::DisableDisfunctionalWidgets() { } } -void lc::MainWindow::LoadIconPixmaps() { +void lc::MainWindow::LoadIconPixmaps() +{ if ( settings->lcDataDir.isEmpty() ) { return; } const QStringList iconNames{ QStringList{} - << "unknown.png" - << "off.png" - << "down.png" - << "boot.png" - << "on.png" - << "zLeaf.png" }; + << "unknown.png" + << "off.png" + << "down.png" + << "boot.png" + << "on.png" + << "zLeaf.png" }; for ( int i = 0; i < ( int )icons_t::ICON_QUANTITY; i++ ) { if ( !icons[ i ].load( settings->lcDataDir + "/icons/" + iconNames[ i ] ) ) { @@ -280,7 +283,8 @@ void lc::MainWindow::LoadIconPixmaps() { } } -void lc::MainWindow::on_PBKillLocalzLeaf_clicked() { +void lc::MainWindow::on_PBKillLocalzLeaf_clicked() +{ QString program{ settings->killallCmd }; QStringList arguments; arguments << "-I" << "-q" << "zleaf.exe"; @@ -297,21 +301,24 @@ void lc::MainWindow::on_PBKillLocalzLeaf_clicked() { qDebug() << program << arguments; } -void lc::MainWindow::on_PBPrintPaymentFileManually_clicked() { - ManualPrintingSetup *manPrint = new ManualPrintingSetup{ this }; - manPrint->setWindowFlags( Qt::Window ); +void lc::MainWindow::on_PBPrintPaymentFileManually_clicked() +{ + ManualPrintingSetup *manPrint = new ManualPrintingSetup{settings, this}; + manPrint->setWindowFlags(Qt::Window); manPrint->show(); - connect( manPrint, SIGNAL( destroyed( QObject* ) ), - manPrint, SLOT( deleteLater() ) ); - connect( manPrint, &ManualPrintingSetup::RequestReceiptsHandler, - this, &MainWindow::StartReceiptsHandler ); + connect(manPrint, SIGNAL(destroyed(QObject *)), + manPrint, SLOT(deleteLater())); + connect(manPrint, &ManualPrintingSetup::RequestReceiptsHandler, + this, &MainWindow::StartReceiptsHandler); } -void lc::MainWindow::on_PBRunzLeaf_clicked() { +void lc::MainWindow::on_PBRunzLeaf_clicked() +{ // Check if more than one client is selected and issue a warning message if so unsigned short int numberOfSelectedClients = 0; QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { ++numberOfSelectedClients; } @@ -321,10 +328,11 @@ void lc::MainWindow::on_PBRunzLeaf_clicked() { QMessageBox messageBox{ QMessageBox::Information, tr( "Too many clients selected" ), tr( "There are too many clients selected in the table view on the left. Please select only one." ), QMessageBox::Ok, this }; messageBox.exec(); } else { - const QString * const fakeName = new QString{ ui->CBClientNames->currentText() }; - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + const QString *const fakeName = new QString{ ui->CBClientNames->currentText() }; + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->StartZLeaf( fakeName ); } } @@ -332,13 +340,15 @@ void lc::MainWindow::on_PBRunzLeaf_clicked() { } } -void lc::MainWindow::on_RBUseLocalUser_toggled(bool checked) { +void lc::MainWindow::on_RBUseLocalUser_toggled(bool checked) +{ if ( checked ) { qDebug() << "'RBUseLocalUser' got toggled."; } } -void lc::MainWindow::SetupWidgets() { +void lc::MainWindow::SetupWidgets() +{ // Fill the 'CBClientNames' with possible client names and the 'TVClients' with the clients if ( !settings->GetClients().isEmpty() ) { valid_items = new QVector< QStandardItem * >; @@ -370,7 +380,7 @@ void lc::MainWindow::SetupWidgets() { valid_items->squeeze(); } else { QMessageBox messageBox{ QMessageBox::Warning, tr( "Could not construct clients view" ), - tr( "The creation of the clients view failed. Please check the file '/etc/xdg/Labcontrol/Labcontrol.conf'." ), QMessageBox::Ok, this }; + tr( "The creation of the clients view failed. Please check the file '/etc/xdg/Labcontrol/Labcontrol.conf'." ), QMessageBox::Ok, this }; messageBox.exec(); ui->CBClientNames->setEnabled( false ); ui->GBClientActions->setEnabled( false ); @@ -443,21 +453,26 @@ void lc::MainWindow::SetupWidgets() { "along with Labcontrol. If not, see .\n\n\n" ); } -void lc::MainWindow::StartReceiptsHandler( QString argzTreeDataTargetPath, - bool argReceiptsForLocalClients, - QString argAnonymousReceiptsPlaceholder, - QString argLatexHeaderName, QString argDateString) { - ReceiptsHandler *recHand = new ReceiptsHandler{ argzTreeDataTargetPath, - argReceiptsForLocalClients, - argAnonymousReceiptsPlaceholder, - argLatexHeaderName, argDateString, this }; - connect( recHand, &ReceiptsHandler::PrintingFinished, - recHand, &ReceiptsHandler::deleteLater ); +void lc::MainWindow::StartReceiptsHandler(QString argzTreeDataTargetPath, + bool argReceiptsForLocalClients, + QString argAnonymousReceiptsPlaceholder, + QString argLatexHeaderName, + QString argDateString) +{ + const auto recHand = new ReceiptsHandler{settings, argzTreeDataTargetPath, + argReceiptsForLocalClients, + argAnonymousReceiptsPlaceholder, + argLatexHeaderName, + argDateString, this}; + connect(recHand, &ReceiptsHandler::PrintingFinished, + recHand, &ReceiptsHandler::deleteLater); } -void lc::MainWindow::UpdateClientsTableView() { +void lc::MainWindow::UpdateClientsTableView() +{ for ( auto s : *valid_items ) { - state_t state = static_cast< Client* >( s->data( Qt::UserRole ).value() )->GetClientState(); + state_t state = static_cast< Client * >( s->data( + Qt::UserRole ).value() )->GetClientState(); switch ( state ) { case state_t::RESPONDING: s->setBackground( QBrush( QColor( 128, 255, 128, 255 ) ) ); @@ -489,89 +504,103 @@ void lc::MainWindow::UpdateClientsTableView() { /* Experiment tab functions */ -void lc::MainWindow::on_PBBoot_clicked() { +void lc::MainWindow::on_PBBoot_clicked() +{ QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->Boot(); } } } -void lc::MainWindow::on_PBChooseFile_clicked() { +void lc::MainWindow::on_PBChooseFile_clicked() +{ QFileDialog *file_dialog = new QFileDialog{ this, tr( "Choose a file to beam" ), QDir::homePath() }; file_dialog->setFileMode( QFileDialog::Directory ); file_dialog->setOption( QFileDialog::DontUseNativeDialog, true ); file_dialog->setOption( QFileDialog::ReadOnly, true ); file_dialog->setOption( QFileDialog::ShowDirsOnly, true ); - if(file_dialog->exec()) { + if (file_dialog->exec()) { ui->LEFilePath->setText(file_dialog->selectedFiles().at(0)); qDebug() << "Chose file" << ui->LEFilePath->text() << "for beaming."; - } - else { + } else { ui->LEFilePath->setText( tr( "File choosing cancelled" ) ); qDebug() << "File choosing cancelled"; } delete file_dialog; } -void lc::MainWindow::on_PBBeamFile_clicked() { +void lc::MainWindow::on_PBBeamFile_clicked() +{ QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); const QString fileToBeam{ ui->LEFilePath->text() }; - if(fileToBeam == ""){ + if (fileToBeam == "") { QMessageBox::information(this, "Upload failed", "You didn't choose any folder to upload."); } else { - //Iterate over the selected clients to upload the file - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { - if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); - client->BeamFile( fileToBeam, &settings->pkeyPathUser, &settings->userNameOnClients ); + //Iterate over the selected clients to upload the file + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); + ++it ) { + if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); + client->BeamFile( fileToBeam, &settings->pkeyPathUser, &settings->userNameOnClients ); + } } - } - // Inform the user about the path - QMessageBox::information(this, "Upload completed", "The folder was copied to all selected clients.\nThe path on every client is /home/ewfuser/media4ztree" + fileToBeam.mid(fileToBeam.lastIndexOf('/')) +".\nDon't forget to adjust the media path within zTree!"); + // Inform the user about the path + QMessageBox::information(this, "Upload completed", + "The folder was copied to all selected clients.\nThe path on every client is /home/ewfuser/media4ztree" + + fileToBeam.mid(fileToBeam.lastIndexOf('/')) + + ".\nDon't forget to adjust the media path within zTree!"); } } -void lc::MainWindow::on_PBShowORSEE_clicked() { +void lc::MainWindow::on_PBShowORSEE_clicked() +{ lablib->ShowOrsee(); } -void lc::MainWindow::on_PBShowPreprints_clicked() { +void lc::MainWindow::on_PBShowPreprints_clicked() +{ lablib->ShowPreprints(); } -void lc::MainWindow::on_PBShutdown_clicked() { +void lc::MainWindow::on_PBShutdown_clicked() +{ // Confirmation dialog QMessageBox::StandardButton reply; - reply = QMessageBox::question(this, "Confirm", "Really shutdown the selected clients?", QMessageBox::Yes|QMessageBox::No); + reply = QMessageBox::question(this, "Confirm", "Really shutdown the selected clients?", + QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); // Do not shut down the server itself - if ( client->name == "self"){ - QMessageBox::information(NULL, "Shutdown canceled", "It is not allowed to shutdown the server itself via labcontrol!"); + if ( client->name == "self") { + QMessageBox::information(NULL, "Shutdown canceled", + "It is not allowed to shutdown the server itself via labcontrol!"); } else { client->Shutdown(); } } } } else { - qDebug() << "Canceled shutting down the selected clients"; + qDebug() << "Canceled shutting down the selected clients"; } } -void lc::MainWindow::on_CBWebcamChooser_activated( int argIndex ) { +void lc::MainWindow::on_CBWebcamChooser_activated( int argIndex ) +{ if ( argIndex != 0 ) { QString program{ settings->webcamDisplayCmd }; QStringList arguments; // Attention argIndex is NOT 0-based - arguments << settings->webcams[argIndex-1]; + arguments << settings->webcams[argIndex - 1]; qDebug() << "Webcam" << arguments << "will be opened"; QProcess showWebcamProcess; @@ -586,9 +615,10 @@ void lc::MainWindow::on_PBstartBrowser_clicked() QString argURL = ui->LEURL->text(); bool argFullscreen = ui->CBFullscreen->checkState(); QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->StartClientBrowser( &argURL, &argFullscreen ); } } @@ -598,12 +628,14 @@ void lc::MainWindow::on_PBstopBrowser_clicked() { // Confirmation dialog QMessageBox::StandardButton reply; - reply = QMessageBox::question(this, "Confirm", "Really kill all selected browser instances?", QMessageBox::Yes|QMessageBox::No); + reply = QMessageBox::question(this, "Confirm", "Really kill all selected browser instances?", + QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->StopClientBrowser( ); } } @@ -616,9 +648,10 @@ void lc::MainWindow::on_PBstopBrowser_clicked() void lc::MainWindow::on_PBViewDesktopViewOnly_clicked() { QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->ShowDesktopViewOnly(); } } @@ -628,9 +661,10 @@ void lc::MainWindow::on_PBViewDesktopViewOnly_clicked() void lc::MainWindow::on_PBViewDesktopFullControl_clicked() { QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activatedItems.cbegin(); it != activatedItems.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->ShowDesktopFullControl(); } } @@ -638,18 +672,21 @@ void lc::MainWindow::on_PBViewDesktopFullControl_clicked() /* Session tab functions */ -void lc::MainWindow::on_PBStartzLeaf_clicked() { +void lc::MainWindow::on_PBStartzLeaf_clicked() +{ QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->StartZLeaf( nullptr, ui->LEzLeafCommandline->text() ); } } } -void lc::MainWindow::on_PBStartLocalzLeaf_clicked() { - LocalzLeafStarter *localzLeafStarter = new LocalzLeafStarter{ this }; +void lc::MainWindow::on_PBStartLocalzLeaf_clicked() +{ + LocalzLeafStarter *localzLeafStarter = new LocalzLeafStarter{settings, this}; localzLeafStarter->setWindowFlags( Qt::Window ); localzLeafStarter->show(); connect( localzLeafStarter, &LocalzLeafStarter::LocalzLeafRequested, @@ -659,9 +696,10 @@ void lc::MainWindow::on_PBStartLocalzLeaf_clicked() { } void lc::MainWindow::StartLocalzLeaf( QString argzLeafName, QString argzLeafVersion, - int argzTreePort ) { + int argzTreePort ) +{ if ( settings->tasksetCmd.isEmpty() || settings->wineCmd.isEmpty() - || settings->zTreeInstDir.isEmpty() ) { + || settings->zTreeInstDir.isEmpty() ) { return; } @@ -673,7 +711,7 @@ void lc::MainWindow::StartLocalzLeaf( QString argzLeafName, QString argzLeafVers << "/server" << "127.0.0.1" << "/channel" << QString::number( argzTreePort - 7000 ) << "/name" << argzLeafName; if ( !settings->localzLeafSize.isEmpty() ) { - arguments << "/size" << QString{ settings->localzLeafSize }; + arguments << "/size" << QString{ settings->localzLeafSize }; } qDebug() << "Start local zLeaf:" << arguments; @@ -687,7 +725,8 @@ void lc::MainWindow::on_PBStopZtree_clicked() arguments << "-I" << "-q" << "ztree.exe"; // Confirmation dialog QMessageBox::StandardButton reply; - reply = QMessageBox::question(this, "Confirm", "Really kill all z-Tree instances?", QMessageBox::Yes|QMessageBox::No); + reply = QMessageBox::question(this, "Confirm", "Really kill all z-Tree instances?", + QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { // Kill all z-Tree processes QProcess killLocalzLeafProc; @@ -704,11 +743,11 @@ void lc::MainWindow::on_PBStopZtree_clicked() void lc::MainWindow::on_PBRecoverCrashedSession_clicked() { // TODO: Implement the functionality of the restore session script in here (no zenity script) - QProcess startProc; - startProc.setProcessEnvironment( QProcessEnvironment::systemEnvironment() ); - if ( !settings->restartCrashedSessionScript.isEmpty() ) { - startProc.startDetached( settings->restartCrashedSessionScript); - } + QProcess startProc; + startProc.setProcessEnvironment( QProcessEnvironment::systemEnvironment() ); + if ( !settings->restartCrashedSessionScript.isEmpty() ) { + startProc.startDetached( settings->restartCrashedSessionScript); + } } void lc::MainWindow::on_CBDataTargetPath_activated( int argIndex ) @@ -721,7 +760,8 @@ void lc::MainWindow::on_CBDataTargetPath_activated( int argIndex ) } // Open a folder chooser dialog for zTree data path -void lc::MainWindow::GetNewDataTargetPath() { +void lc::MainWindow::GetNewDataTargetPath() +{ QFileDialog fileDialog{ this }; fileDialog.setFileMode( QFileDialog::Directory ); fileDialog.setDirectory( QDir::homePath() ); @@ -749,7 +789,8 @@ void lc::MainWindow::on_ChBPrintanonymousreceipts_clicked() } // Start session button actions -void lc::MainWindow::on_PBStartSession_clicked() { +void lc::MainWindow::on_PBStartSession_clicked() +{ if ( ui->CBzTreeVersion->currentIndex() == 0 ) { QMessageBox::information( this, tr( "No z-Tree version chosen" ), @@ -759,7 +800,7 @@ void lc::MainWindow::on_PBStartSession_clicked() { } const QModelIndexList activatedItems = ui->TVClients->selectionModel()->selectedIndexes(); - if( !ui->ChBSessionWithoutAttachedClients->isChecked() ) { + if ( !ui->ChBSessionWithoutAttachedClients->isChecked() ) { if ( !activatedItems.length() ) { QMessageBox::information( this, tr( "Canceled, no clients were chosen" ), tr( "The start of a new session was canceled.\n" @@ -775,10 +816,10 @@ void lc::MainWindow::on_PBStartSession_clicked() { anonymousReceiptsPlaceholder = ui->CBReplaceParticipantNames->currentText(); } - QVector< Client* > associatedClients; + QVector< Client * > associatedClients; for ( auto cit = activatedItems.cbegin(); cit != activatedItems.cend(); ++cit ) { if ( ( *cit ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *cit ).data( Qt::UserRole ).value< void* >() ); + Client *client = static_cast< Client * >( ( *cit ).data( Qt::UserRole ).value< void * >() ); client->SetSessionPort( ui->SBPort->value() ); client->SetzLeafVersion( ui->CBzTreeVersion->currentText() ); associatedClients.append( client ); @@ -786,21 +827,22 @@ void lc::MainWindow::on_PBStartSession_clicked() { } this->lablib->StartNewSession ( associatedClients, anonymousReceiptsPlaceholder, - ui->ChBReceiptsForLocalClients->isChecked(), - ui->CBReceiptsHeader->currentText(), - ui->CBDataTargetPath->currentText(), - static_cast< quint16 >( ui->SBPort->value() ), - ui->CBzTreeVersion->currentText() ); + ui->ChBReceiptsForLocalClients->isChecked(), + ui->CBReceiptsHeader->currentText(), + ui->CBDataTargetPath->currentText(), + static_cast< quint16 >( ui->SBPort->value() ), + ui->CBzTreeVersion->currentText() ); //Display the command line - QString cmd = this->lablib->getzLeafArgs( ui->SBPort->value(), ui->CBzTreeVersion->currentText()).join(" "); + QString cmd = this->lablib->getzLeafArgs( ui->SBPort->value(), + ui->CBzTreeVersion->currentText()).join(" "); ui->LEzLeafCommandline->setText(cmd); //Start z-Leaf on selected clients if checkbox is activated - if( ui->ChBautoStartClientZleaf->isChecked() ) { + if ( ui->ChBautoStartClientZleaf->isChecked() ) { for ( auto cit = activatedItems.cbegin(); cit != activatedItems.cend(); ++cit ) { if ( ( *cit ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *cit ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *cit ).data( Qt::UserRole ).value< void * >() ); client->StartZLeaf( nullptr, cmd ); } } @@ -816,9 +858,10 @@ void lc::MainWindow::on_PBStartSession_clicked() { void lc::MainWindow::on_PBKillzLeaf_clicked() { QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->KillZLeaf(); } } @@ -826,9 +869,10 @@ void lc::MainWindow::on_PBKillzLeaf_clicked() /* Admin tab functions */ -void lc::MainWindow::on_PBOpenFilesystem_clicked() { +void lc::MainWindow::on_PBOpenFilesystem_clicked() +{ // Determine the correct user to be used - QString * userToBeUsed = nullptr; + QString *userToBeUsed = nullptr; if ( ui->RBUseUserRoot->isChecked() ) { userToBeUsed = new QString{ "root" }; } else { @@ -836,16 +880,18 @@ void lc::MainWindow::on_PBOpenFilesystem_clicked() { } QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->OpenFilesystem( userToBeUsed ); } } delete userToBeUsed; } -void lc::MainWindow::on_PBExecute_clicked() { +void lc::MainWindow::on_PBExecute_clicked() +{ // Get the command to be executed ... QString command = ui->CBCommandToExecute->currentText(); @@ -860,9 +906,10 @@ void lc::MainWindow::on_PBExecute_clicked() { qDebug() << "Executing command" << command << " on chosen clients."; QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->OpenTerminal( command, ui->RBUseUserRoot->isChecked() ); } } @@ -870,7 +917,8 @@ void lc::MainWindow::on_PBExecute_clicked() { } // Issue open terminal call -void lc::MainWindow::on_PBOpenTerminal_clicked() { +void lc::MainWindow::on_PBOpenTerminal_clicked() +{ QString pkeyPathUser; if ( ui->RBUseUserRoot->isChecked() ) { pkeyPathUser = settings->pkeyPathRoot; @@ -878,9 +926,10 @@ void lc::MainWindow::on_PBOpenTerminal_clicked() { pkeyPathUser = settings->pkeyPathUser; } QModelIndexList activated_items = ui->TVClients->selectionModel()->selectedIndexes(); - for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); ++it ) { + for ( QModelIndexList::ConstIterator it = activated_items.cbegin(); it != activated_items.cend(); + ++it ) { if ( ( *it ).data( Qt::DisplayRole ).type() != 0 ) { - Client *client = static_cast< Client* >( ( *it ).data( Qt::UserRole ).value< void * >() ); + Client *client = static_cast< Client * >( ( *it ).data( Qt::UserRole ).value< void * >() ); client->OpenTerminal( QString{}, ui->RBUseUserRoot->isChecked() ); } } diff --git a/src/mainwindow.h b/src/mainwindow.h index 154afef..b0753a6 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 Markus Prasser + * Copyright 2014-2018 Markus Prasser, Tobias Weiss * * This file is part of Labcontrol. * @@ -43,16 +43,20 @@ namespace Ui { class MainWindow; } +class Settings; + //! The class containing the graphical user interface. /*! This class represents the graphical user interface and all connected functionality. */ -class MainWindow : public QMainWindow { +class MainWindow : public QMainWindow +{ Q_OBJECT public: - explicit MainWindow( QWidget *argParent = nullptr ); - ~MainWindow(); + explicit MainWindow(Settings *const argSettings, + QWidget *argParent = nullptr); + ~MainWindow() override; private slots: void on_CBWebcamChooser_activated(int index); @@ -85,10 +89,10 @@ private slots: signals: /*Session actions*/ void RequestNewDataTargetPath(); - void RequestNewSession( QVector< Client* > argAssocCl, QString argParticipNameReplacement, - bool argPrintLocalReceipts, QString argReceiptsHeader, - QString argzTreeDataTargetPath, quint16 argzTreePort, - QString argzTreeVersion ); + void RequestNewSession(QVector argAssocCl, QString argParticipNameReplacement, + bool argPrintLocalReceipts, QString argReceiptsHeader, + QString argzTreeDataTargetPath, quint16 argzTreePort, + QString argzTreeVersion); private: //! Checks, if the user has administrative rights @@ -103,21 +107,31 @@ private: //! Sets up all used widgets void SetupWidgets(); - QStandardItemModel *clients_view_model = nullptr; //! The view storing all clients data - QTimer *gui_update_timer = nullptr; //! A QTimer triggering updates of the graphical user interface - QVector< QPixmap > icons; //! Vector of pixmaps storing the icons indicating the clients' statuses - Lablib *lablib = nullptr; //! Accumulator of all program logic being accessed by the GUI - bool localzLeavesAreRunning = false; //! Stores if a local z-Leaf instance is running on the server ('true' if local z-Leaf exists) - QButtonGroup *userChooseButtonGroup = nullptr; //! Used to group the radio buttons choosing which user shall be used for administrative client actions - Ui::MainWindow *ui = nullptr; //! Pointer storing all GUI items - QVector *valid_items = nullptr; //! Stores all valid Client instances displayed by the table view, its main use is as iterable object for 'update_clients_table_view()' + //! The view storing all clients data + QStandardItemModel *clients_view_model = nullptr; + //! A QTimer triggering updates of the graphical user interface + QTimer *gui_update_timer = nullptr; + //! Vector of pixmaps storing the icons indicating the clients' statuses + QVector icons; + //! Accumulator of all program logic being accessed by the GUI + Lablib *lablib = nullptr; + //! Stores if a local z-Leaf instance is running on the server ('true' if local z-Leaf exists) + bool localzLeavesAreRunning = false; + Settings *const settings = nullptr; + //! Used to group the radio buttons choosing which user shall be used for administrative client actions + QButtonGroup *userChooseButtonGroup = nullptr; + //! Pointer storing all GUI items + Ui::MainWindow *const ui = nullptr; + //! Stores all valid Client instances displayed by the table view, its main use is as iterable object for 'update_clients_table_view()' + QVector *valid_items = nullptr; private slots: - void StartReceiptsHandler( QString argzTreeDataTargetPath, - bool argReceiptsForLocalClients, - QString argAnonymousReceiptsPlaceholder, - QString argLatexHeaderName, - QString argDateString ); + void StartReceiptsHandler(QString argzTreeDataTargetPath, + bool argReceiptsForLocalClients, + QString argAnonymousReceiptsPlaceholder, + QString argLatexHeaderName, + QString argDateString + ); void on_PBstartBrowser_clicked(); void on_PBstopBrowser_clicked(); @@ -125,12 +139,12 @@ private slots: void on_PBStopZtree_clicked(); void on_PBRecoverCrashedSession_clicked(); void GetNewDataTargetPath(); - void on_CBDataTargetPath_activated( int argIndex ); + void on_CBDataTargetPath_activated(int argIndex); void on_CBReceiptsHeader_activated(int argIndex); void on_ChBPrintanonymousreceipts_clicked(); void on_PBKillzLeaf_clicked(); }; -} +} // namespace lc #endif // MAINWINDOW_H diff --git a/src/manualprintingsetup.cpp b/src/manualprintingsetup.cpp index 30ed20c..f143199 100644 --- a/src/manualprintingsetup.cpp +++ b/src/manualprintingsetup.cpp @@ -17,13 +17,6 @@ * along with Labcontrol. If not, see . */ -/* #include "manualprintingsetup.h" -#include "ui_manualprintingsetup.h" -#include "Lib/settings.h" - -#include - */ - #include "manualprintingsetup.h" #include "ui_manualprintingsetup.h" #include "Lib/settings.h" @@ -33,10 +26,10 @@ #include -extern std::unique_ptr settings; - -lc::ManualPrintingSetup::ManualPrintingSetup(QWidget *argParent) : +lc::ManualPrintingSetup::ManualPrintingSetup(const Settings *const argSettings, + QWidget *argParent) : QWidget{argParent}, + settings{argSettings}, ui{new Ui::ManualPrintingSetup} { ui->setupUi(this); diff --git a/src/manualprintingsetup.h b/src/manualprintingsetup.h index 3561983..b4de0d5 100644 --- a/src/manualprintingsetup.h +++ b/src/manualprintingsetup.h @@ -28,12 +28,15 @@ namespace Ui { class ManualPrintingSetup; } // namespace Ui +class Settings; + class ManualPrintingSetup : public QWidget { Q_OBJECT public: - explicit ManualPrintingSetup(QWidget *argParent = nullptr); + explicit ManualPrintingSetup(const Settings *const argSettings, + QWidget *argParent = nullptr); ~ManualPrintingSetup() override; signals: @@ -45,6 +48,7 @@ signals: private: QString dateString; + const Settings *const settings = nullptr; Ui::ManualPrintingSetup *const ui = nullptr; QString workPath; From d663ec6aeb02be3368e18b839a9889a523e3e950 Mon Sep 17 00:00:00 2001 From: markuspg Date: Sat, 17 Mar 2018 12:39:15 +0100 Subject: [PATCH 21/30] Got entirely rid of global variables --- src/Lib/client.cpp | 12 ++++++------ src/Lib/client.h | 3 +++ src/Lib/clienthelpnotificationserver.cpp | 2 -- src/Lib/lablib.h | 3 +-- src/Lib/receipts_handler.cpp | 2 -- src/Lib/session.cpp | 2 -- src/Lib/settings.cpp | 12 +++++++----- src/Lib/settings.h | 8 ++++---- src/Lib/ztree.cpp | 2 -- src/localzleafstarter.cpp | 2 -- src/main.cpp | 9 ++------- src/manualprintingsetup.cpp | 2 -- 12 files changed, 23 insertions(+), 36 deletions(-) diff --git a/src/Lib/client.cpp b/src/Lib/client.cpp index bc83671..2adf1b6 100644 --- a/src/Lib/client.cpp +++ b/src/Lib/client.cpp @@ -18,14 +18,13 @@ */ #include "clientpinger.h" -#include "lablib.h" +#include "settings.h" -#include - -extern std::unique_ptr settings; -extern std::unique_ptr lablib; +#include +#include lc::Client::Client(const QString &argIP, const QString &argMAC, const QString &argName, + const Settings *const argSettings, const unsigned short int argXPosition, const unsigned short int argYPosition, const QString &argPingCmd): @@ -34,7 +33,8 @@ lc::Client::Client(const QString &argIP, const QString &argMAC, const QString &a name{argName}, xPosition{argXPosition}, yPosition{argYPosition}, - protectedCycles{0} + protectedCycles{0}, + settings{argSettings} { qRegisterMetaType("state_t"); diff --git a/src/Lib/client.h b/src/Lib/client.h index d4b0278..2cc9228 100644 --- a/src/Lib/client.h +++ b/src/Lib/client.h @@ -29,6 +29,7 @@ class QTimer; namespace lc { class ClientPinger; +class Settings; //! Class which represents the clients in the lab /*! @@ -58,6 +59,7 @@ public: * \param argYPosition The client's y coordinate in the lab's grid */ Client(const QString &argIP, const QString &argMAC, const QString &argName, + const Settings *const argSettings, const unsigned short int argXPosition, const unsigned short int argYPosition, const QString &argPingCmd); @@ -148,6 +150,7 @@ private: unsigned short int protectedCycles; ClientPinger *pinger = nullptr; QThread pingerThread; + const Settings *const settings = nullptr; state_t state = state_t::UNINITIALIZED; //! QTimer used to trigger pings by pinger's ClientPinger instance QTimer *pingTimer = nullptr; diff --git a/src/Lib/clienthelpnotificationserver.cpp b/src/Lib/clienthelpnotificationserver.cpp index d18b15e..b6d5eed 100644 --- a/src/Lib/clienthelpnotificationserver.cpp +++ b/src/Lib/clienthelpnotificationserver.cpp @@ -26,8 +26,6 @@ #include #include -#include - lc::ClientHelpNotificationServer::ClientHelpNotificationServer(const Settings *const argSettings, QObject *argParent) : QObject{argParent}, diff --git a/src/Lib/lablib.h b/src/Lib/lablib.h index fd0070f..1f6efe2 100644 --- a/src/Lib/lablib.h +++ b/src/Lib/lablib.h @@ -21,7 +21,6 @@ #define LABLIB_H #include -#include #include #include @@ -130,7 +129,7 @@ private: QThread netstatThread; //! A timer for regular execution of the NetstatAgent instance's request mechanism QTimer *netstatTimer = nullptr; - QVector< quint16 > occupiedPorts; + QVector occupiedPorts; //! A derivation from QAbstractTableModel used to store the single Session instances SessionsModel *sessionsModel = nullptr; Settings *const settings = nullptr; diff --git a/src/Lib/receipts_handler.cpp b/src/Lib/receipts_handler.cpp index 0a7daf2..ebd5676 100644 --- a/src/Lib/receipts_handler.cpp +++ b/src/Lib/receipts_handler.cpp @@ -17,8 +17,6 @@ * along with Labcontrol. If not, see . */ -#include - #include #include "receipts_handler.h" diff --git a/src/Lib/session.cpp b/src/Lib/session.cpp index 4006ccf..2838b02 100644 --- a/src/Lib/session.cpp +++ b/src/Lib/session.cpp @@ -22,8 +22,6 @@ #include -#include - lc::Session::Session(QVector &&argAssocClients, const QString &argZTreeDataTargetPath, const quint16 argZTreePort, const QString &argZTreeVersionPath, bool argPrintReceiptsForLocalClients, diff --git a/src/Lib/settings.cpp b/src/Lib/settings.cpp index 12fdd64..4e0a9e0 100644 --- a/src/Lib/settings.cpp +++ b/src/Lib/settings.cpp @@ -134,12 +134,12 @@ lc::Settings::Settings(const QSettings &argSettings, QObject *argParent) : installedZTreeVersions{DetectInstalledzTreeVersions()}, clientHelpNotificationServerPort{GetClientHelpNotificationServerPort(argSettings)}, chosenzTreePort{GetInitialPort(argSettings)}, - clients{CreateClients(argSettings, pingCmd)}, localzLeafName{ReadSettingsItem("local_zLeaf_name", "The local zLeaf default name will default to 'local'.", - argSettings, false)}, - clIPsToClMap{CreateClIPsToClMap(clients)} + argSettings, false)} { + clients = CreateClients(argSettings, pingCmd); + clIPsToClMap = CreateClIPsToClMap(clients); // Let the local zLeaf name default to 'local' if none was given in the settings if (localzLeafName.isEmpty()) { qDebug() << "'local_zLeaf_name' was not set, defaulting to 'local'"; @@ -241,9 +241,11 @@ QVector lc::Settings::CreateClients(const QSettings &argSettings, qDebug() << "clientYPositions:" << clientYPositions.join(" / "); for (int i = 0; i < clientQuantity; i++) { - tempClientVec.append(new Client{clientIPs[i], clientMACs[i], clientNames[i], + tempClientVec.append(new Client{clientIPs[i], clientMACs[i], + clientNames[i], this, clientXPositions[i].toUShort(), - clientYPositions[i].toUShort(), argPingCmd}); + clientYPositions[i].toUShort(), + argPingCmd}); } return tempClientVec; diff --git a/src/Lib/settings.h b/src/Lib/settings.h index f34f697..2688d84 100644 --- a/src/Lib/settings.h +++ b/src/Lib/settings.h @@ -103,8 +103,8 @@ private: static bool CheckPathAndComplain(const QString &argPath, const QString &argVariableName, const QString &argMessage); - static QVector CreateClients(const QSettings &argSettings, - const QString &argPingCmd); + QVector CreateClients(const QSettings &argSettings, + const QString &argPingCmd); static QMap CreateClIPsToClMap(const QVector &argClients); QStringList DetectInstalledLaTeXHeaders() const; QStringList DetectInstalledzTreeVersions() const; @@ -119,11 +119,11 @@ private: bool argItemIsFile); int chosenzTreePort = 0; - QVector< Client * > clients; + QVector clients; QString localzLeafName; public: - const QMap clIPsToClMap; + QMap clIPsToClMap; }; } // namespace lc diff --git a/src/Lib/ztree.cpp b/src/Lib/ztree.cpp index 9369e99..5581a34 100644 --- a/src/Lib/ztree.cpp +++ b/src/Lib/ztree.cpp @@ -23,8 +23,6 @@ #include #include -#include - lc::ZTree::ZTree(const Settings *const argSettings, const QString &argZTreeDataTargetPath, const int argZTreePort, const QString &argZTreeVersionPath, QObject *argParent) : diff --git a/src/localzleafstarter.cpp b/src/localzleafstarter.cpp index bd8dc6c..cf8fc57 100644 --- a/src/localzleafstarter.cpp +++ b/src/localzleafstarter.cpp @@ -23,8 +23,6 @@ #include -#include - lc::LocalzLeafStarter::LocalzLeafStarter(Settings *const argSettings, QWidget *argParent) : QWidget{argParent}, diff --git a/src/main.cpp b/src/main.cpp index e00d6db..e9f9fa9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -22,16 +22,11 @@ #include -#include - -std::unique_ptr settings; - int main(int argc, char *argv[]) { QApplication a{argc, argv}; - settings = std::make_unique(QSettings{"Labcontrol", - "Labcontrol"}); - lc::MainWindow w{settings.get()}; + lc::Settings settings{QSettings{"Labcontrol", "Labcontrol"}}; + lc::MainWindow w{&settings}; w.show(); return a.exec(); diff --git a/src/manualprintingsetup.cpp b/src/manualprintingsetup.cpp index f143199..a560a72 100644 --- a/src/manualprintingsetup.cpp +++ b/src/manualprintingsetup.cpp @@ -24,8 +24,6 @@ #include #include -#include - lc::ManualPrintingSetup::ManualPrintingSetup(const Settings *const argSettings, QWidget *argParent) : QWidget{argParent}, From 9d304905e3107abcf89b640b8ec7030d6f87f12a Mon Sep 17 00:00:00 2001 From: markuspg Date: Fri, 20 Apr 2018 00:13:23 +0200 Subject: [PATCH 22/30] Minor Settings clean-ups --- src/Lib/client.cpp | 15 +++--- src/Lib/clienthelpnotificationserver.cpp | 1 + src/Lib/session.cpp | 1 + src/Lib/settings.cpp | 16 ++----- src/Lib/settings.h | 58 +++++++++++++++--------- src/main.cpp | 3 ++ src/mainwindow.cpp | 16 +++---- 7 files changed, 59 insertions(+), 51 deletions(-) diff --git a/src/Lib/client.cpp b/src/Lib/client.cpp index 2adf1b6..814b8b0 100644 --- a/src/Lib/client.cpp +++ b/src/Lib/client.cpp @@ -17,6 +17,7 @@ * along with Labcontrol. If not, see . */ +#include "client.h" #include "clientpinger.h" #include "settings.h" @@ -36,8 +37,6 @@ lc::Client::Client(const QString &argIP, const QString &argMAC, const QString &a protectedCycles{0}, settings{argSettings} { - qRegisterMetaType("state_t"); - if (!argPingCmd.isEmpty()) { pinger = new ClientPinger{ip, argPingCmd}; pinger->moveToThread(&pingerThread); @@ -79,8 +78,8 @@ void lc::Client::BeamFile(const QString &argFileToBeam, } const QStringList arguments{"-2", "-i", *argPublickeyPathUser, "-l", - "32768", "-r", argFileToBeam, - QString{*argUserNameOnClients + "@" + ip + ":media4ztree"}}; + "32768", "-r", argFileToBeam, + QString{*argUserNameOnClients + "@" + ip + ":media4ztree"}}; // Start the process QProcess beamFileProcess; @@ -126,8 +125,8 @@ void lc::Client::GotStatusChanged(state_t argState) void lc::Client::KillZLeaf() { const QStringList arguments{"-i", settings->pkeyPathUser, - QString{settings->userNameOnClients + "@" + ip}, - settings->killallCmd, "-I", "-q", "zleaf.exe"}; + QString{settings->userNameOnClients + "@" + ip}, + settings->killallCmd, "-I", "-q", "zleaf.exe"}; // Start the process QProcess killZLeafProcess; @@ -237,8 +236,8 @@ void lc::Client::Shutdown() return; } const QStringList arguments{"-i", settings->pkeyPathUser, - QString{settings->userNameOnClients + "@" + ip}, - "sudo shutdown -P now"}; + QString{settings->userNameOnClients + "@" + ip}, + "sudo shutdown -P now"}; // Start the process QProcess shutdownProcess; diff --git a/src/Lib/clienthelpnotificationserver.cpp b/src/Lib/clienthelpnotificationserver.cpp index b6d5eed..bba144f 100644 --- a/src/Lib/clienthelpnotificationserver.cpp +++ b/src/Lib/clienthelpnotificationserver.cpp @@ -17,6 +17,7 @@ * along with Labcontrol. If not, see . */ +#include "client.h" #include "clienthelpnotificationserver.h" #include "settings.h" diff --git a/src/Lib/session.cpp b/src/Lib/session.cpp index 2838b02..98fdd72 100644 --- a/src/Lib/session.cpp +++ b/src/Lib/session.cpp @@ -17,6 +17,7 @@ * along with Labcontrol. If not, see . */ +#include "client.h" #include "session.h" #include "settings.h" diff --git a/src/Lib/settings.cpp b/src/Lib/settings.cpp index 4e0a9e0..065c159 100644 --- a/src/Lib/settings.cpp +++ b/src/Lib/settings.cpp @@ -50,9 +50,6 @@ lc::Settings::Settings(const QSettings &argSettings, QObject *argParent) : "Datapath not set. Labcontrol will missbehave with high propability.", argSettings, true)}, localUserName{GetLocalUserName()}, - localzLeafSize{ReadSettingsItem("local_zLeaf_size", - "Resolution of local zLeaf window", - argSettings, false)}, lprCmd{ReadSettingsItem("lpr_command", "Receipts printing will not work.", argSettings, true)}, @@ -136,6 +133,9 @@ lc::Settings::Settings(const QSettings &argSettings, QObject *argParent) : chosenzTreePort{GetInitialPort(argSettings)}, localzLeafName{ReadSettingsItem("local_zLeaf_name", "The local zLeaf default name will default to 'local'.", + argSettings, false)}, + localzLeafSize{ReadSettingsItem("local_zLeaf_size", + "Resolution of local zLeaf window", argSettings, false)} { clients = CreateClients(argSettings, pingCmd); @@ -395,13 +395,3 @@ QString lc::Settings::ReadSettingsItem(const QString &argVariableName, } return QString{}; } - -void lc::Settings::SetLocalzLeafSize(QString arg) -{ - localzLeafSize = arg; -} - -void lc::Settings::SetChosenZTreePort(const int argPort) -{ - chosenzTreePort = argPort; -} diff --git a/src/Lib/settings.h b/src/Lib/settings.h index 2688d84..c556fca 100644 --- a/src/Lib/settings.h +++ b/src/Lib/settings.h @@ -24,10 +24,10 @@ #include #include -#include "client.h" - namespace lc { +class Client; + class Settings : public QObject { Q_OBJECT @@ -39,35 +39,26 @@ public: Settings &operator=(const Settings &argSettings) = delete; Settings(Settings &&argSettings ) = delete; Settings &operator=(Settings &&argSettings) = delete; - ~Settings(); - - int GetChosenZTreePort() const - { - return chosenzTreePort; - } - const QVector &GetClients() const - { - return clients; - } + ~Settings() override; + + int GetChosenZTreePort() const noexcept; + const QVector &GetClients() const; QString GetLocalzLeafName() const; - void SetChosenZTreePort(const int argPort); + QString GetLocalzLeafSize() const; + void SetChosenZTreePort(const int argPort) noexcept; void SetLocalzLeafName(const QString &argLocalzLeafName); + void SetLocalzLeafSize(const QString &argSize); const int defaultReceiptIndex = 0; const QString browserCmd; const QString clientBrowserCmd; + QMap clIPsToClMap; const QString dvipsCmd; const QString fileMngr; const QString killallCmd; const QString latexCmd; const QString lcDataDir; const QString localUserName; - QString localzLeafSize; - void SetLocalzLeafSize(QString arg); - QString GetLocalzLeafSize() const - { - return localzLeafSize; - } const QString lprCmd; const QString netstatCmd; const QString netwBrdAddr; @@ -121,21 +112,44 @@ private: int chosenzTreePort = 0; QVector clients; QString localzLeafName; - -public: - QMap clIPsToClMap; + QString localzLeafSize; }; } // namespace lc +inline int lc::Settings::GetChosenZTreePort() const noexcept +{ + return chosenzTreePort; +} + +inline const QVector &lc::Settings::GetClients() const +{ + return clients; +} + inline QString lc::Settings::GetLocalzLeafName() const { return localzLeafName; } +inline QString lc::Settings::GetLocalzLeafSize() const +{ + return localzLeafSize; +} + +inline void lc::Settings::SetChosenZTreePort(const int argPort) noexcept +{ + chosenzTreePort = argPort; +} + inline void lc::Settings::SetLocalzLeafName(const QString &argLocalzLeafName) { localzLeafName = argLocalzLeafName; } +inline void lc::Settings::SetLocalzLeafSize(const QString &argSize) +{ + localzLeafSize = argSize; +} + #endif // SETTINGS_H diff --git a/src/main.cpp b/src/main.cpp index e9f9fa9..9be497f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -18,12 +18,15 @@ */ #include "mainwindow.h" +#include "Lib/client.h" #include "Lib/settings.h" #include int main(int argc, char *argv[]) { + qRegisterMetaType(); + QApplication a{argc, argv}; lc::Settings settings{QSettings{"Labcontrol", "Labcontrol"}}; lc::MainWindow w{&settings}; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index c5db45f..f51fde3 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -267,12 +267,12 @@ void lc::MainWindow::LoadIconPixmaps() } const QStringList iconNames{ QStringList{} - << "unknown.png" - << "off.png" - << "down.png" - << "boot.png" - << "on.png" - << "zLeaf.png" }; + << "unknown.png" + << "off.png" + << "down.png" + << "boot.png" + << "on.png" + << "zLeaf.png" }; for ( int i = 0; i < ( int )icons_t::ICON_QUANTITY; i++ ) { if ( !icons[ i ].load( settings->lcDataDir + "/icons/" + iconNames[ i ] ) ) { @@ -710,8 +710,8 @@ void lc::MainWindow::StartLocalzLeaf( QString argzLeafName, QString argzLeafVers << QString{ settings->zTreeInstDir + "/zTree_" + argzLeafVersion + "/zleaf.exe" } << "/server" << "127.0.0.1" << "/channel" << QString::number( argzTreePort - 7000 ) << "/name" << argzLeafName; - if ( !settings->localzLeafSize.isEmpty() ) { - arguments << "/size" << QString{ settings->localzLeafSize }; + if (!settings->GetLocalzLeafSize().isEmpty()) { + arguments << "/size" << settings->GetLocalzLeafSize(); } qDebug() << "Start local zLeaf:" << arguments; From 256f10712e605c4883a265df9953d0ba39701f21 Mon Sep 17 00:00:00 2001 From: markuspg Date: Sat, 27 Oct 2018 20:55:42 +0200 Subject: [PATCH 23/30] Rename state_t to EState and move it into Client --- Labcontrol.pro | 1 - src/Lib/client.cpp | 34 +++++++++++++++--------------- src/Lib/client.h | 29 +++++++++++++++++++++----- src/Lib/clientpinger.cpp | 10 ++++----- src/Lib/clientpinger.h | 6 +++--- src/Lib/global.h | 44 --------------------------------------- src/Lib/lablib.h | 1 - src/Lib/receiptsprinter.h | 2 -- src/Lib/ztree.h | 2 -- src/main.cpp | 2 +- src/mainwindow.cpp | 17 ++++++++------- 11 files changed, 59 insertions(+), 89 deletions(-) delete mode 100644 src/Lib/global.h diff --git a/Labcontrol.pro b/Labcontrol.pro index 0fb2715..49d2c5f 100644 --- a/Labcontrol.pro +++ b/Labcontrol.pro @@ -26,7 +26,6 @@ HEADERS += src/localzleafstarter.h \ src/Lib/client.h \ src/Lib/clienthelpnotificationserver.h \ src/Lib/clientpinger.h \ - src/Lib/global.h \ src/Lib/lablib.h \ src/Lib/netstatagent.h \ src/Lib/receipts_handler.h \ diff --git a/src/Lib/client.cpp b/src/Lib/client.cpp index 814b8b0..dadfcf2 100644 --- a/src/Lib/client.cpp +++ b/src/Lib/client.cpp @@ -73,7 +73,7 @@ void lc::Client::BeamFile(const QString &argFileToBeam, const QString *const argPublickeyPathUser, const QString *const argUserNameOnClients) { - if (state < state_t::RESPONDING) { + if (state < EState::RESPONDING) { return; } @@ -104,17 +104,17 @@ void lc::Client::Boot() pingTimer->start(3000); protectedCycles = 7; - GotStatusChanged(state_t::BOOTING); + GotStatusChanged(EState::BOOTING); } -void lc::Client::GotStatusChanged(state_t argState) +void lc::Client::GotStatusChanged(EState argState) { - if ((protectedCycles > 0) && (state == state_t::BOOTING) - && (argState != state_t::RESPONDING)) { + if ((protectedCycles > 0) && (state == EState::BOOTING) + && (argState != EState::RESPONDING)) { return; } - if ((protectedCycles > 0) && (state == state_t::SHUTTING_DOWN) - && argState != state_t::NOT_RESPONDING) { + if ((protectedCycles > 0) && (state == EState::SHUTTING_DOWN) + && argState != EState::NOT_RESPONDING) { return; } state = argState; @@ -142,7 +142,7 @@ void lc::Client::KillZLeaf() void lc::Client::OpenFilesystem(const QString *const argUserToBeUsed) { - if (state < state_t::RESPONDING) { + if (state < EState::RESPONDING) { return; } const QStringList arguments{QString{ "sftp://" + *argUserToBeUsed + "@" + ip }}; @@ -157,7 +157,7 @@ void lc::Client::OpenTerminal(const QString &argCommand, const bool argOpenAsRoot) { if (!settings->termEmulCmd.isEmpty()) { - if (state < state_t::RESPONDING) { + if (state < EState::RESPONDING) { return; } @@ -196,11 +196,11 @@ void lc::Client::SetStateToZLEAF_RUNNING(const QString &argClientIP) if ( argClientIP != ip ) { return; } - if (state != state_t::ZLEAF_RUNNING) { + if (state != EState::ZLEAF_RUNNING) { pingTimer->stop(); // Inform the ClientPinger instance, that zLeaf is now running pinger->setStateToZLEAF_RUNNING(); - this->GotStatusChanged(state_t::ZLEAF_RUNNING); + this->GotStatusChanged(EState::ZLEAF_RUNNING); qDebug() << "Client" << name << "got 'ZLEAF_RUNNING' signal."; } } @@ -231,8 +231,8 @@ void lc::Client::ShowDesktopFullControl() void lc::Client::Shutdown() { - if (state == state_t::NOT_RESPONDING || state == state_t::BOOTING - || state == state_t::SHUTTING_DOWN) { + if (state == EState::NOT_RESPONDING || state == EState::BOOTING + || state == EState::SHUTTING_DOWN) { return; } const QStringList arguments{"-i", settings->pkeyPathUser, @@ -251,12 +251,12 @@ void lc::Client::Shutdown() pingTimer->start(3000); protectedCycles = 3; - GotStatusChanged(state_t::SHUTTING_DOWN); + GotStatusChanged(EState::SHUTTING_DOWN); } void lc::Client::StartZLeaf(const QString *argFakeName, QString cmd) { - if (state < state_t::RESPONDING + if (state < EState::RESPONDING || zLeafVersion.isEmpty() || GetSessionPort() < 7000) { return; @@ -264,7 +264,7 @@ void lc::Client::StartZLeaf(const QString *argFakeName, QString cmd) // Create a QMessageBox for user interaction if there is already a zLeaf running std::unique_ptr messageBoxRunningZLeafFound; - if (state == state_t::ZLEAF_RUNNING) { + if (state == EState::ZLEAF_RUNNING) { messageBoxRunningZLeafFound.reset(new QMessageBox{QMessageBox::Warning, "Running zLeaf found", QString{"There is already a zLeaf running on " + name + "."}, QMessageBox::No | QMessageBox::Yes}); @@ -277,7 +277,7 @@ void lc::Client::StartZLeaf(const QString *argFakeName, QString cmd) if ((messageBoxRunningZLeafFound.get() != nullptr && messageBoxRunningZLeafFound->clickedButton() == messageBoxRunningZLeafFound->button(QMessageBox::Yes)) - || state != state_t::ZLEAF_RUNNING) { + || state != EState::ZLEAF_RUNNING) { QStringList arguments; if (argFakeName == nullptr) { arguments << "-i" << settings->pkeyPathUser diff --git a/src/Lib/client.h b/src/Lib/client.h index 2cc9228..635fb5a 100644 --- a/src/Lib/client.h +++ b/src/Lib/client.h @@ -20,8 +20,7 @@ #ifndef CLIENT_H #define CLIENT_H -#include "global.h" - +#include #include class QTimer; @@ -39,6 +38,26 @@ class Client : public QObject { Q_OBJECT +public: + enum class EState : unsigned short { + //! The client's state is not yet defined (should only occur directly after client creation) + UNINITIALIZED = 1 << 0, + + //! The client is booting but not yet responding + BOOTING = 1 << 1, + //! An error occurred determining the client's state + ERROR = 1 << 2, + //! The client is not responding to pings + NOT_RESPONDING = 1 << 3, + //! The client is shutting down but not yet stopped responding + SHUTTING_DOWN = 1 << 4, + //! The client is responding to pings + RESPONDING = 1 << 5, + //! The client is running a zLeaf + ZLEAF_RUNNING = 1 << 6, + }; + Q_ENUM(EState) + public slots: //! Sets the STATE of the client to 'ZLEAF_RUNNING' void SetStateToZLEAF_RUNNING(const QString &argClientIP); @@ -85,7 +104,7 @@ public: /*! @return The current state of the client */ - state_t GetClientState() const + EState GetClientState() const { return state; } @@ -151,14 +170,14 @@ private: ClientPinger *pinger = nullptr; QThread pingerThread; const Settings *const settings = nullptr; - state_t state = state_t::UNINITIALIZED; + EState state = EState::UNINITIALIZED; //! QTimer used to trigger pings by pinger's ClientPinger instance QTimer *pingTimer = nullptr; int sessionPort = 0; QString zLeafVersion; private slots: - void GotStatusChanged(const state_t argState); + void GotStatusChanged(const EState argState); void RequestAPing(); signals: diff --git a/src/Lib/clientpinger.cpp b/src/Lib/clientpinger.cpp index 8f4a9d6..3120a21 100644 --- a/src/Lib/clientpinger.cpp +++ b/src/Lib/clientpinger.cpp @@ -35,18 +35,18 @@ lc::ClientPinger::ClientPinger(const QString &argIP, void lc::ClientPinger::doPing() { // Initialize the new state to be queried - state_t newState = state_t::UNINITIALIZED; + Client::EState newState = Client::EState::UNINITIALIZED; // Query the current state of the client pingProcess->start(pingCommand, pingArguments); if (!pingProcess->waitForFinished(2500) || pingProcess->exitStatus() != QProcess::NormalExit) - newState = state_t::ERROR; + newState = Client::EState::ERROR; else { if (pingProcess->exitCode() == 0) { - newState = state_t::RESPONDING; + newState = Client::EState::RESPONDING; } else { - newState = state_t::NOT_RESPONDING; + newState = Client::EState::NOT_RESPONDING; } } @@ -58,5 +58,5 @@ void lc::ClientPinger::doPing() void lc::ClientPinger::setStateToZLEAF_RUNNING() { - state = state_t::ZLEAF_RUNNING; + state = Client::EState::ZLEAF_RUNNING; } diff --git a/src/Lib/clientpinger.h b/src/Lib/clientpinger.h index 30b14eb..d0bc7b1 100644 --- a/src/Lib/clientpinger.h +++ b/src/Lib/clientpinger.h @@ -20,7 +20,7 @@ #ifndef CLIENTPINGER_H #define CLIENTPINGER_H -#include "global.h" +#include "client.h" #include #include @@ -63,12 +63,12 @@ private: //! The 'ping' process which will be executed on every call of 'do_ping()' std::unique_ptr pingProcess; //! Stores the current state of the client - state_t state = state_t::UNINITIALIZED; + Client::EState state = Client::EState::UNINITIALIZED; signals: //! This signal was just implemented for testing purposes //! This signal is emitted if the ping finished and the state of the client changed - void PingFinished(state_t state); + void PingFinished(Client::EState state); }; } // namespace lc diff --git a/src/Lib/global.h b/src/Lib/global.h deleted file mode 100644 index 7f834bd..0000000 --- a/src/Lib/global.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2014-2018 Markus Prasser, Tobias Weiss - * - * This file is part of Labcontrol. - * - * Labcontrol is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Labcontrol is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Labcontrol. If not, see . - */ - -#ifndef GLOBAL_H -#define GLOBAL_H - -#include - -//! Opens a terminal for the client -enum class state_t : unsigned short int { - //! The client is booting but not yet responding - BOOTING = 1 << 0, - //! An error occurred determining the client's state - ERROR = 1 << 1, - //! The client is not responding to pings - NOT_RESPONDING = 1 << 2, - //! The client is shutting down but not yet stopped responding - SHUTTING_DOWN = 1 << 3, - //! The client's state is not yet defined (should only occur directly after client creation) - UNINITIALIZED = 1 << 4, - //! The client is responding to pings - RESPONDING = 1 << 5, - //! The client is running a zLeaf - ZLEAF_RUNNING = 1 << 6, -}; -Q_DECLARE_METATYPE(state_t) - -#endif // GLOBAL_H diff --git a/src/Lib/lablib.h b/src/Lib/lablib.h index 1f6efe2..82ee60b 100644 --- a/src/Lib/lablib.h +++ b/src/Lib/lablib.h @@ -38,7 +38,6 @@ #include "client.h" #include "clienthelpnotificationserver.h" -#include "global.h" #include "netstatagent.h" #include "session.h" #include "sessionsmodel.h" diff --git a/src/Lib/receiptsprinter.h b/src/Lib/receiptsprinter.h index 5433d08..5c9a526 100644 --- a/src/Lib/receiptsprinter.h +++ b/src/Lib/receiptsprinter.h @@ -24,8 +24,6 @@ #include #include -#include "global.h" - namespace lc { class Settings; diff --git a/src/Lib/ztree.h b/src/Lib/ztree.h index 9c00c56..056c326 100644 --- a/src/Lib/ztree.h +++ b/src/Lib/ztree.h @@ -20,8 +20,6 @@ #ifndef ZTREE_H #define ZTREE_H -#include "global.h" - #include namespace lc { diff --git a/src/main.cpp b/src/main.cpp index 9be497f..dffffff 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -25,7 +25,7 @@ int main(int argc, char *argv[]) { - qRegisterMetaType(); + qRegisterMetaType(); QApplication a{argc, argv}; lc::Settings settings{QSettings{"Labcontrol", "Labcontrol"}}; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f51fde3..d594bfa 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -17,6 +17,7 @@ * along with Labcontrol. If not, see . */ +#include #include #include #include @@ -471,31 +472,31 @@ void lc::MainWindow::StartReceiptsHandler(QString argzTreeDataTargetPath, void lc::MainWindow::UpdateClientsTableView() { for ( auto s : *valid_items ) { - state_t state = static_cast< Client * >( s->data( + lc::Client::EState state = static_cast< Client * >( s->data( Qt::UserRole ).value() )->GetClientState(); switch ( state ) { - case state_t::RESPONDING: + case Client::EState::RESPONDING: s->setBackground( QBrush( QColor( 128, 255, 128, 255 ) ) ); s->setIcon( icons[ ( int )icons_t::ON ] ); break; - case state_t::NOT_RESPONDING: + case lc::Client::EState::NOT_RESPONDING: s->setBackground( QBrush( QColor( 255, 255, 128, 255 ) ) ); s->setIcon( icons[ ( int )icons_t::OFF ] ); break; - case state_t::BOOTING: + case Client::EState::BOOTING: s->setBackground( QBrush( QColor( 128, 128, 255, 255 ) ) ); s->setIcon( icons[ ( int )icons_t::BOOT ] ); break; - case state_t::SHUTTING_DOWN: + case Client::EState::SHUTTING_DOWN: s->setBackground( QBrush( QColor( 128, 128, 255, 255 ) ) ); s->setIcon( icons[ ( int )icons_t::DOWN ] ); break; - case state_t::ZLEAF_RUNNING: + case Client::EState::ZLEAF_RUNNING: s->setBackground( QBrush( QColor( 0, 255, 0, 255 ) ) ); s->setIcon( icons[ ( int )icons_t::ZLEAF ] ); break; - case state_t::UNINITIALIZED: - case state_t::ERROR: + case Client::EState::UNINITIALIZED: + case Client::EState::ERROR: s->setBackground( QBrush( QColor( 255, 128, 128, 255 ) ) ); break; } From f46056847f445d0e185249a4dc6f572c8e3f93fd Mon Sep 17 00:00:00 2001 From: markuspg Date: Sat, 17 Nov 2018 12:55:21 +0100 Subject: [PATCH 24/30] Add CMakeLists.txt to support CMake buildsystem --- CMakeLists.txt | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..a16c422 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.12.3 FATAL_ERROR) +project(Labcontrol CXX) + +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTOUIC ON) +set(CMAKE_CXX_STANDARD 14) + +find_package(Qt5 COMPONENTS Core Network Widgets REQUIRED) +set(labcontrol_srcs + src/localzleafstarter.cpp + src/main.cpp + src/mainwindow.cpp + src/manualprintingsetup.cpp + src/Lib/client.cpp + src/Lib/clientpinger.cpp + src/Lib/netstatagent.cpp + src/Lib/receiptsprinter.cpp + src/Lib/sessionsmodel.cpp + src/Lib/ztree.cpp + src/Lib/clienthelpnotificationserver.cpp + src/Lib/lablib.cpp + src/Lib/receipts_handler.cpp + src/Lib/session.cpp + src/Lib/settings.cpp) +add_executable(labcontrol ${labcontrol_srcs}) +target_link_libraries(labcontrol Qt5::Core Qt5::Network Qt5::Widgets) From f423daf50c005dc5ded8fd6284a559cf8d003e3d Mon Sep 17 00:00:00 2001 From: markuspg Date: Sat, 17 Nov 2018 13:17:06 +0100 Subject: [PATCH 25/30] Add HelpMessageSender to the project --- CMakeLists.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index a16c422..c05309c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,6 +6,13 @@ set(CMAKE_AUTOUIC ON) set(CMAKE_CXX_STANDARD 14) find_package(Qt5 COMPONENTS Core Network Widgets REQUIRED) + +set(helpmessagesender_srcs + src/helpmessagesender/helpmessagewindow.cpp + src/helpmessagesender/main.cpp) +add_executable(lc-helpmessagesender ${helpmessagesender_srcs}) +target_link_libraries(lc-helpmessagesender Qt5::Core Qt5::Network Qt5::Widgets) + set(labcontrol_srcs src/localzleafstarter.cpp src/main.cpp From bc345ff4d375915bce868a0e5525f60f31af7b5f Mon Sep 17 00:00:00 2001 From: markuspg Date: Sat, 17 Nov 2018 13:30:35 +0100 Subject: [PATCH 26/30] Reformat HelpMessageSender --- src/helpmessagesender/helpmessagewindow.cpp | 100 ++++++++++++-------- src/helpmessagesender/helpmessagewindow.h | 8 +- src/helpmessagesender/main.cpp | 10 +- 3 files changed, 69 insertions(+), 49 deletions(-) diff --git a/src/helpmessagesender/helpmessagewindow.cpp b/src/helpmessagesender/helpmessagewindow.cpp index fc11fa4..9a8300a 100644 --- a/src/helpmessagesender/helpmessagewindow.cpp +++ b/src/helpmessagesender/helpmessagewindow.cpp @@ -2,35 +2,42 @@ #include -lcHelpMessageWindow::lcHelpMessageWindow( const QString &argServerIP, const unsigned short int &argServerPort, QWidget *argParent ) : - QMainWindow{ argParent }, - helpMessageSocket { new QTcpSocket{ this } }, - serverPort{ argServerPort }, - serverAddress{ argServerIP }, - ui{ new Ui::HelpMessageWindow } +lcHelpMessageWindow::lcHelpMessageWindow(const QString &argServerIP, + const unsigned short int &argServerPort, + QWidget *argParent) : + QMainWindow{argParent}, + helpMessageSocket {new QTcpSocket{this}}, + serverPort{argServerPort}, + serverAddress{argServerIP}, + ui{new Ui::HelpMessageWindow} { - ui->setupUi( this ); - connect( ui->PBAskForHelp, &QPushButton::clicked, this, &lcHelpMessageWindow::RequestHelp ); - connect( helpMessageSocket, &QTcpSocket::readyRead, this, &lcHelpMessageWindow::ReadHelpReply ); - connect( helpMessageSocket, SIGNAL( error( QAbstractSocket::SocketError ) ), - this, SLOT( DisplayError( QAbstractSocket::SocketError ) ) ); + ui->setupUi(this); + connect(ui->PBAskForHelp, &QPushButton::clicked, + this, &lcHelpMessageWindow::RequestHelp); + connect(helpMessageSocket, &QTcpSocket::readyRead, + this, &lcHelpMessageWindow::ReadHelpReply); + connect(helpMessageSocket, SIGNAL(error(QAbstractSocket::SocketError)), + this, SLOT(DisplayError(QAbstractSocket::SocketError))); QNetworkConfigurationManager manager; - if ( manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired ) { + if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) { // Get saved network configuration - QSettings settings{ QSettings::UserScope, QLatin1String{ "QtProject" } }; - settings.beginGroup( QLatin1String{ "QtNetwork" } ); - const QString id = settings.value( QLatin1String{ "DefaultNetworkConfiguration" } ).toString(); + QSettings settings{QSettings::UserScope, QLatin1String{"QtProject"}}; + settings.beginGroup(QLatin1String{"QtNetwork"}); + const QString id + = settings.value(QLatin1String{"DefaultNetworkConfiguration"}).toString(); settings.endGroup(); // If the saved network configuration is not currently discovered use the system default QNetworkConfiguration config = manager.configurationFromIdentifier( id ); - if ( ( config.state() & QNetworkConfiguration::Discovered ) != QNetworkConfiguration::Discovered ) { + if ((config.state() & QNetworkConfiguration::Discovered) + != QNetworkConfiguration::Discovered) { config = manager.defaultConfiguration(); } - networkSession = new QNetworkSession{ config, this }; - connect( networkSession, &QNetworkSession::opened, this, &lcHelpMessageWindow::OpenedSession ); + networkSession = new QNetworkSession{config, this}; + connect(networkSession, &QNetworkSession::opened, + this, &lcHelpMessageWindow::OpenedSession); networkSession->open(); } @@ -40,68 +47,77 @@ lcHelpMessageWindow::~lcHelpMessageWindow() { delete ui; } -void lcHelpMessageWindow::DisplayError( QAbstractSocket::SocketError socketError ) { +void lcHelpMessageWindow::DisplayError(QAbstractSocket::SocketError socketError) { QString errorMessage; - switch ( socketError ) { + switch (socketError) { case QAbstractSocket::RemoteHostClosedError: return; case QAbstractSocket::HostNotFoundError: - errorMessage = tr( "An error occurred: The server could not be found for error reporting:\n" ); + errorMessage = tr("An error occurred: The server could not be found for" + " error reporting:\n"); break; case QAbstractSocket::ConnectionRefusedError: - errorMessage = tr( "An error occurred: The connection was refused by the laboratory server:\n" ); + errorMessage = tr("An error occurred: The connection was refused by the" + " laboratory server:\n"); break; default: - errorMessage = tr( "The following error occured:\n" ); + errorMessage = tr("The following error occured:\n"); } - errorMessage.append( tr("%1").arg( helpMessageSocket->errorString() ) ); - errorMessage.append( "\n\nPlease raise your hand to notify the experimenters." ); - ui->LSendingSuccess->setText( errorMessage ); + errorMessage.append(tr("%1").arg(helpMessageSocket->errorString())); + errorMessage.append("\n\nPlease raise your hand to notify the experimenters."); + ui->LSendingSuccess->setText(errorMessage); } void lcHelpMessageWindow::OpenedSession() { // Save the used configuration QNetworkConfiguration config = networkSession->configuration(); QString id; - if ( config.type() == QNetworkConfiguration::UserChoice ) - id = networkSession->sessionProperty( QLatin1String{ "UserChoiceConfiguration" } ).toString(); - else + if (config.type() == QNetworkConfiguration::UserChoice) { + id = networkSession->sessionProperty( + QLatin1String{"UserChoiceConfiguration"}).toString(); + } else { id = config.identifier(); + } - QSettings settings{ QSettings::UserScope, QLatin1String{ "QtProject" } }; - settings.beginGroup( QLatin1String{ "QtNetwork" } ); - settings.setValue( QLatin1String{ "DefaultNetworkConfiguration" }, id ); + QSettings settings{QSettings::UserScope, QLatin1String{"QtProject"}}; + settings.beginGroup(QLatin1String{"QtNetwork"}); + settings.setValue(QLatin1String{"DefaultNetworkConfiguration"}, id); settings.endGroup(); } void lcHelpMessageWindow::ReadHelpReply() { - QDataStream in( helpMessageSocket ); - in.setVersion( QDataStream::Qt_5_2 ); + QDataStream in(helpMessageSocket); + in.setVersion(QDataStream::Qt_5_2); - if ( blockSize == 0 ) { - if ( helpMessageSocket->bytesAvailable() < ( int )sizeof( quint16 ) ) + if (blockSize == 0) { + if (helpMessageSocket->bytesAvailable() < (int)sizeof(quint16)) { return; + } in >> blockSize; } - if ( helpMessageSocket->bytesAvailable() < blockSize ) { + if (helpMessageSocket->bytesAvailable() < blockSize) { return; } QString serverAnswer; in >> serverAnswer; - if ( serverAnswer == "Help demand retrieved." ) { - ui->LSendingSuccess->setText( tr( "Help message successfully sent.\nPlease wait for the experimenter to show up at your booth." ) ); - ui->PBAskForHelp->setEnabled( false ); + if (serverAnswer == "Help demand retrieved.") { + ui->LSendingSuccess->setText(tr("Help message successfully" + " sent.\nPlease wait for the" + " experimenter to show up at your booth.")); + ui->PBAskForHelp->setEnabled(false); } else { - ui->LSendingSuccess->setText( tr( "An error occurred sending the help message. Please raise your arm.\n\n'%1'" ).arg( serverAnswer ) ); + ui->LSendingSuccess->setText(tr("An error occurred sending the help" + " message. Please raise your" + " arm.\n\n'%1'").arg(serverAnswer)); } } void lcHelpMessageWindow::RequestHelp() { blockSize = 0; helpMessageSocket->abort(); - helpMessageSocket->connectToHost( serverAddress, serverPort ); + helpMessageSocket->connectToHost(serverAddress, serverPort); } diff --git a/src/helpmessagesender/helpmessagewindow.h b/src/helpmessagesender/helpmessagewindow.h index 41cdc9d..2d1e293 100644 --- a/src/helpmessagesender/helpmessagewindow.h +++ b/src/helpmessagesender/helpmessagewindow.h @@ -9,14 +9,16 @@ namespace Ui { class HelpMessageWindow; -} +} // namespace Ui class lcHelpMessageWindow : public QMainWindow { Q_OBJECT public: - explicit lcHelpMessageWindow( const QString &argServerIP, const unsigned short int &argServerPort, QWidget *argParent = nullptr ); + explicit lcHelpMessageWindow(const QString &argServerIP, + const unsigned short int &argServerPort, + QWidget *argParent = nullptr); ~lcHelpMessageWindow(); private: @@ -30,7 +32,7 @@ private: private slots: void RequestHelp(); void ReadHelpReply(); - void DisplayError( QAbstractSocket::SocketError socketError ); + void DisplayError(QAbstractSocket::SocketError socketError); void OpenedSession(); }; diff --git a/src/helpmessagesender/main.cpp b/src/helpmessagesender/main.cpp index a0991dd..fc63008 100644 --- a/src/helpmessagesender/main.cpp +++ b/src/helpmessagesender/main.cpp @@ -1,11 +1,13 @@ #include "helpmessagewindow.h" + #include -int main( int argc, char *argv[] ) +int main(int argc, char *argv[]) { - QApplication a( argc, argv ); - QSettings labSettings{ "Economic Laboratory", "Labcontrol" }; - lcHelpMessageWindow w{ labSettings.value( "server_ip", "127.0.0.1" ).toString(), labSettings.value( "client_help_server_port", "0" ).toUInt() }; + QApplication a(argc, argv); + QSettings labSettings{"Economic Laboratory", "Labcontrol"}; + lcHelpMessageWindow w{labSettings.value("server_ip", "127.0.0.1").toString(), + labSettings.value("client_help_server_port", "0").toUInt()}; w.show(); return a.exec(); From e8b31b5ccaefff80e8493daa24bf2b05d594e5af Mon Sep 17 00:00:00 2001 From: markuspg Date: Thu, 29 Nov 2018 21:32:10 +0100 Subject: [PATCH 27/30] Modernize helpmessage sender utility --- .gitignore | 2 + CMakeLists.txt | 2 +- src/helpmessagesender/helpmessagewindow.cpp | 61 +++++++++++++++------ src/helpmessagesender/helpmessagewindow.h | 43 +++++++++++---- src/helpmessagesender/main.cpp | 39 ++++++++++++- 5 files changed, 115 insertions(+), 32 deletions(-) diff --git a/.gitignore b/.gitignore index 06b7d96..814cdc6 100755 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,5 @@ # Qt Creator User Project Files *.pro.user *.eccba64 + +/CMakeLists.txt.user* diff --git a/CMakeLists.txt b/CMakeLists.txt index c05309c..34714db 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,7 +3,7 @@ project(Labcontrol CXX) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTOUIC ON) -set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD 17) find_package(Qt5 COMPONENTS Core Network Widgets REQUIRED) diff --git a/src/helpmessagesender/helpmessagewindow.cpp b/src/helpmessagesender/helpmessagewindow.cpp index 9a8300a..95d816a 100644 --- a/src/helpmessagesender/helpmessagewindow.cpp +++ b/src/helpmessagesender/helpmessagewindow.cpp @@ -1,35 +1,63 @@ +/* + * Copyright 2018 Markus Prasser + * + * This file is part of Labcontrol. + * + * Labcontrol is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Labcontrol is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Labcontrol. If not, see . + */ + #include "helpmessagewindow.h" +#include "ui_helpmessagewindow.h" + +#include +#include +#include +#include #include lcHelpMessageWindow::lcHelpMessageWindow(const QString &argServerIP, - const unsigned short int &argServerPort, - QWidget *argParent) : + const quint16 argServerPort, + QWidget *const argParent) : QMainWindow{argParent}, - helpMessageSocket {new QTcpSocket{this}}, - serverPort{argServerPort}, serverAddress{argServerIP}, + serverPort{argServerPort}, ui{new Ui::HelpMessageWindow} { + helpMessageSocket = new QTcpSocket{this}; + ui->setupUi(this); connect(ui->PBAskForHelp, &QPushButton::clicked, this, &lcHelpMessageWindow::RequestHelp); connect(helpMessageSocket, &QTcpSocket::readyRead, this, &lcHelpMessageWindow::ReadHelpReply); - connect(helpMessageSocket, SIGNAL(error(QAbstractSocket::SocketError)), - this, SLOT(DisplayError(QAbstractSocket::SocketError))); + connect(helpMessageSocket, + static_cast + (&QAbstractSocket::error), + this, &lcHelpMessageWindow::DisplayError); QNetworkConfigurationManager manager; - if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) { + if (manager.capabilities() + & QNetworkConfigurationManager::NetworkSessionRequired) { // Get saved network configuration QSettings settings{QSettings::UserScope, QLatin1String{"QtProject"}}; settings.beginGroup(QLatin1String{"QtNetwork"}); - const QString id - = settings.value(QLatin1String{"DefaultNetworkConfiguration"}).toString(); + const auto id{settings.value("DefaultNetworkConfiguration").toString()}; settings.endGroup(); // If the saved network configuration is not currently discovered use the system default - QNetworkConfiguration config = manager.configurationFromIdentifier( id ); + QNetworkConfiguration config = manager.configurationFromIdentifier(id); if ((config.state() & QNetworkConfiguration::Discovered) != QNetworkConfiguration::Discovered) { config = manager.defaultConfiguration(); @@ -47,9 +75,9 @@ lcHelpMessageWindow::~lcHelpMessageWindow() { delete ui; } -void lcHelpMessageWindow::DisplayError(QAbstractSocket::SocketError socketError) { +void lcHelpMessageWindow::DisplayError(QAbstractSocket::SocketError argSocketError) { QString errorMessage; - switch (socketError) { + switch (argSocketError) { case QAbstractSocket::RemoteHostClosedError: return; case QAbstractSocket::HostNotFoundError: @@ -70,9 +98,9 @@ void lcHelpMessageWindow::DisplayError(QAbstractSocket::SocketError socketError) void lcHelpMessageWindow::OpenedSession() { // Save the used configuration - QNetworkConfiguration config = networkSession->configuration(); QString id; - if (config.type() == QNetworkConfiguration::UserChoice) { + if (const auto config{networkSession->configuration()}; + config.type() == QNetworkConfiguration::UserChoice) { id = networkSession->sessionProperty( QLatin1String{"UserChoiceConfiguration"}).toString(); } else { @@ -86,11 +114,12 @@ void lcHelpMessageWindow::OpenedSession() { } void lcHelpMessageWindow::ReadHelpReply() { - QDataStream in(helpMessageSocket); + QDataStream in{helpMessageSocket}; in.setVersion(QDataStream::Qt_5_2); if (blockSize == 0) { - if (helpMessageSocket->bytesAvailable() < (int)sizeof(quint16)) { + if (helpMessageSocket->bytesAvailable() + < static_cast(sizeof(quint16))) { return; } diff --git a/src/helpmessagesender/helpmessagewindow.h b/src/helpmessagesender/helpmessagewindow.h index 2d1e293..a00d75f 100644 --- a/src/helpmessagesender/helpmessagewindow.h +++ b/src/helpmessagesender/helpmessagewindow.h @@ -1,11 +1,30 @@ +/* + * Copyright 2018 Markus Prasser + * + * This file is part of Labcontrol. + * + * Labcontrol is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Labcontrol is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Labcontrol. If not, see . + */ + #ifndef HELPMESSAGEWINDOW_H #define HELPMESSAGEWINDOW_H -#include "ui_helpmessagewindow.h" - +#include #include -#include -#include + +class QNetworkSession; +class QTcpSocket; namespace Ui { class HelpMessageWindow; @@ -17,23 +36,23 @@ class lcHelpMessageWindow : public QMainWindow public: explicit lcHelpMessageWindow(const QString &argServerIP, - const unsigned short int &argServerPort, - QWidget *argParent = nullptr); - ~lcHelpMessageWindow(); + const quint16 argServerPort, + QWidget *const argParent = nullptr); + ~lcHelpMessageWindow() override; private: quint16 blockSize = 0; QTcpSocket *helpMessageSocket = nullptr; QNetworkSession *networkSession = nullptr; - const quint16 serverPort = 0; const QHostAddress serverAddress; - Ui::HelpMessageWindow *ui; + const quint16 serverPort = 0; + Ui::HelpMessageWindow *const ui = nullptr; private slots: - void RequestHelp(); - void ReadHelpReply(); - void DisplayError(QAbstractSocket::SocketError socketError); + void DisplayError(QAbstractSocket::SocketError argSocketError); void OpenedSession(); + void ReadHelpReply(); + void RequestHelp(); }; #endif // HELPMESSAGEWINDOW_H diff --git a/src/helpmessagesender/main.cpp b/src/helpmessagesender/main.cpp index fc63008..84be188 100644 --- a/src/helpmessagesender/main.cpp +++ b/src/helpmessagesender/main.cpp @@ -1,14 +1,47 @@ +/* + * Copyright 2018 Markus Prasser + * + * This file is part of Labcontrol. + * + * Labcontrol is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Labcontrol is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Labcontrol. If not, see . + */ + #include "helpmessagewindow.h" #include +#include + +#include int main(int argc, char *argv[]) { - QApplication a(argc, argv); + QApplication app{argc, argv}; + QSettings labSettings{"Economic Laboratory", "Labcontrol"}; + + bool convSuccess = false; + const auto portNum{ + static_cast(labSettings.value("client_help_server_port", "0") + .toUInt(&convSuccess))}; + if (convSuccess == false) { + std::cerr << "Failed to convert \"client_help_server_port\" setting\n"; + return 1; + } + lcHelpMessageWindow w{labSettings.value("server_ip", "127.0.0.1").toString(), - labSettings.value("client_help_server_port", "0").toUInt()}; + portNum}; w.show(); - return a.exec(); + return app.exec(); } From bda6d8ad11f3832d3bf17c614ee71d2d386e6d32 Mon Sep 17 00:00:00 2001 From: ewflab Date: Tue, 25 Feb 2020 09:29:18 +0100 Subject: [PATCH 28/30] qt-test.yml --- .github/workflows/main.yml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/workflows/main.yml diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..df2721d --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,30 @@ +name: Test Installing Qt + +on: [push, pull_request] + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest] + steps: + - uses: actions/checkout@v1 + + - uses: actions/setup-node@v1 + with: + node-version: '10.x' + + - name: Install Qt + uses: ./ + with: + aqtversion: "==0.7.1" + modules: qtcharts qtwebengine + + - name: Configure test project on unix + if: (!startsWith(matrix.os, 'windows')) + run: | + cd tests/TestWithModules + ls $Qt5_Dir/lib/cmake + qmake + shell: bash From 1c65d1e2936474941e6c89971c0defe9fd2e9e47 Mon Sep 17 00:00:00 2001 From: Tobias Weiss Date: Tue, 25 Feb 2020 09:32:32 +0100 Subject: [PATCH 29/30] fix QButtonGroup --- src/mainwindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index b0fb33d..7f639ff 100755 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -22,7 +22,7 @@ #include #include #include - +#include #include "localzleafstarter.h" #include "mainwindow.h" #include "manualprintingsetup.h" From 4b6f10554a0fe36632a5aaedaa34ad21b6502b4b Mon Sep 17 00:00:00 2001 From: ewflab Date: Tue, 25 Feb 2020 09:41:09 +0100 Subject: [PATCH 30/30] Delete main.yml delete action - test it elsewhere. --- .github/workflows/main.yml | 30 ------------------------------ 1 file changed, 30 deletions(-) delete mode 100644 .github/workflows/main.yml diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml deleted file mode 100644 index df2721d..0000000 --- a/.github/workflows/main.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Test Installing Qt - -on: [push, pull_request] - -jobs: - test: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest] - steps: - - uses: actions/checkout@v1 - - - uses: actions/setup-node@v1 - with: - node-version: '10.x' - - - name: Install Qt - uses: ./ - with: - aqtversion: "==0.7.1" - modules: qtcharts qtwebengine - - - name: Configure test project on unix - if: (!startsWith(matrix.os, 'windows')) - run: | - cd tests/TestWithModules - ls $Qt5_Dir/lib/cmake - qmake - shell: bash