1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2022 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU GENERAL PUBLIC LICENSE as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version; always including the non-optional
9 // LAMEXP GNU GENERAL PUBLIC LICENSE ADDENDUM. See "License.txt" file!
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Tool_Abstract.h"
29 #include <MUtils/Global.h>
30 #include <MUtils/OSSupport.h>
31 #include <MUtils/JobObject.h>
36 #include <QMutexLocker>
37 #include <QProcessEnvironment>
39 #include <QElapsedTimer>
44 QScopedPointer<MUtils::JobObject> AbstractTool::s_jobObjectInstance;
45 QScopedPointer<QElapsedTimer> AbstractTool::s_startProcessTimer;
50 QMutex AbstractTool::s_startProcessMutex;
51 QMutex AbstractTool::s_createObjectMutex;
56 quint64 AbstractTool::s_referenceCounter = 0ui64;
61 static const qint64 START_DELAY = 64i64; //in milliseconds
66 AbstractTool::AbstractTool(void)
71 QMutexLocker lock(&s_createObjectMutex);
73 if(s_referenceCounter++ == 0)
75 s_jobObjectInstance.reset(new MUtils::JobObject());
76 s_startProcessTimer.reset(new QElapsedTimer());
77 if(!MUtils::OS::setup_timer_resolution())
79 qWarning("Failed to setup system timer resolution!");
87 AbstractTool::~AbstractTool(void)
89 QMutexLocker lock(&s_createObjectMutex);
91 if(--s_referenceCounter == 0)
93 s_jobObjectInstance.reset(NULL);
94 s_startProcessTimer.reset(NULL);
95 if(!MUtils::OS::reset_timer_resolution())
97 qWarning("Failed to reset system timer resolution!");
103 * Initialize and launch process object
105 bool AbstractTool::startProcess(QProcess &process, const QString &program, const QStringList &args, const QString &workingDir)
107 QMutexLocker lock(&s_startProcessMutex);
109 if((!s_startProcessTimer.isNull()) && s_startProcessTimer->isValid())
111 qint64 elapsed = s_startProcessTimer->elapsed();
112 while(elapsed < START_DELAY)
115 MUtils::OS::sleep_ms((size_t)(START_DELAY - elapsed));
117 elapsed = s_startProcessTimer->elapsed();
121 emit messageLogged(commandline2string(program, args) + "\n");
122 MUtils::init_process(process, workingDir.isEmpty() ? QFileInfo(program).absolutePath() : workingDir);
124 process.start(program, args);
126 if(process.waitForStarted())
128 if(!s_jobObjectInstance.isNull())
130 if(!s_jobObjectInstance->addProcessToJob(&process))
132 qWarning("Failed to assign process to job object!");
136 MUtils::OS::change_process_priority(&process, -1);
140 emit statusUpdated(0);
141 m_firstLaunch = false;
144 s_startProcessTimer->start();
148 emit messageLogged("Process creation has failed :-(");
149 QString errorMsg= process.errorString().trimmed();
150 if(!errorMsg.isEmpty()) emit messageLogged(errorMsg);
153 process.waitForFinished(-1);
155 s_startProcessTimer->start();
160 * Wait for process to terminate while processing its output
162 AbstractTool::result_t AbstractTool::awaitProcess(QProcess &process, QAtomicInt &abortFlag, int *const exitCode)
164 return awaitProcess(process, abortFlag, [](const QString& /*text*/) { return false; }, exitCode);
168 * Wait for process to terminate while processing its output
170 AbstractTool::result_t AbstractTool::awaitProcess(QProcess &process, QAtomicInt &abortFlag, std::function<bool(const QString &text)> &&handler, int *const exitCode)
172 bool bTimeout = false;
173 bool bAborted = false;
177 while (process.state() != QProcess::NotRunning)
179 if (CHECK_FLAG(abortFlag))
183 emit messageLogged("\nABORTED BY USER !!!");
187 process.waitForReadyRead(m_processTimeoutInterval);
188 if (!process.bytesAvailable() && process.state() == QProcess::Running)
191 qWarning("Tool process timed out <-- killing!");
192 emit messageLogged("\nPROCESS TIMEOUT !!!");
197 while (process.bytesAvailable() > 0)
199 QByteArray line = process.readLine();
202 line.replace('\r', char(0x20)).replace('\b', char(0x20)).replace('\t', char(0x20));
203 const QString text = QString::fromUtf8(line.constData()).simplified();
208 if (text.compare(lastText, Qt::CaseInsensitive) != 0)
210 emit messageLogged(lastText = text);
218 process.waitForFinished();
219 if (process.state() != QProcess::NotRunning)
222 process.waitForFinished(-1);
227 *exitCode = process.exitCode();
230 emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));
231 if (!(bAborted || bTimeout)) emit statusUpdated(100);
233 if (bAborted || bTimeout || (process.exitCode() != EXIT_SUCCESS))
235 return bAborted ? RESULT_ABORTED : (bTimeout ? RESULT_TIMEOUT : RESULT_FAILURE);
238 return RESULT_SUCCESS;
242 * Convert program arguments to single string
244 QString AbstractTool::commandline2string(const QString &program, const QStringList &arguments)
246 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
248 for(int i = 0; i < arguments.count(); i++)
250 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));