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"
22 #include "support/ProgressInterface.h"
31 #include <QCoreApplication>
37 struct Sleep : QThread
39 static void millisec(unsigned long ms)
41 QThread::usleep(ms * 1000);
54 class ProgressDummy : public ProgressInterface
59 void processStarted(QString const &) {}
60 void processFinished(QString const &) {}
61 void appendMessage(QString const &) {}
62 void appendError(QString const &) {}
63 void clearMessages() {}
67 static ProgressInterface* progress_instance = 0;
69 void ProgressInterface::setInstance(ProgressInterface* p)
71 progress_instance = p;
75 ProgressInterface* ProgressInterface::instance()
77 if (!progress_instance) {
78 static ProgressDummy dummy;
81 return progress_instance;
89 int Systemcall::startscript(Starttype how, string const & what,
90 bool /*process_events*/)
92 string command = what;
94 if (how == DontWait) {
95 switch (os::shell()) {
100 command = "start /min " + command;
105 return ::system(command.c_str());
113 * This is a parser that (mostly) mimics the behavior of a posix shell but
114 * its output is tailored for being processed by QProcess.
116 * The escape character is the backslash.
117 * A backslash that is not quoted preserves the literal value of the following
118 * character, with the exception of a double-quote '"'. If a double-quote
119 * follows a backslash, it will be replaced by three consecutive double-quotes
120 * (this is how the QProcess parser recognizes a '"' as a simple character
121 * instead of a quoting character). Thus, for example:
127 * Characters enclosed in single-quotes ('') have their literal value preserved.
128 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
129 * be used to escape a single-quote in a single-quoted string. In other words,
130 * anything enclosed in single-quotes is passed as is, but the single-quotes
131 * themselves are eliminated. Thus, for example:
138 * Characters enclosed in double-quotes ("") have their literal value preserved,
139 * with the exception of the backslash. The backslash retains its special
140 * meaning as an escape character only when followed by a double-quote.
141 * Contrarily to the behavior of a posix shell, the double-quotes themselves
142 * are *not* eliminated. Thus, for example:
147 string const parsecmd(string const & inputcmd, string & outfile)
149 bool in_single_quote = false;
150 bool in_double_quote = false;
151 bool escaped = false;
154 for (size_t i = 0; i < inputcmd.length(); ++i) {
155 char c = inputcmd[i];
157 if (in_double_quote || escaped) {
158 if (in_double_quote && escaped)
162 in_single_quote = !in_single_quote;
166 if (in_single_quote) {
176 in_double_quote = !in_double_quote;
178 } else if (c == '\\' && !escaped) {
180 } else if (c == '>' && !(in_double_quote || escaped)) {
181 outfile = trim(inputcmd.substr(i + 1), " \"");
184 if (escaped && in_double_quote)
198 int Systemcall::startscript(Starttype how, string const & what, bool process_events)
201 QString cmd = toqstr(parsecmd(what, outfile));
203 SystemcallPrivate d(outfile);
207 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
208 LYXERR0("Systemcall: '" << cmd << "' did not start!");
209 LYXERR0("error " << d.errorMessage());
213 if (how == DontWait) {
214 QProcess* released = d.releaseProcess();
215 (void) released; // TODO who deletes it?
219 if (!d.waitWhile(SystemcallPrivate::Running, process_events, 180000)) {
220 LYXERR0("Systemcall: '" << cmd << "' did not finished!");
221 LYXERR0("error " << d.errorMessage());
222 LYXERR0("status " << d.exitStatusMessage());
226 int const exit_code = d.exitCode();
228 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
235 SystemcallPrivate::SystemcallPrivate(const std::string& of) :
236 proc_(new QProcess), outindex_(0), errindex_(0),
237 outfile(of), showout_(false), showerr_(false), process_events(false)
239 if (!outfile.empty()) {
240 // Check whether we have to simply throw away the output.
241 if (outfile != os::nulldev())
242 proc_->setStandardOutputFile(toqstr(outfile));
243 } else if (os::is_terminal(os::STDOUT))
245 if (os::is_terminal(os::STDERR))
248 connect(proc_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
249 connect(proc_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
250 connect(proc_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
251 connect(proc_, SIGNAL(started()), this, SLOT(processStarted()));
252 connect(proc_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
257 void SystemcallPrivate::startProcess(const QString& cmd)
261 state = SystemcallPrivate::Starting;
267 void SystemcallPrivate::processEvents()
270 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
275 void SystemcallPrivate::waitAndProcessEvents()
277 Sleep::millisec(100);
282 bool SystemcallPrivate::waitWhile(State waitwhile, bool proc_events, int timeout)
287 process_events = proc_events;
289 // Block GUI while waiting,
290 // relay on QProcess' wait functions
291 if (!process_events) {
292 if (waitwhile == Starting)
293 return proc_->waitForStarted(timeout);
294 if (waitwhile == Running)
295 return proc_->waitForFinished(timeout);
299 // process events while waiting, no timeout
301 while (state == waitwhile && state != Error) {
302 waitAndProcessEvents();
304 return state != Error;
307 // process events while waiting whith timeout
310 while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
311 waitAndProcessEvents();
313 return (state != Error) && (timer.elapsed() < timeout);
317 SystemcallPrivate::~SystemcallPrivate()
322 outdata_[outindex_] = '\0';
329 errdata_[errindex_] = '\0';
340 void SystemcallPrivate::flush()
343 // If the output has been redirected, we write it all at once.
344 // Even if we are not running in a terminal, the output could go
345 // to some log file, for example ~/.xsession-errors on *nix.
346 if (!os::is_terminal(os::STDOUT) && outfile.empty())
347 cout << fromqstr(QString::fromLocal8Bit(
348 proc_->readAllStandardOutput().data()));
349 if (!os::is_terminal(os::STDERR))
350 cerr << fromqstr(QString::fromLocal8Bit(
351 proc_->readAllStandardError().data()));
356 void SystemcallPrivate::stdOut()
360 proc_->setReadChannel(QProcess::StandardOutput);
361 while (proc_->getChar(&c)) {
362 outdata_[outindex_++] = c;
363 if (c == '\n' || outindex_ + 1 == bufsize_) {
364 outdata_[outindex_] = '\0';
371 const QString data = QString::fromLocal8Bit(outdata_);
373 ProgressInterface::instance()->appendMessage(data);
378 void SystemcallPrivate::stdErr()
382 proc_->setReadChannel(QProcess::StandardError);
383 while (proc_->getChar(&c)) {
384 errdata_[errindex_++] = c;
385 if (c == '\n' || errindex_ + 1 == bufsize_) {
386 errdata_[errindex_] = '\0';
393 const QString data = QString::fromLocal8Bit(errdata_);
395 ProgressInterface::instance()->appendError(data);
400 void SystemcallPrivate::processStarted()
403 ProgressInterface::instance()->processStarted(cmd_);
407 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
410 ProgressInterface::instance()->processFinished(cmd_);
414 void SystemcallPrivate::processError(QProcess::ProcessError)
417 ProgressInterface::instance()->appendError(errorMessage());
421 QString SystemcallPrivate::errorMessage() const
424 return "No QProcess available";
427 switch (proc_->error()) {
428 case QProcess::FailedToStart:
429 message = "The process failed to start. Either the invoked program is missing, "
430 "or you may have insufficient permissions to invoke the program.";
432 case QProcess::Crashed:
433 message = "The process crashed some time after starting successfully.";
435 case QProcess::Timedout:
436 message = "The process timed out. It might be restarted automatically.";
438 case QProcess::WriteError:
439 message = "An error occurred when attempting to write to the process-> For example, "
440 "the process may not be running, or it may have closed its input channel.";
442 case QProcess::ReadError:
443 message = "An error occurred when attempting to read from the process-> For example, "
444 "the process may not be running.";
446 case QProcess::UnknownError:
448 message = "An unknown error occured.";
455 QString SystemcallPrivate::exitStatusMessage() const
458 return "No QProcess available";
461 switch (proc_->exitStatus()) {
462 case QProcess::NormalExit:
463 message = "The process exited normally.";
465 case QProcess::CrashExit:
466 message = "The process crashed.";
469 message = "Unknown exit state.";
476 int SystemcallPrivate::exitCode()
481 return proc_->exitCode();
485 QProcess* SystemcallPrivate::releaseProcess()
487 QProcess* released = proc_;
493 void SystemcallPrivate::killProcess()
499 void SystemcallPrivate::killProcess(QProcess * p)
503 p->closeReadChannel(QProcess::StandardOutput);
504 p->closeReadChannel(QProcess::StandardError);
512 #include "moc_SystemcallPrivate.cpp"
515 } // namespace support