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() {}
66 void lyxerrConnect() {}
67 void lyxerrDisconnect() {}
69 void warning(QString const &, QString const &) {}
70 void toggleWarning(QString const &, QString const &, QString const &) {}
71 void error(QString const &, QString const &) {}
72 void information(QString const &, QString const &) {}
76 static ProgressInterface* progress_instance = 0;
78 void ProgressInterface::setInstance(ProgressInterface* p)
80 progress_instance = p;
84 ProgressInterface* ProgressInterface::instance()
86 if (!progress_instance) {
87 static ProgressDummy dummy;
90 return progress_instance;
98 int Systemcall::startscript(Starttype how, string const & what,
99 bool /*process_events*/)
101 string command = what;
103 if (how == DontWait) {
104 switch (os::shell()) {
109 command = "start /min " + command;
114 return ::system(command.c_str());
122 * This is a parser that (mostly) mimics the behavior of a posix shell but
123 * its output is tailored for being processed by QProcess.
125 * The escape character is the backslash.
126 * A backslash that is not quoted preserves the literal value of the following
127 * character, with the exception of a double-quote '"'. If a double-quote
128 * follows a backslash, it will be replaced by three consecutive double-quotes
129 * (this is how the QProcess parser recognizes a '"' as a simple character
130 * instead of a quoting character). Thus, for example:
136 * Characters enclosed in single-quotes ('') have their literal value preserved.
137 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
138 * be used to escape a single-quote in a single-quoted string. In other words,
139 * anything enclosed in single-quotes is passed as is, but the single-quotes
140 * themselves are eliminated. Thus, for example:
147 * Characters enclosed in double-quotes ("") have their literal value preserved,
148 * with the exception of the backslash. The backslash retains its special
149 * meaning as an escape character only when followed by a double-quote.
150 * Contrarily to the behavior of a posix shell, the double-quotes themselves
151 * are *not* eliminated. Thus, for example:
156 string const parsecmd(string const & inputcmd, string & outfile)
158 bool in_single_quote = false;
159 bool in_double_quote = false;
160 bool escaped = false;
163 for (size_t i = 0; i < inputcmd.length(); ++i) {
164 char c = inputcmd[i];
166 if (in_double_quote || escaped) {
167 if (in_double_quote && escaped)
171 in_single_quote = !in_single_quote;
175 if (in_single_quote) {
185 in_double_quote = !in_double_quote;
187 } else if (c == '\\' && !escaped) {
189 } else if (c == '>' && !(in_double_quote || escaped)) {
190 outfile = trim(inputcmd.substr(i + 1), " \"");
193 if (escaped && in_double_quote)
207 int Systemcall::startscript(Starttype how, string const & what, bool process_events)
210 QString cmd = toqstr(parsecmd(what, outfile));
212 SystemcallPrivate d(outfile);
216 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
217 LYXERR0("Systemcall: '" << cmd << "' did not start!");
218 LYXERR0("error " << d.errorMessage());
222 if (how == DontWait) {
223 QProcess* released = d.releaseProcess();
224 (void) released; // TODO who deletes it?
228 if (!d.waitWhile(SystemcallPrivate::Running, process_events, 180000)) {
229 LYXERR0("Systemcall: '" << cmd << "' did not finished!");
230 LYXERR0("error " << d.errorMessage());
231 LYXERR0("status " << d.exitStatusMessage());
235 int const exit_code = d.exitCode();
237 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
244 SystemcallPrivate::SystemcallPrivate(const std::string& of) :
245 proc_(new QProcess), outindex_(0), errindex_(0),
247 terminalOutExists_(os::is_terminal(os::STDOUT)),
248 terminalErrExists_(os::is_terminal(os::STDERR)),
249 process_events(false)
251 if (!outfile.empty()) {
252 // Check whether we have to simply throw away the output.
253 if (outfile != os::nulldev())
254 proc_->setStandardOutputFile(toqstr(outfile));
257 connect(proc_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
258 connect(proc_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
259 connect(proc_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
260 connect(proc_, SIGNAL(started()), this, SLOT(processStarted()));
261 connect(proc_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
266 void SystemcallPrivate::startProcess(const QString& cmd)
270 state = SystemcallPrivate::Starting;
276 void SystemcallPrivate::processEvents()
279 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
284 void SystemcallPrivate::waitAndProcessEvents()
286 Sleep::millisec(100);
291 bool SystemcallPrivate::waitWhile(State waitwhile, bool proc_events, int timeout)
296 process_events = proc_events;
298 // Block GUI while waiting,
299 // relay on QProcess' wait functions
300 if (!process_events) {
301 if (waitwhile == Starting)
302 return proc_->waitForStarted(timeout);
303 if (waitwhile == Running)
304 return proc_->waitForFinished(timeout);
308 // process events while waiting, no timeout
310 while (state == waitwhile && state != Error) {
311 waitAndProcessEvents();
313 return state != Error;
316 // process events while waiting whith timeout
319 while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
320 waitAndProcessEvents();
322 return (state != Error) && (timer.elapsed() < timeout);
326 SystemcallPrivate::~SystemcallPrivate()
331 outdata_[outindex_] = '\0';
333 if (terminalOutExists_)
338 errdata_[errindex_] = '\0';
340 if (terminalErrExists_)
349 void SystemcallPrivate::flush()
352 // If the output has been redirected, we write it all at once.
353 // Even if we are not running in a terminal, the output could go
354 // to some log file, for example ~/.xsession-errors on *nix.
356 QString data = QString::fromLocal8Bit(proc_->readAllStandardOutput().data());
357 ProgressInterface::instance()->appendMessage(data);
358 if (!terminalOutExists_ && outfile.empty())
359 cout << fromqstr(data);
361 data = QString::fromLocal8Bit(proc_->readAllStandardError().data());
362 ProgressInterface::instance()->appendError(data);
363 if (!terminalErrExists_)
364 cerr << fromqstr(data);
369 void SystemcallPrivate::stdOut()
373 proc_->setReadChannel(QProcess::StandardOutput);
374 while (proc_->getChar(&c)) {
375 outdata_[outindex_++] = c;
376 if (c == '\n' || outindex_ + 1 == bufsize_) {
377 outdata_[outindex_] = '\0';
379 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(outdata_));
380 if (terminalOutExists_)
388 void SystemcallPrivate::stdErr()
392 proc_->setReadChannel(QProcess::StandardError);
393 while (proc_->getChar(&c)) {
394 errdata_[errindex_++] = c;
395 if (c == '\n' || errindex_ + 1 == bufsize_) {
396 errdata_[errindex_] = '\0';
398 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(errdata_));
399 if (terminalErrExists_)
407 void SystemcallPrivate::processStarted()
409 if (state != Running) {
411 ProgressInterface::instance()->processStarted(cmd_);
416 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
418 if (state != Finished) {
420 ProgressInterface::instance()->processFinished(cmd_);
425 void SystemcallPrivate::processError(QProcess::ProcessError)
428 ProgressInterface::instance()->appendError(errorMessage());
432 QString SystemcallPrivate::errorMessage() const
435 return "No QProcess available";
438 switch (proc_->error()) {
439 case QProcess::FailedToStart:
440 message = "The process failed to start. Either the invoked program is missing, "
441 "or you may have insufficient permissions to invoke the program.";
443 case QProcess::Crashed:
444 message = "The process crashed some time after starting successfully.";
446 case QProcess::Timedout:
447 message = "The process timed out. It might be restarted automatically.";
449 case QProcess::WriteError:
450 message = "An error occurred when attempting to write to the process-> For example, "
451 "the process may not be running, or it may have closed its input channel.";
453 case QProcess::ReadError:
454 message = "An error occurred when attempting to read from the process-> For example, "
455 "the process may not be running.";
457 case QProcess::UnknownError:
459 message = "An unknown error occured.";
466 QString SystemcallPrivate::exitStatusMessage() const
469 return "No QProcess available";
472 switch (proc_->exitStatus()) {
473 case QProcess::NormalExit:
474 message = "The process exited normally.";
476 case QProcess::CrashExit:
477 message = "The process crashed.";
480 message = "Unknown exit state.";
487 int SystemcallPrivate::exitCode()
492 return proc_->exitCode();
496 QProcess* SystemcallPrivate::releaseProcess()
498 QProcess* released = proc_;
504 void SystemcallPrivate::killProcess()
510 void SystemcallPrivate::killProcess(QProcess * p)
514 p->closeReadChannel(QProcess::StandardOutput);
515 p->closeReadChannel(QProcess::StandardError);
523 #include "moc_SystemcallPrivate.cpp"
526 } // namespace support