3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Angus Leeming
8 * \author Enrico Forestieri
9 * \author Peter Kuemmel
11 * Full author contact details are available in file CREDITS.
16 #include "support/debug.h"
17 #include "support/lstrings.h"
18 #include "support/qstring_helpers.h"
19 #include "support/Systemcall.h"
20 #include "support/SystemcallPrivate.h"
21 #include "support/os.h"
30 #include <QCoreApplication>
36 struct Sleep : QThread
38 static void millisec(unsigned long ms)
40 QThread::usleep(ms * 1000);
55 int Systemcall::startscript(Starttype how, string const & what,
56 bool /*process_events*/)
58 string command = what;
60 if (how == DontWait) {
61 switch (os::shell()) {
66 command = "start /min " + command;
71 return ::system(command.c_str());
78 string const parsecmd(string const & cmd, string & outfile)
83 for (size_t i = 0; i < cmd.length(); ++i) {
85 if (c == '"' && !escaped)
87 else if (c == '\\' && !escaped)
89 else if (c == '>' && !(inquote || escaped)) {
90 outfile = trim(cmd.substr(i + 1), " \"");
91 return trim(cmd.substr(0, i));
103 int Systemcall::startscript(Starttype how, string const & what, bool process_events)
106 QString cmd = toqstr(parsecmd(what, outfile));
108 SystemcallPrivate d(outfile);
112 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
113 LYXERR0("Systemcall: '" << cmd << "' did not start!");
114 LYXERR0("error " << d.errorMessage());
118 if (how == DontWait) {
119 QProcess* released = d.releaseProcess();
120 (void) released; // TODO who deletes it?
124 if (!d.waitWhile(SystemcallPrivate::Running, process_events, 180000)) {
125 LYXERR0("Systemcall: '" << cmd << "' did not finished!");
126 LYXERR0("error " << d.errorMessage());
127 LYXERR0("status " << d.exitStatusMessage());
131 int const exit_code = d.exitCode();
133 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
140 SystemcallPrivate::SystemcallPrivate(const std::string& of) :
141 proc_(new QProcess), outindex_(0), errindex_(0),
142 outfile(of), showout_(false), showerr_(false), process_events(false)
144 if (!outfile.empty()) {
145 // Check whether we have to simply throw away the output.
146 if (outfile != os::nulldev())
147 proc_->setStandardOutputFile(toqstr(outfile));
148 } else if (os::is_terminal(os::STDOUT))
150 if (os::is_terminal(os::STDERR))
153 connect(proc_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
154 connect(proc_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
155 connect(proc_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
156 connect(proc_, SIGNAL(started()), this, SLOT(processStarted()));
157 connect(proc_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
162 void SystemcallPrivate::startProcess(const QString& cmd)
165 state = SystemcallPrivate::Starting;
171 void SystemcallPrivate::processEvents()
174 //static int count = 0; qDebug() << count++ << ": waitAndProcessEvents";
175 QCoreApplication::processEvents(QEventLoop::AllEvents);
180 void SystemcallPrivate::waitAndProcessEvents()
182 Sleep::millisec(100);
187 bool SystemcallPrivate::waitWhile(State waitwhile, bool proc_events, int timeout)
192 process_events = proc_events;
194 // Block GUI while waiting,
195 // relay on QProcess' wait functions
196 if (!process_events) {
197 if (waitwhile == Starting)
198 return proc_->waitForStarted(timeout);
199 if (waitwhile == Running)
200 return proc_->waitForFinished(timeout);
204 // process events while waiting, no timeout
206 while (state == waitwhile && state != Error) {
207 waitAndProcessEvents();
209 return state != Error;
212 // process events while waiting whith timeout
215 while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
216 waitAndProcessEvents();
218 return (state != Error) && (timer.elapsed() < timeout);
222 SystemcallPrivate::~SystemcallPrivate()
227 outdata_[outindex_] = '\0';
233 errdata_[errindex_] = '\0';
243 void SystemcallPrivate::flush()
246 // If the output has been redirected, we write it all at once.
247 // Even if we are not running in a terminal, the output could go
248 // to some log file, for example ~/.xsession-errors on *nix.
249 if (!os::is_terminal(os::STDOUT) && outfile.empty())
250 cout << fromqstr(QString::fromLocal8Bit(
251 proc_->readAllStandardOutput().data()));
252 if (!os::is_terminal(os::STDERR))
253 cerr << fromqstr(QString::fromLocal8Bit(
254 proc_->readAllStandardError().data()));
259 void SystemcallPrivate::stdOut()
261 if (proc_ && showout_) {
263 proc_->setReadChannel(QProcess::StandardOutput);
264 while (proc_->getChar(&c)) {
265 outdata_[outindex_++] = c;
266 if (c == '\n' || outindex_ + 1 == bufsize_) {
267 outdata_[outindex_] = '\0';
277 void SystemcallPrivate::stdErr()
279 if (proc_ && showerr_) {
281 proc_->setReadChannel(QProcess::StandardError);
282 while (proc_->getChar(&c)) {
283 errdata_[errindex_++] = c;
284 if (c == '\n' || errindex_ + 1 == bufsize_) {
285 errdata_[errindex_] = '\0';
295 void SystemcallPrivate::processStarted()
298 // why do we get two started signals?
299 //disconnect(proc_, SIGNAL(started()), this, SLOT(processStarted()));
303 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
309 void SystemcallPrivate::processError(QProcess::ProcessError)
315 QString SystemcallPrivate::errorMessage() const
318 return "No QProcess available";
321 switch (proc_->error()) {
322 case QProcess::FailedToStart:
323 message = "The process failed to start. Either the invoked program is missing, "
324 "or you may have insufficient permissions to invoke the program.";
326 case QProcess::Crashed:
327 message = "The process crashed some time after starting successfully.";
329 case QProcess::Timedout:
330 message = "The process timed out. It might be restarted automatically.";
332 case QProcess::WriteError:
333 message = "An error occurred when attempting to write to the process-> For example, "
334 "the process may not be running, or it may have closed its input channel.";
336 case QProcess::ReadError:
337 message = "An error occurred when attempting to read from the process-> For example, "
338 "the process may not be running.";
340 case QProcess::UnknownError:
342 message = "An unknown error occured.";
349 QString SystemcallPrivate::exitStatusMessage() const
352 return "No QProcess available";
355 switch (proc_->exitStatus()) {
356 case QProcess::NormalExit:
357 message = "The process exited normally.";
359 case QProcess::CrashExit:
360 message = "The process crashed.";
363 message = "Unknown exit state.";
370 int SystemcallPrivate::exitCode()
375 return proc_->exitCode();
379 QProcess* SystemcallPrivate::releaseProcess()
381 QProcess* released = proc_;
387 void SystemcallPrivate::killProcess()
393 void SystemcallPrivate::killProcess(QProcess * p)
397 p->closeReadChannel(QProcess::StandardOutput);
398 p->closeReadChannel(QProcess::StandardError);
406 #include "moc_SystemcallPrivate.cpp"
409 } // namespace support