refactor: Get process IDs by iterating /proc. Improve readability in JsonConnection option handling. (#843)

Co-authored-by: brindosch <edeltraud70@gmx.de>
This commit is contained in:
Murat Seker 2020-06-29 22:55:12 +02:00 committed by GitHub
parent 26813be36a
commit 6cf9dfaa68
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 60 additions and 107 deletions

View File

@ -1,5 +1,4 @@
// QT includes // QT includes
#include <QCoreApplication> #include <QCoreApplication>
#include <QImage> #include <QImage>

View File

@ -121,7 +121,7 @@ void JsonConnection::setImage(QImage &image, int priority, int duration)
void JsonConnection::setEffect(const QString &effectName, const QString & effectArgs, int priority, int duration) void JsonConnection::setEffect(const QString &effectName, const QString & effectArgs, int priority, int duration)
{ {
qDebug() << "Start effect " << effectName; qDebug() << "Start effect " << effectName;
// create command // create command
QJsonObject command, effect; QJsonObject command, effect;
@ -157,7 +157,7 @@ void JsonConnection::setEffect(const QString &effectName, const QString & effect
void JsonConnection::createEffect(const QString &effectName, const QString &effectScript, const QString & effectArgs) void JsonConnection::createEffect(const QString &effectName, const QString &effectScript, const QString & effectArgs)
{ {
qDebug() << "Create effect " << effectName; qDebug() << "Create effect " << effectName;
// create command // create command
QJsonObject effect; QJsonObject effect;
@ -185,7 +185,7 @@ void JsonConnection::createEffect(const QString &effectName, const QString &effe
void JsonConnection::deleteEffect(const QString &effectName) void JsonConnection::deleteEffect(const QString &effectName)
{ {
qDebug() << "Delete effect configuration" << effectName; qDebug() << "Delete effect configuration" << effectName;
// create command // create command
QJsonObject effect; QJsonObject effect;
@ -372,7 +372,6 @@ void JsonConnection::setConfig(const QString &jsonString)
command["command"] = QString("config"); command["command"] = QString("config");
command["subcommand"] = QString("setconfig"); command["subcommand"] = QString("setconfig");
if (jsonString.size() > 0) if (jsonString.size() > 0)
{ {
QJsonObject configObj; QJsonObject configObj;
@ -384,9 +383,6 @@ void JsonConnection::setConfig(const QString &jsonString)
command["config"] = configObj; command["config"] = configObj;
} }
// send command message // send command message
QJsonObject reply = sendMessage(command); QJsonObject reply = sendMessage(command);
@ -423,72 +419,26 @@ void JsonConnection::setAdjustment(
adjust["id"] = adjustmentId; adjust["id"] = adjustmentId;
} }
if (redAdjustment.isValid()) const auto addAdjustmentIfValid = [&] (const QString & name, const QColor & adjustment) {
{ if (adjustment.isValid())
QJsonArray red; {
red.append(redAdjustment.red()); QJsonArray color;
red.append(redAdjustment.green()); color.append(adjustment.red());
red.append(redAdjustment.blue()); color.append(adjustment.green());
adjust["red"] = red; color.append(adjustment.blue());
} adjust[name] = color;
}
};
if (greenAdjustment.isValid()) addAdjustmentIfValid("red", redAdjustment);
{ addAdjustmentIfValid("green", greenAdjustment);
QJsonArray green; addAdjustmentIfValid("blue", blueAdjustment);
green.append(greenAdjustment.red()); addAdjustmentIfValid("cyan", cyanAdjustment);
green.append(greenAdjustment.green()); addAdjustmentIfValid("magenta", magentaAdjustment);
green.append(greenAdjustment.blue()); addAdjustmentIfValid("yellow", yellowAdjustment);
adjust["green"] = green; addAdjustmentIfValid("white", whiteAdjustment);
} addAdjustmentIfValid("black", blackAdjustment);
if (blueAdjustment.isValid())
{
QJsonArray blue;
blue.append(blueAdjustment.red());
blue.append(blueAdjustment.green());
blue.append(blueAdjustment.blue());
adjust["blue"] = blue;
}
if (cyanAdjustment.isValid())
{
QJsonArray cyan;
cyan.append(cyanAdjustment.red());
cyan.append(cyanAdjustment.green());
cyan.append(cyanAdjustment.blue());
adjust["cyan"] = cyan;
}
if (magentaAdjustment.isValid())
{
QJsonArray magenta;
magenta.append(magentaAdjustment.red());
magenta.append(magentaAdjustment.green());
magenta.append(magentaAdjustment.blue());
adjust["magenta"] = magenta;
}
if (yellowAdjustment.isValid())
{
QJsonArray yellow;
yellow.append(yellowAdjustment.red());
yellow.append(yellowAdjustment.green());
yellow.append(yellowAdjustment.blue());
adjust["yellow"] = yellow;
}
if (whiteAdjustment.isValid())
{
QJsonArray white;
white.append(whiteAdjustment.red());
white.append(whiteAdjustment.green());
white.append(whiteAdjustment.blue());
adjust["white"] = white;
}
if (blackAdjustment.isValid())
{
QJsonArray black;
black.append(blackAdjustment.red());
black.append(blackAdjustment.green());
black.append(blackAdjustment.blue());
adjust["black"] = black;
}
if (backlightThreshold != nullptr) if (backlightThreshold != nullptr)
{ {
adjust["backlightThreshold"] = *backlightThreshold; adjust["backlightThreshold"] = *backlightThreshold;

View File

@ -46,7 +46,7 @@ bool ScreenshotHandler::findNoSignalSettings(const Image<ColorRgb> & image)
ColorRgb redThresoldColor = {255,75,75}; ColorRgb redThresoldColor = {255,75,75};
ColorRgb greenThresoldColor = {75,255,75}; ColorRgb greenThresoldColor = {75,255,75};
ColorRgb blueThresoldColor = {75,75,255}; ColorRgb blueThresoldColor = {75,75,255};
QVector<unsigned> redOffsets; QVector<unsigned> redOffsets;
QVector<unsigned> redCounts; QVector<unsigned> redCounts;
QVector<unsigned> greenOffsets; QVector<unsigned> greenOffsets;
@ -203,7 +203,7 @@ bool ScreenshotHandler::findNoSignalSettings(const Image<ColorRgb> & image)
{ {
std::cout << "WARNING difference between threshold color and the other color components is to small, signal detection might have problems." << std::endl; std::cout << "WARNING difference between threshold color and the other color components is to small, signal detection might have problems." << std::endl;
} }
if (thresholdGreen > thresholdRed && thresholdGreen > thresholdBlue && ((thresholdGreen-thresholdRed) <= 0.5 || (thresholdGreen-thresholdBlue) <= 0.5)) if (thresholdGreen > thresholdRed && thresholdGreen > thresholdBlue && ((thresholdGreen-thresholdRed) <= 0.5 || (thresholdGreen-thresholdBlue) <= 0.5))
{ {
std::cout << "WARNING difference between threshold color and the other color components is to small, signal detection might have problems." << std::endl; std::cout << "WARNING difference between threshold color and the other color components is to small, signal detection might have problems." << std::endl;

View File

@ -67,8 +67,8 @@ int main(int argc, char ** argv)
parser.isSet(argCropBottom) ? argCropBottom.getInt(parser) : argCropHeight.getInt(parser), parser.isSet(argCropBottom) ? argCropBottom.getInt(parser) : argCropHeight.getInt(parser),
argSizeDecimation.getInt(parser)); // decimation argSizeDecimation.getInt(parser)); // decimation
if (!x11Wrapper.displayInit()) if (!x11Wrapper.displayInit())
return -1; return -1;
if (parser.isSet(argScreenshot)) if (parser.isSet(argScreenshot))
{ {

View File

@ -1,8 +1,11 @@
#pragma once #pragma once
#include <QString>
#include <QProcess>
#include <QByteArray> #include <QByteArray>
#include <QDir>
#include <QFile>
#include <QRegExp>
#include <QString>
#include <QTextStream>
#ifdef WIN32 #ifdef WIN32
// psapi.h requires windows.h to be included // psapi.h requires windows.h to be included
@ -12,7 +15,6 @@
unsigned int getProcessIdsByProcessName(const char *processName, QStringList &listOfPids) unsigned int getProcessIdsByProcessName(const char *processName, QStringList &listOfPids)
{ {
// Clear content of returned list of PIDS // Clear content of returned list of PIDS
listOfPids.clear(); listOfPids.clear();
@ -57,33 +59,36 @@ unsigned int getProcessIdsByProcessName(const char *processName, QStringList &li
} }
} }
return listOfPids.count();
#else #else
// Run pgrep, which looks through the currently running processses and lists the process IDs QDir dir("/proc");
// which match the selection criteria to stdout. dir.setFilter(QDir::Dirs);
QProcess process; dir.setSorting(QDir::Name | QDir::Reversed);
process.start("pgrep", QStringList() << processName);
process.waitForReadyRead();
QByteArray bytes = process.readAllStandardOutput(); for (const QString & pid : dir.entryList()) {
QRegExp regexp("\\d*");
if (!regexp.exactMatch(pid))
{
/* Not a number, can not be PID */
continue;
}
process.terminate(); QFile cmdline("/proc/" + pid + "/cmdline");
process.waitForFinished(); if (!cmdline.open(QFile::ReadOnly | QFile::Text))
process.kill(); {
/* Can not open cmdline file */
continue;
}
// Output is something like "2472\n2323" for multiple instances QTextStream in(&cmdline);
if (bytes.isEmpty()) QString command = in.readAll();
return 0; if (command.startsWith(processName))
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) listOfPids.push_back(pid);
listOfPids = QString(bytes).split("\n", Qt::SkipEmptyParts); }
#else }
listOfPids = QString(bytes).split("\n", QString::SkipEmptyParts);
#endif
return listOfPids.count();
#endif #endif
return listOfPids.count();
} }

View File

@ -153,7 +153,6 @@ int main(int argc, char** argv)
Logger::setLogLevel(Logger::WARNING); Logger::setLogLevel(Logger::WARNING);
// check if we are running already an instance // check if we are running already an instance
// TODO Do not use pgrep on linux, instead iter /proc
// TODO Allow one session per user // TODO Allow one session per user
// http://www.qtcentre.org/threads/44489-Get-Process-ID-for-a-running-application // http://www.qtcentre.org/threads/44489-Get-Process-ID-for-a-running-application
QStringList listOfPids; QStringList listOfPids;
@ -196,8 +195,8 @@ int main(int argc, char** argv)
BooleanOption & silentOption = parser.add<BooleanOption> ('s', "silent", "do not print any outputs"); BooleanOption & silentOption = parser.add<BooleanOption> ('s', "silent", "do not print any outputs");
BooleanOption & verboseOption = parser.add<BooleanOption> ('v', "verbose", "Increase verbosity"); BooleanOption & verboseOption = parser.add<BooleanOption> ('v', "verbose", "Increase verbosity");
BooleanOption & debugOption = parser.add<BooleanOption> ('d', "debug", "Show debug messages"); BooleanOption & debugOption = parser.add<BooleanOption> ('d', "debug", "Show debug messages");
parser.add<BooleanOption> (0x0, "desktop", "show systray on desktop"); parser.add<BooleanOption> (0x0, "desktop", "show systray on desktop");
parser.add<BooleanOption> (0x0, "service", "force hyperion to start as console service"); parser.add<BooleanOption> (0x0, "service", "force hyperion to start as console service");
Option & exportEfxOption = parser.add<Option> (0x0, "export-effects", "export effects to given path"); Option & exportEfxOption = parser.add<Option> (0x0, "export-effects", "export effects to given path");
parser.process(*qApp); parser.process(*qApp);

View File

@ -88,7 +88,7 @@ void SysTray::createTrayIcon()
connect(efxAction, SIGNAL(triggered()), this, SLOT(setEffect())); connect(efxAction, SIGNAL(triggered()), this, SLOT(setEffect()));
_trayIconEfxMenu->addAction(efxAction); _trayIconEfxMenu->addAction(efxAction);
} }
_trayIconMenu->addAction(settingsAction); _trayIconMenu->addAction(settingsAction);
_trayIconMenu->addSeparator(); _trayIconMenu->addSeparator();
_trayIconMenu->addAction(colorAction); _trayIconMenu->addAction(colorAction);
@ -104,7 +104,7 @@ void SysTray::createTrayIcon()
void SysTray::setColor(const QColor & color) void SysTray::setColor(const QColor & color)
{ {
std::vector<ColorRgb> rgbColor{ ColorRgb{ (uint8_t)color.red(), (uint8_t)color.green(), (uint8_t)color.blue() } }; std::vector<ColorRgb> rgbColor{ ColorRgb{ (uint8_t)color.red(), (uint8_t)color.green(), (uint8_t)color.blue() } };
_hyperion->setColor(1 ,rgbColor, 0); _hyperion->setColor(1 ,rgbColor, 0);
} }
@ -149,7 +149,7 @@ void SysTray::settings()
#endif #endif
QDesktopServices::openUrl(QUrl("http://localhost:"+QString::number(_webPort)+"/", QUrl::TolerantMode)); QDesktopServices::openUrl(QUrl("http://localhost:"+QString::number(_webPort)+"/", QUrl::TolerantMode));
#ifndef _WIN32 #ifndef _WIN32
// restoring stdout // restoring stdout
::dup2(saved_stdout, STDOUT_FILENO); ::dup2(saved_stdout, STDOUT_FILENO);