Add clang-format style file and format accordingly

remotes/origin/HEAD
markuspg 6 years ago
parent ea2e335f8f
commit d5fe3526d1

@ -0,0 +1,118 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Right
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
IndentPPDirectives: None
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 8
UseTab: Never
...

@ -25,48 +25,41 @@
#include <QRegularExpression>
#include "client.h"
#include "settings.h"
#include "lablib.h"
#include "settings.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 }
{
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 );
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} {
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);
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 ) {
if (pingTimer) {
pingTimer->stop();
}
delete pingTimer;
@ -74,132 +67,144 @@ 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" };
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(env);
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 };
QStringList arguments{QStringList{} << "-i" << settings->netwBrdAddr << mac};
// Start the process
QProcess wakeonlanProcess;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
wakeonlanProcess.setProcessEnvironment( env );
wakeonlanProcess.startDetached( settings->wakeonlanCmd, arguments );
wakeonlanProcess.setProcessEnvironment(env);
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<unsigned short int>(argState);
}
void lc::Client::KillZLeaf() {
QStringList arguments;
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;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
killZLeafProcess.setProcessEnvironment( env );
killZLeafProcess.startDetached( settings->sshCmd, arguments );
killZLeafProcess.setProcessEnvironment(env);
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 };
QStringList arguments = QStringList{}
<< 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(env);
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 ) {
if (!argOpenAsRoot) {
*arguments << "-e"
<< QString{ settings->sshCmd + " -i " + settings->pkeyPathUser + " "
+ settings->userNameOnClients + "@" + ip };
<< 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( " " );
openTerminalProcess.setProcessEnvironment(env);
openTerminalProcess.startDetached(settings->termEmulCmd, *arguments);
qDebug() << settings->termEmulCmd << arguments->join(" ");
delete arguments;
}
}
void lc::Client::RequestAPing() {
if ( protectedCycles > 0 ) {
if (protectedCycles > 0) {
--protectedCycles;
}
emit PingWanted();
}
void lc::Client::SetStateToZLEAF_RUNNING( QString argClientIP ) {
if ( argClientIP != ip ) {
void lc::Client::SetStateToZLEAF_RUNNING(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.";
}
}
@ -210,11 +215,11 @@ void lc::Client::ShowDesktopViewOnly() {
QProcess showDesktopProcess;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
showDesktopProcess.setProcessEnvironment( env );
showDesktopProcess.startDetached( settings->vncViewer, arguments );
showDesktopProcess.setProcessEnvironment(env);
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::ShowDesktopFullControl() {
@ -223,109 +228,112 @@ void lc::Client::ShowDesktopFullControl() {
QProcess showDesktopProcess;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
showDesktopProcess.setProcessEnvironment( env );
showDesktopProcess.startDetached( settings->vncViewer, arguments );
showDesktopProcess.setProcessEnvironment(env);
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 ) {
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";
<< 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(env);
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 );
// This additional 'ping_timer' start is needed for the case that the clients
// are shut down without prior closing of zLeaves
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 );
// 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);
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 }
<< cmd;
<< QString{settings->userNameOnClients + "@" + ip} << cmd;
} else {
arguments << "-i" << settings->pkeyPathUser
<< QString{ settings->userNameOnClients + "@" + ip }
<< cmd
<< 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(env);
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, const QString * const argBrowser ) {
//Declarations
void lc::Client::StartClientBrowser(const QString *const argURL,
const bool *const argFullscreen,
const QString *const argBrowser) {
// Declarations
QStringList arguments;
QString processedArgUrl(*argURL);
QRegularExpression clientRegEx(QStringLiteral("%CLIENT%"));
processedArgUrl.replace(clientRegEx,this->name);
//qDebug() << processedArgUrl;
processedArgUrl.replace(clientRegEx, this->name);
// qDebug() << processedArgUrl;
if(argBrowser==QString("firefox")){
if (argBrowser == QString("firefox")) {
// Build arguments list for SSH command
arguments << "-i" << settings->pkeyPathUser
<< QString{ settings->userNameOnClients + "@" + ip }
<< "DISPLAY=:0.0"
<< settings->clientBrowserCmd
<< QString{settings->userNameOnClients + "@" + ip}
<< "DISPLAY=:0.0" << settings->clientBrowserCmd
<< processedArgUrl;
// Add fullscreen toggle if checked
if (*argFullscreen == true){
if (*argFullscreen == true) {
arguments << "& sleep 3 && DISPLAY=:0.0 xdotool key --clearmodifiers F11";
}
} else if (argBrowser==QString("chromium")) {
} else if (argBrowser == QString("chromium")) {
// Build arguments list for SSH command
arguments << "-i" << settings->pkeyPathUser
<< QString{ settings->userNameOnClients + "@" + ip }
<< "DISPLAY=:0.0"
<< settings->clientChromiumCmd
<< QString{settings->userNameOnClients + "@" + ip}
<< "DISPLAY=:0.0" << settings->clientChromiumCmd
<< "--noerrdialogs --kiosk"
<< "--app='" + processedArgUrl + "'"
<< "> /dev/null 2>&1 &disown";
@ -334,57 +342,57 @@ void lc::Client::StartClientBrowser( const QString * const argURL, const bool *
// Start the process
QProcess startClientBrowserProcess;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
startClientBrowserProcess.setProcessEnvironment( env );
startClientBrowserProcess.startDetached( settings->sshCmd, arguments );
startClientBrowserProcess.setProcessEnvironment(env);
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() {
//Declarations
// Declarations
QStringList arguments;
//Build arguments list
// Build arguments list
arguments << "-i" << settings->pkeyPathUser
<< QString{ settings->userNameOnClients + "@" + ip }
<< "killall"
<< QString{settings->userNameOnClients + "@" + ip} << "killall"
<< settings->clientBrowserCmd
<< "& sleep 1 && rm -R /home/ewfuser/.mozilla/firefox/*"
<< "& killall"
<< settings->clientChromiumCmd;
<< "& killall" << settings->clientChromiumCmd;
// Start the process
QProcess startClientBrowserProcess;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
startClientBrowserProcess.setProcessEnvironment( env );
startClientBrowserProcess.startDetached( settings->sshCmd, arguments );
startClientBrowserProcess.setProcessEnvironment(env);
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::ControlRMB(bool enable) {
//Declarations
// Declarations
QStringList arguments;
//Build arguments list
if(enable){
// Build arguments list
if (enable) {
arguments << "-i" << settings->pkeyPathUser
<< QString{ settings->userNameOnClients + "@" + ip }
<< "DISPLAY=:0 xinput set-button-map 'Microsoft Basic Optical Mouse' 1 2 3 4 5 6 7 8 9 10 11 12 > /dev/null 2>&1 &disown;";
<< QString{settings->userNameOnClients + "@" + ip}
<< "DISPLAY=:0 xinput set-button-map 'Microsoft Basic Optical "
"Mouse' 1 2 3 4 5 6 7 8 9 10 11 12 > /dev/null 2>&1 &disown;";
} else {
arguments << "-i" << settings->pkeyPathUser
<< QString{ settings->userNameOnClients + "@" + ip }
<< "DISPLAY=:0 xinput set-button-map 'Microsoft Basic Optical Mouse' 1 2 0 4 5 6 7 8 9 10 11 12 > /dev/null 2>&1 &disown;";
<< QString{settings->userNameOnClients + "@" + ip}
<< "DISPLAY=:0 xinput set-button-map 'Microsoft Basic Optical "
"Mouse' 1 2 0 4 5 6 7 8 9 10 11 12 > /dev/null 2>&1 &disown;";
}
// Start the process
QProcess startClientBrowserProcess;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
startClientBrowserProcess.setProcessEnvironment( env );
startClientBrowserProcess.startDetached( settings->sshCmd, arguments );
startClientBrowserProcess.setProcessEnvironment(env);
startClientBrowserProcess.startDetached(settings->sshCmd, arguments);
// Output message via the debug messages tab
qDebug() << settings->sshCmd << arguments.join( " " );
qDebug() << settings->sshCmd << arguments.join(" ");
}

@ -28,21 +28,22 @@
#include <QThread>
#include <QTimer>
#include "global.h"
#include "clientpinger.h"
#include "global.h"
namespace lc {
//! Class which represents the clients in the lab
/*!
This class contains elements and functions needed to represent all functions of a client.
This class contains elements and functions needed to represent all functions
of a client.
*/
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(QString argClientIP);
public:
const QString ip;
@ -59,24 +60,29 @@ 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,
Client(const QString &argIP, const QString &argMAC, const QString &argName,
unsigned short int argXPosition, unsigned short int argYPosition,
const QString &argPingCmd );
const QString &argPingCmd);
//! Client's destructor
~Client();
//! 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 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
*/
void Boot();
/*!
* \brief DeactiveScreensaver deactivates potentially running screensavers on the client
* \brief DeactiveScreensaver deactivates potentially running screensavers on
* the client
*/
void DeactiveScreensaver();
//! Returns the current state of the client
@ -93,15 +99,16 @@ 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)
* \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(int argSP) { sessionPort = argSP; }
void SetzLeafVersion(const QString &argzLeafV) { zLeafVersion = argzLeafV; }
//! Shows the desktop of the given client
void ShowDesktopViewOnly();
void ShowDesktopFullControl();
@ -112,15 +119,18 @@ 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)
* @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, const QString *argBrowser = nullptr );
void StartClientBrowser(const QString *argURL = nullptr,
const bool *argFullscreen = nullptr,
const QString *argBrowser = nullptr);
/*!
* \brief Closes all browser instances
@ -139,18 +149,19 @@ private:
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 *pingTimer = nullptr; //! QTimer used to trigger pings by pinger's
//! ClientPinger instance
int sessionPort = 0;
QString zLeafVersion;
private slots:
void GotStatusChanged( state_t argState );
void GotStatusChanged(state_t argState);
void RequestAPing();
signals:
void PingWanted();
};
}
} // namespace lc
#endif // CLIENT_H

@ -22,58 +22,69 @@
#include "clienthelpnotificationserver.h"
#include "settings.h"
extern std::unique_ptr< lc::Settings > settings;
extern std::unique_ptr<lc::Settings> settings;
lc::ClientHelpNotificationServer::ClientHelpNotificationServer( QObject *argParent ) :
QObject{ argParent },
hostAddress{ settings->serverIP }
{
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 ) {
// 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) {
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() {
// Save the used configuration
if ( networkSession ) {
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 };
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 };
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};
messageBox.exec();
return;
}
@ -81,34 +92,38 @@ void lc::ClientHelpNotificationServer::OpenSession() {
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 << (quint16)0;
out << QString{"Help demand retrieved."};
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
QTcpSocket *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();
}
}

@ -22,9 +22,9 @@
#include "src/Lib/client.h"
#include <QObject>
#include <QHostAddress>
#include <QMessageBox>
#include <QObject>
#include <QtNetwork>
namespace lc {
@ -32,7 +32,7 @@ namespace lc {
class ClientHelpNotificationServer : public QObject {
Q_OBJECT
public:
explicit ClientHelpNotificationServer( QObject *argParent = nullptr );
explicit ClientHelpNotificationServer(QObject *argParent = nullptr);
signals:
@ -48,6 +48,6 @@ private slots:
void SendReply();
};
}
} // namespace lc
#endif // CLIENTHELPNOTIFICATIONSERVER_H

@ -19,42 +19,45 @@
#include "clientpinger.h"
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 }
{
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} {
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
pingProcess->setProcessEnvironment(env);
// emit ping_string(new QString(*ping_command + " " + ping_arguments->join(" ")));
// emit ping_string(new QString(*ping_command + " " + ping_arguments->join("
// ")));
}
lc::ClientPinger::~ClientPinger() {
delete pingProcess;
}
lc::ClientPinger::~ClientPinger() { delete pingProcess; }
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))
newState = state_t::ERROR;
else {
if ( pingProcess->exitCode() == 0 )
if (pingProcess->exitCode() == 0)
newState = state_t::RESPONDING;
else
newState = state_t::NOT_RESPONDING;
}
if ( newState != state ) {
if (newState != state) {
state = newState;
emit PingFinished( newState );
emit PingFinished(newState);
}
}

@ -28,7 +28,8 @@
namespace lc {
//! The ClientPinger class is used to do repetitive pings of the owning Client instance's client.
//! The ClientPinger class is used to do repetitive pings of the owning Client
//! instance's client.
/*!
This class is just used for executing repetitive pings.
*/
@ -38,33 +39,39 @@ class ClientPinger : public QObject {
public:
//! ClientPinger's constructor
/*!
@param argIP A reference to the owning Client instance's IP address
@param argPingCommand The path were the command to be executed for pings resides
@param argParent The ClientPinger's parent owning this instance of it
@param argIP A reference to the owning Client instance's IP
address
@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 );
explicit ClientPinger(const QString &argIP, const QString &argPingCommand,
QObject *argParent = nullptr);
//! ClientPinger's destructor
~ClientPinger();
public slots:
//! This slot executes a ping when called.
void doPing();
//! Retrieves the information, that zLeaf is running (otherwise restarting will not result in status updates)
//! Retrieves the information, that zLeaf is running (otherwise restarting
//! will not result in status updates)
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()'
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
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 );
//! This signal is emitted if the ping finished and the state of the client
//! changed
void PingFinished(state_t state);
};
}
} // namespace lc
#endif // CLIENTPINGER_H

@ -32,12 +32,14 @@ enum class state_t : unsigned short int {
NOT_RESPONDING,
//! The client is shutting down but not yet stopped responding
SHUTTING_DOWN,
//! The client's state is not yet defined (should only occur directly after client creation)
//! The client's state is not yet defined (should only occur directly after
//! client creation)
UNINITIALIZED,
//! The client is responding to pings
RESPONDING,
//! The client is running a zLeaf
ZLEAF_RUNNING};
Q_DECLARE_METATYPE( state_t )
ZLEAF_RUNNING
};
Q_DECLARE_METATYPE(state_t)
#endif // GLOBAL_H

@ -24,39 +24,38 @@
#include "lablib.h"
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 );
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);
}
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;
}
@ -65,26 +64,25 @@ lc::Lablib::~Lablib () {
}
bool lc::Lablib::CheckIfUserIsAdmin() const {
for ( const auto &s : settings->adminUsers ) {
if ( s == settings->localUserName ) {
qDebug() << "User" << settings->localUserName << "has administrative rights.";
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 );
}
emit ZLEAF_RUNNING(s);
}
else
} else
qDebug() << "Netstat status query failed.";
delete argActiveZLeafConnections;
}
@ -92,96 +90,106 @@ void lc::Lablib::GotNetstatQueryResult( QStringList *argActiveZLeafConnections )
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(env);
QString program{settings->browserCmd};
QStringList arguments{QStringList{} << 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() {
// 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(env);
QString program{settings->fileMngr};
QStringList arguments{QStringList{} << 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,
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 };
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"
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 };
" 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'"
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 ) );
" 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 ){
// 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" }
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" }
arguments << "DISPLAY=:0.0" << settings->tasksetCmd << "0x00000001"
<< settings->wineCmd
<< QString{settings->zTreeInstDir + "/zTree_" + zleafVersion +
"/zleaf.exe"}
<< "/server" << settings->serverIP << "/channel"
<< QString::number( sessionPort- 7000 );
<< QString::number(sessionPort - 7000);
}
//Return the crafted QStringList
// Return the crafted QStringList
return arguments;
}

@ -45,70 +45,73 @@
#include "sessionsmodel.h"
#include "settings.h"
extern std::unique_ptr< lc::Settings > settings;
extern std::unique_ptr<lc::Settings> settings;
namespace lc {
//! This class represents the entire lab and running sessions.
/*!
This class contains elements and functions needed to represent the lab and running sessions.
This class contains elements and functions needed to represent the lab and
running sessions.
*/
class Lablib : public QObject
{
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();
/*!
* \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
* \return True, if the account has administrative rights; false, otherwise
* \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 \return True, if the account has
* administrative rights; false, otherwise
*/
bool CheckIfUserIsAdmin() const;
/** Returns a pointer to a QVector<unsigned int> containing all by sessions occupied ports
/** Returns a pointer to a QVector<unsigned int> containing all by sessions
* occupied ports
*
* @return A pointer to a QVector<unsigned int> containing all occupied ports
*/
const QVector< quint16 > &GetOccupiedPorts () const { return occupiedPorts; }
const QVector<quint16> &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,
void StartNewSession(QVector<Client *> argAssocCl,
QString argParticipNameReplacement,
bool argPrintLocalReceipts, QString argReceiptsHeader,
QString argzTreeDataTargetPath, quint16 argzTreePort,
QString argzTreeVersion );
QString argzTreeVersion);
/*!
* \brief Returns the commandline to issue on the client(s) in order to start zLeaf
* \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 +120,20 @@ private:
*/
void ReadSettings();
ClientHelpNotificationServer *clientHelpNotificationServer = nullptr; //! A server to retrieve help requests from the clients
ClientHelpNotificationServer *clientHelpNotificationServer =
nullptr; //! A server to retrieve help requests from the clients
QSettings labSettings;
NetstatAgent *netstatAgent = nullptr; //! Tries to detect active zLeaf connections from the clients
NetstatAgent *netstatAgent =
nullptr; //! Tries to detect active zLeaf connections from the clients
QThread netstatThread;
QTimer *netstatTimer = nullptr; //! A timer for regular execution of the NetstatAgent instance's request mechanism
QVector< quint16 > occupiedPorts;
SessionsModel *sessionsModel = nullptr; //! A derivation from QAbstractTableModel used to store the single Session instances
QTimer *netstatTimer = nullptr; //! A timer for regular execution of the
//! NetstatAgent instance's request mechanism
QVector<quint16> occupiedPorts;
SessionsModel *sessionsModel =
nullptr; //! A derivation from QAbstractTableModel used to store the
//! single Session instances
};
}
} // namespace lc
#endif // LABLIB_H

@ -19,33 +19,37 @@
#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}, extractionRegexp{"\\d+\\.\\d+\\.\\d+\\.\\d+"},
netstatArguments{QStringList{} << "-anp"
<< "--tcp"},
netstatCommand{argNetstatCommand}, netstatQueryProcess{this},
searchRegexp{"\\W(ESTABLISHED|VERBUNDEN)( +)(\\d+)(/ztree.exe)\\W",
QRegularExpression::CaseInsensitiveOption} {
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
netstatQueryProcess.setProcessEnvironment( env );
netstatQueryProcess.setProcessEnvironment(env);
}
void lc::NetstatAgent::QueryClientConnections() {
netstatQueryProcess.start( netstatCommand, netstatArguments );
if ( !netstatQueryProcess.waitForFinished( 400 ) ) {
emit QueryFinished( nullptr );
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 );
// 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);
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() );
for (auto s : tempStrings) {
if (s.contains(searchRegexp)) {
QRegularExpressionMatch match =
extractionRegexp.match(s, s.indexOf(':', 0, Qt::CaseInsensitive));
netstatQueryProcessOutput->append(match.captured());
}
}

@ -27,7 +27,8 @@
namespace lc {
//! The NetstatAgent class is used to do repetitive runs of the 'netstat' program to check for active zLeaf connections.
//! The NetstatAgent class is used to do repetitive runs of the 'netstat'
//! program to check for active zLeaf connections.
/*!
This class is just used for repetive executions of netstat.
*/
@ -35,10 +36,12 @@ 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
//! This signal is emitted if the query of the currently active zLeaf
//! connections finished
void QueryFinished(QStringList *argActiveZLeafConnections);
public slots:
@ -52,6 +55,6 @@ private:
const QRegularExpression searchRegexp;
};
}
} // namespace lc
#endif // NETSTATAGENT_H

@ -24,47 +24,43 @@
#include "receipts_handler.h"
#include "settings.h"
extern std::unique_ptr< lc::Settings > settings;
extern std::unique_ptr<lc::Settings> settings;
lc::ReceiptsHandler::ReceiptsHandler( const QString &argZTreeDataTargetPath,
bool argPrintReceiptsForLocalClients,
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 }
{
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 );
// 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);
}
lc::ReceiptsHandler::ReceiptsHandler( const QString &argZTreeDataTargetPath,
bool argPrintReceiptsForLocalClients,
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 }
{
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();
@ -72,9 +68,9 @@ lc::ReceiptsHandler::ReceiptsHandler( const QString &argZTreeDataTargetPath,
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();
}
@ -86,24 +82,29 @@ void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() {
// Get the data needed for receipts creation from the payment file
QVector<QString> *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<paymentEntry_t*> *participants = new QVector<paymentEntry_t*>;
QVector<paymentEntry_t *> *participants = new QVector<paymentEntry_t *>;
double overall_payoff = 0.0;
for ( QVector<QString>::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 {
for (QVector<QString>::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 {
// Create a new struct instance for participant data and fill it
paymentEntry_t *participant = new paymentEntry_t;
participant->computer = temp_participant_data.at(1);
@ -116,15 +117,16 @@ void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() {
delete rawParticipantsData;
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 );
// 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);
}
// 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,33 +135,40 @@ 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;
}
// 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 );
// 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);
}
// 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;
}
@ -167,42 +176,50 @@ void lc::ReceiptsHandler::CreateReceiptsFromPaymentFile() {
participants = nullptr;
// Append LaTeX ending
latexText->append( "\\end{document}" );
latexText->append("\\end{document}");
qDebug() << *latexText;
// Create the tex file
QFile *texFile = new QFile{ zTreeDataTargetPath + "/" + dateString + ".tex" };
qDebug() << "Tex file" << texFile->fileName() << "will be created for receipts printing.";
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();
@ -219,8 +236,10 @@ 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();
@ -231,21 +250,21 @@ QVector<QString> *lc::ReceiptsHandler::GetParticipantsDataFromPaymentFile() {
QVector<QString> *participantsData = new QVector<QString>;
// 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();
@ -255,36 +274,43 @@ QVector<QString> *lc::ReceiptsHandler::GetParticipantsDataFromPaymentFile() {
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<paymentEntry_t*> *argDataVector, bool argAlsoAnonymizeClients ) {
if ( !argAlsoAnonymizeClients ) {
void lc::ReceiptsHandler::MakeReceiptsAnonymous(
QVector<paymentEntry_t *> *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<paymentEntry_t *>::iterator it = argDataVector->begin();
it != argDataVector->end(); ++it) {
(*it)->name = anonymousReceiptsPlaceholder;
}
else {
} 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}";
for (QVector<paymentEntry_t *>::iterator it = argDataVector->begin();
it != argDataVector->end(); ++it) {
(*it)->name = anonymousReceiptsPlaceholder;
(*it)->computer = "\\hspace{1cm}";
}
}
}

@ -34,27 +34,36 @@ namespace lc {
//! A struct representing one payoff entry.
/*!
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.
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.
This class is element of every session and is used to handle the receipts
printing.
*/
class ReceiptsHandler : public QObject {
Q_OBJECT
public:
explicit ReceiptsHandler( const QString &argZTreeDataTargetPath,
explicit ReceiptsHandler(const QString &argZTreeDataTargetPath,
bool argPrintReceiptsForLocalClients,
const QString &argAnonymousReceiptsPlaceholder,
const QString &argLatexHeaderName, QObject *argParent = nullptr );
explicit ReceiptsHandler( const QString &argZTreeDataTargetPath,
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 );
const QString &argDateString,
QObject *argParent = nullptr);
signals:
void PrintingFinished();
@ -63,7 +72,8 @@ private slots:
/*! Deletes the ReceiptsPrinter instance after successful printing
*/
void DeleteReceiptsPrinterInstance();
/*! Displays QMessageBox widgets for errors given by the ReceiptsPrinter instance
/*! Displays QMessageBox widgets for errors given by the ReceiptsPrinter
* instance
*/
void DisplayMessageBox(QString *argErrorMessage, QString *argHeading);
/*! Prints the receipts
@ -74,20 +84,33 @@ private:
void CreateReceiptsFromPaymentFile();
QVector<QString> *GetParticipantsDataFromPaymentFile();
QString *LoadLatexHeader();
void MakeReceiptsAnonymous( QVector<paymentEntry_t*> *argDataVector, bool argAlsoAnonymizeClients );
void MakeReceiptsAnonymous(QVector<paymentEntry_t *> *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
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
};
}
} // namespace lc
#endif // RECEIPTS_HANDLER_H

@ -22,20 +22,13 @@
#include "receiptsprinter.h"
#include "settings.h"
extern std::unique_ptr< lc::Settings > settings;
extern std::unique_ptr<lc::Settings> settings;
lc::ReceiptsPrinter::ReceiptsPrinter( const QString &argDateString,
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 }
{
}
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} {}

@ -38,16 +38,21 @@ class ReceiptsPrinter : public QThread {
void run() Q_DECL_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 };
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,20 @@ 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,64 +85,75 @@ 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->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"));
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"));
}
delete process;
process = nullptr;
@ -139,10 +161,11 @@ class ReceiptsPrinter : public QThread {
emit PrintingFinished();
}
public:
explicit ReceiptsPrinter( const QString &argDateString,
explicit ReceiptsPrinter(const QString &argDateString,
const QString &argWorkpath,
QObject *argParent = nullptr );
QObject *argParent = nullptr);
signals:
void ErrorOccurred(QString *error_message, QString *heading);
@ -154,13 +177,15 @@ 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
const QString
workpath; //!< The path were zTree was ordered to store all its data
};
}
} // namespace lc
#endif // RECEIPTSPRINTER_H

@ -22,51 +22,53 @@
#include "session.h"
#include "settings.h"
extern std::unique_ptr< lc::Settings > settings;
extern std::unique_ptr<lc::Settings> settings;
lc::Session::Session( QVector< Client* > &&argAssocClients,
const QString &argZTreeDataTargetPath, const quint16 argZTreePort,
const QString &argZTreeVersionPath, bool argPrintReceiptsForLocalClients,
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 }
{
// This part ensures, that both class instances are created in the same minute, so that the payment file name can be guessed correctly
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 ) {
switch ( argIndex ) {
QVariant lc::Session::GetDataItem(int 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{};
}
@ -74,43 +76,50 @@ 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 ) );
qDebug() << "New session's chosen_zTree_data_target_path:" << zTreeDataTargetPath;
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 };
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);
// 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};
} else {
qDebug() << "No 'ReceiptsHandler' instance was created.";
}
}
void lc::Session::OnzTreeClosed( int argExitCode ) {
qDebug() << "z-Tree running on port" << zTreePort << "closed with exit code" << argExitCode;
emit SessionFinished( this );
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() {
// Example: wmctrl -r <window name> -T <new name>
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(env);
renameZTreeWindowProcess.startDetached(settings->wmctrlCmd, arguments);
qDebug() << "Renamed window";

@ -32,52 +32,63 @@ class Client;
//! A class containing an entire session.
/*!
This class represents an entire session with its zTree instance and the corresponding lcReceiptsHandler instance.
This class represents an entire session with its zTree instance and the
corresponding lcReceiptsHandler instance.
*/
class Session : public QObject {
Q_OBJECT
public:
const int zTreePort = 7000; //! The port this session's zTree instance is running on
const int zTreePort =
7000; //! The port this session's zTree instance is running on
Session( QVector< Client* > &&argAssocClients, const QString &argZTreeDataTargetPath,
const quint16 argZTreePort, const QString &argZTreeVersionPath,
Session(QVector<Client *> &&argAssocClients,
const QString &argZTreeDataTargetPath, const quint16 argZTreePort,
const QString &argZTreeVersionPath,
bool argPrintReceiptsForLocalClients,
const QString &argAnonymousReceiptsPlaceholder,
const QString &argLatexHeaderName, QObject *argParent = nullptr );
const QString &argLatexHeaderName, QObject *argParent = nullptr);
~Session();
/*! 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.
//! 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 );
/*! Changes zTree's window title to contain its port number to make zTree windows distinguishable
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
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
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
};
}
} // namespace lc
#endif // SESSION_H

@ -21,14 +21,10 @@
#include "sessionsmodel.h"
lc::SessionsModel::SessionsModel( QObject *argParent ) :
QAbstractTableModel{ argParent }
{
}
lc::SessionsModel::SessionsModel(QObject *argParent)
: QAbstractTableModel{argParent} {}
lc::Session *lc::SessionsModel::back() const {
return sessionsList.back();
}
lc::Session *lc::SessionsModel::back() const { return sessionsList.back(); }
int lc::SessionsModel::columnCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
@ -43,14 +39,15 @@ 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,16 +63,17 @@ QVariant lc::SessionsModel::headerData(int section, Qt::Orientation orientation,
return QVariant{};
}
void lc::SessionsModel::push_back( Session *argSession ) {
connect( argSession, &Session::SessionFinished,
this, &SessionsModel::RemoveSession );
argSession->setParent( this );
sessionsList.push_back( argSession );
void lc::SessionsModel::push_back(Session *argSession) {
connect(argSession, &Session::SessionFinished, this,
&SessionsModel::RemoveSession);
argSession->setParent(this);
sessionsList.push_back(argSession);
}
void lc::SessionsModel::RemoveSession( Session *argSession ) {
if ( sessionsList.removeAll( argSession ) ) {
qDebug() << "Successfully removed" << argSession << "from lc::SessionsModel";
void lc::SessionsModel::RemoveSession(Session *argSession) {
if (sessionsList.removeAll(argSession)) {
qDebug() << "Successfully removed" << argSession
<< "from lc::SessionsModel";
argSession->deleteLater();
}
}

@ -30,12 +30,12 @@ class SessionsModel : public QAbstractTableModel {
Q_OBJECT
public:
explicit SessionsModel(QObject *parent = 0);
SessionsModel(const SessionsModel&) = delete;
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:
@ -43,12 +43,12 @@ signals:
public slots:
private:
QList< Session* > sessionsList;
QList<Session *> sessionsList;
private slots:
void RemoveSession( Session *argSession );
void RemoveSession(Session *argSession);
};
}
} // namespace lc
#endif // SESSIONSMODEL_H

@ -25,131 +25,152 @@
#include "client.h"
#include "settings.h"
lc::Settings::Settings( const QSettings &argSettings, QObject *argParent ) :
QObject{ argParent },
defaultReceiptIndex{ GetDefaultReceiptIndex( argSettings ) },
browserCmd{ ReadSettingsItem( "browser_command",
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",
argSettings, true)},
clientBrowserCmd{
ReadSettingsItem("client_browser_command",
"Opening a browser window on clients will not work.",
argSettings, false ) },
clientChromiumCmd{ ReadSettingsItem( "client_chromium_command",
"Opening a chromium window on clients will not work.",
argSettings, false ) },
dvipsCmd{ ReadSettingsItem( "dvips_command",
"Receipts creation will not work.",
argSettings, true ) },
fileMngr{ ReadSettingsItem( "file_manager",
argSettings, false)},
clientChromiumCmd{ReadSettingsItem(
"client_chromium_command",
"Opening a chromium 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",
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",
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",
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",
argSettings, false)},
orseeUrl{ReadSettingsItem("orsee_url",
"Opening ORSEE in a browser will not work.",
argSettings, false ) },
pingCmd{ ReadSettingsItem( "ping_command",
argSettings, false)},
pingCmd{ReadSettingsItem("ping_command",
"Status updates for the clients will not work.",
argSettings, true ) },
postscriptViewer{ ReadSettingsItem( "postscript_viewer",
argSettings, true)},
postscriptViewer{ReadSettingsItem(
"postscript_viewer",
"Viewing the generated receipts postscript file will not work.",
argSettings, true ) },
ps2pdfCmd{ ReadSettingsItem( "ps2pdf_command",
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",
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",
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",
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",
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",
argSettings, true)},
wakeonlanCmd{ReadSettingsItem("wakeonlan_command",
"Booting the clients will not work.",
argSettings, true ) },
webcamDisplayCmd{ ReadSettingsItem( "webcam_command",
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",
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",
argSettings, true)},
wmctrlCmd{ReadSettingsItem(
"wmctrl_command",
"Setting zTree's window title to its port number will not work.",
argSettings, true ) },
xsetCmd{ ReadSettingsItem( "xset_command",
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() ) {
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()) {
qDebug() << "'local_zLeaf_name' was not set, defaulting to 'local'";
localzLeafName = "local";
}
if ( webcams.isEmpty() ) {
qDebug() << "'webcams' was not properly set. No stationary webcams will be available.";
if (webcams.isEmpty()) {
qDebug() << "'webcams' was not properly set. No stationary webcams will be "
"available.";
} else {
qDebug() << "The following webcams where loaded:" << webcams;
}
@ -157,14 +178,16 @@ lc::Settings::Settings( const QSettings &argSettings, QObject *argParent ) :
}
lc::Settings::~Settings() {
for ( QVector< Client* >::iterator it = clients.begin(); it != clients.end(); ++it ) {
for (QVector<Client *>::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;
@ -173,89 +196,115 @@ 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::Client *> lc::Settings::CreateClients(const QSettings &argSettings,
const QString &argPingCmd) {
QVector<Client *> tempClientVec;
// Get the client quantity to check the value lists for clients creation for correct length
// Get the client quantity to check the value lists for clients creation for
// correct length
int clientQuantity = 0;
if ( !argSettings.contains("client_quantity" ) ) {
qWarning() << "'client_quantity' was not set. The client quantity will be guessed"
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();
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 ) {
qWarning() << "The quantity of client ips does not match the client quantity. Client"
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.";
return tempClientVec;
}
qDebug() << "Client IPs:" << clientIPs.join( " / " );
qDebug() << "Client IPs:" << clientIPs.join(" / ");
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"
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.";
return tempClientVec;
}
qDebug() << "Client MACs:" << clientMACs.join( " / " );
qDebug() << "Client MACs:" << clientMACs.join(" / ");
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"
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.";
return tempClientVec;
}
qDebug() << "Client names:" << clientNames.join( " / " );
qDebug() << "Client names:" << clientNames.join(" / ");
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.";
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.";
return tempClientVec;
}
qDebug() << "clientXPositions:" << clientXPositions.join( " / " );
qDebug() << "clientXPositions:" << clientXPositions.join(" / ");
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.";
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.";
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<Client *> &argClients) {
QMap<QString, Client *> 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<const void *>(tempMap[s->ip]);
qDebug() << "Added" << s->name
<< "to 'clientIPsToClientsMap':" << clientPtrAddr;
@ -264,18 +313,19 @@ QMap< QString, lc::Client* > lc::Settings::CreateClIPsToClMap( const QVector< Cl
}
QStringList lc::Settings::DetectInstalledLaTeXHeaders() const {
QStringList tempLaTeXHeaders{ "None found" };
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() ) {
qDebug() << "Receipts printing will not work. No LaTeX headers could be found in"
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;
@ -283,82 +333,88 @@ QStringList lc::Settings::DetectInstalledLaTeXHeaders() 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.";
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 ) {
qDebug() << "The 'client_help_server_port' variable was not set or set to zero."
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.";
return 0;
} else {
qDebug() << "'clientHelpNotificationServerPort':" << clientHelpNotificationServerPort;
qDebug() << "'clientHelpNotificationServerPort':"
<< clientHelpNotificationServerPort;
return clientHelpNotificationServerPort;
}
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" ) ) {
qDebug() << "The 'initial_port' variable was not set."
if (!argSettings.contains("initial_port")) {
qDebug()
<< "The 'initial_port' variable was not set."
" 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() };
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";
@ -366,17 +422,17 @@ QString lc::Settings::GetLocalUserName() {
return userName;
}
QString lc::Settings::ReadSettingsItem( const QString &argVariableName,
QString lc::Settings::ReadSettingsItem(const QString &argVariableName,
const QString &argMessage,
const QSettings &argSettings,
bool argItemIsFile) {
if ( !argSettings.contains( argVariableName ) ) {
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;
@ -384,11 +440,8 @@ QString lc::Settings::ReadSettingsItem( const QString &argVariableName,
return QString{};
}
void lc::Settings::SetLocalzLeafSize( QString arg) {
localzLeafSize = 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;
}

@ -33,18 +33,18 @@ class Settings : public QObject {
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; }
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;
@ -57,7 +57,7 @@ public:
const QString lcDataDir;
const QString localUserName;
QString localzLeafSize;
void SetLocalzLeafSize( QString arg);
void SetLocalzLeafSize(QString arg);
QString GetLocalzLeafSize() const { return localzLeafSize; }
const QString lprCmd;
const QString netstatCmd;
@ -91,38 +91,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<Client *> CreateClients(const QSettings &argSettings,
const QString &argPingCmd);
static QMap<QString, Client *>
CreateClIPsToClMap(const QVector<Client *> &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,
static QString ReadSettingsItem(const QString &argVariableName,
const QString &argMessage,
const QSettings &argSettings,
bool argItemIsFile );
bool argItemIsFile);
int chosenzTreePort = 0;
QVector< Client* > clients;
QVector<Client *> clients;
QString localzLeafName;
public:
const QMap< QString, Client* > clIPsToClMap;
const QMap<QString, Client *> clIPsToClMap;
};
}
} // namespace lc
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;
}

@ -24,28 +24,29 @@
#include "settings.h"
#include "ztree.h"
extern std::unique_ptr< lc::Settings > settings;
extern std::unique_ptr<lc::Settings> settings;
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 ) };
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)};
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(env);
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(" ");
}

@ -30,23 +30,23 @@ 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.
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

@ -21,49 +21,47 @@
#include <QMessageBox>
#include "Lib/settings.h"
#include "localzleafstarter.h"
#include "ui_localzleafstarter.h"
#include "Lib/settings.h"
extern std::unique_ptr< lc::Settings > settings;
extern std::unique_ptr<lc::Settings> settings;
lc::LocalzLeafStarter::LocalzLeafStarter( QWidget *argParent ) :
QWidget{ argParent },
ui{ new Ui::LocalzLeafStarter }
{
ui->setupUi( this );
lc::LocalzLeafStarter::LocalzLeafStarter(QWidget *argParent)
: QWidget{argParent}, ui{new Ui::LocalzLeafStarter} {
ui->setupUi(this);
//Choose initial port from settings
if ( settings->GetChosenZTreePort() ) {
ui->SBzLeafPort->setValue( settings->GetChosenZTreePort() );
// 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() );
// 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 );
ui->CBzLeafVersion->addItem(tr("Please choose a version"));
if (!settings->installedZTreeVersions.isEmpty()) {
ui->CBzLeafVersion->addItems(settings->installedZTreeVersions);
}
}
lc::LocalzLeafStarter::~LocalzLeafStarter() {
delete ui;
}
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 );
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() );
// 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() );
// Emit start local z-Leaf request to main window
emit LocalzLeafRequested(ui->LEzLeafName->text(),
ui->CBzLeafVersion->currentText(),
ui->SBzLeafPort->value());
}

@ -32,11 +32,12 @@ class LocalzLeafStarter : public QWidget {
Q_OBJECT
public:
explicit LocalzLeafStarter( QWidget *argParent = nullptr );
explicit LocalzLeafStarter(QWidget *argParent = nullptr);
~LocalzLeafStarter();
signals:
void LocalzLeafRequested( QString argzLeafName, QString argzLeafVersion, int argzTreePort );
void LocalzLeafRequested(QString argzLeafName, QString argzLeafVersion,
int argzTreePort);
private:
Ui::LocalzLeafStarter *ui = nullptr;
@ -45,6 +46,6 @@ private slots:
void on_PBStartLocalzLeaf_clicked();
};
}
} // namespace lc
#endif // LOCALZLEAFSTARTER_H

@ -21,14 +21,14 @@
#include <QApplication>
#include "mainwindow.h"
#include "Lib/settings.h"
#include "mainwindow.h"
std::unique_ptr< lc::Settings > settings;
std::unique_ptr<lc::Settings> 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.reset(new lc::Settings{QSettings{"Labcontrol", "Labcontrol"}});
lc::MainWindow w;
w.show();

File diff suppressed because it is too large Load Diff

@ -20,7 +20,15 @@
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
enum class icons_t : unsigned short int { UNKNOWN, OFF, DOWN, BOOT, ON, ZLEAF, ICON_QUANTITY };
enum class icons_t : unsigned short int {
UNKNOWN,
OFF,
DOWN,
BOOT,
ON,
ZLEAF,
ICON_QUANTITY
};
#include "Lib/client.h"
#include "Lib/lablib.h"
@ -45,13 +53,14 @@ class MainWindow;
//! The class containing the graphical user interface.
/*!
This class represents the graphical user interface and all connected functionality.
This class represents the graphical user interface and all connected
functionality.
*/
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow( QWidget *argParent = nullptr );
explicit MainWindow(QWidget *argParent = nullptr);
~MainWindow();
private slots:
@ -74,50 +83,64 @@ private slots:
void on_PBViewDesktopViewOnly_clicked();
void on_PBViewDesktopFullControl_clicked();
void on_RBUseLocalUser_toggled(bool checked);
void StartLocalzLeaf( QString argzLeafName, QString argzLeafVersion, int argzTreePort );
void StartLocalzLeaf(QString argzLeafName, QString argzLeafVersion,
int argzTreePort);
//! Updates the icons of the QTableView displaying the clients' states
/*!
* This function iterates over all valid items of the 'TVClients' and sets their states
* by querying the represented 'lcClient' instances.
* This function iterates over all valid items of the 'TVClients' and sets
* their states by querying the represented 'lcClient' instances.
*/
void UpdateClientsTableView();
signals:
/*Session actions*/
void RequestNewDataTargetPath();
void RequestNewSession( QVector< Client* > argAssocCl, QString argParticipNameReplacement,
void RequestNewSession(QVector<Client *> argAssocCl,
QString argParticipNameReplacement,
bool argPrintLocalReceipts, QString argReceiptsHeader,
QString argzTreeDataTargetPath, quint16 argzTreePort,
QString argzTreeVersion );
QString argzTreeVersion);
private:
//! Checks, if the user has administrative rights
/*!
@return Returns true, if the user has administrative rights (If the user is in the 'sudo' group)
@return Returns true, if the user has administrative rights (If the user is
in the 'sudo' group)
*/
bool CheckIfUserIsAdmin();
//! Disables widgets for functions not available due to lacking devices or settings
//! Disables widgets for functions not available due to lacking devices or
//! settings
void DisableDisfunctionalWidgets();
//! Loads all needed client icon QPixmaps
void LoadIconPixmaps();
//! 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
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<QStandardItem *> *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()'
QVector<QStandardItem *> *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()'
private slots:
void StartReceiptsHandler( QString argzTreeDataTargetPath,
void StartReceiptsHandler(QString argzTreeDataTargetPath,
bool argReceiptsForLocalClients,
QString argAnonymousReceiptsPlaceholder,
QString argLatexHeaderName,
QString argDateString );
QString argLatexHeaderName, QString argDateString);
void on_PBstartBrowser_clicked();
void on_PBstopBrowser_clicked();
@ -125,7 +148,7 @@ 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();
@ -133,6 +156,6 @@ private slots:
void on_PBDisableRMB_clicked();
};
}
} // namespace lc
#endif // MAINWINDOW_H

@ -21,79 +21,80 @@
#include <QFileDialog>
#include "Lib/settings.h"
#include "manualprintingsetup.h"
#include "ui_manualprintingsetup.h"
#include "Lib/settings.h"
extern std::unique_ptr< lc::Settings > settings;
extern std::unique_ptr<lc::Settings> settings;
lc::ManualPrintingSetup::ManualPrintingSetup( QWidget *argParent ) :
QWidget{ argParent },
ui{ new Ui::ManualPrintingSetup }
{
ui->setupUi( this );
lc::ManualPrintingSetup::ManualPrintingSetup(QWidget *argParent)
: QWidget{argParent}, ui{new Ui::ManualPrintingSetup} {
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"
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 );
" 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() {
delete ui;
}
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();
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(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(
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() {
QString anonymousReceiptsPlaceholder;
if ( ui->ChBPrintAnonymousReceipts->isChecked() ) {
if (ui->ChBPrintAnonymousReceipts->isChecked()) {
anonymousReceiptsPlaceholder = ui->CBReplaceParticipantNames->currentText();
}
emit RequestReceiptsHandler( workPath, ui->ChBReceiptsForLocalClients->isChecked(),
emit RequestReceiptsHandler(workPath,
ui->ChBReceiptsForLocalClients->isChecked(),
anonymousReceiptsPlaceholder,
ui->CBReceiptsHeader->currentText(), dateString );
ui->CBReceiptsHeader->currentText(), dateString);
this->deleteLater();
}

@ -32,15 +32,15 @@ class ManualPrintingSetup : public QWidget {
Q_OBJECT
public:
explicit ManualPrintingSetup( QWidget *argParent = nullptr );
explicit ManualPrintingSetup(QWidget *argParent = nullptr);
~ManualPrintingSetup();
signals:
void RequestReceiptsHandler( QString argzTreeDataTargetPath,
void RequestReceiptsHandler(QString argzTreeDataTargetPath,
bool argReceiptsForLocalClients,
QString argAnonymousReceiptsPlaceholder,
QString argLatexHeaderName,
QString argDateString );
QString argDateString);
private:
QString dateString;
@ -48,12 +48,12 @@ private:
QString workPath;
private slots:
void on_CBReceiptsHeader_activated( int argIndex );
void on_ChBPrintAnonymousReceipts_clicked( bool argChecked );
void on_CBReceiptsHeader_activated(int argIndex);
void on_ChBPrintAnonymousReceipts_clicked(bool argChecked);
void on_PBPrint_clicked();
void on_PBSelectFile_clicked();
};
}
} // namespace lc
#endif // MANUALPRINTINGSETUP_H

Loading…
Cancel
Save