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/filetools.h"
18 #include "support/lstrings.h"
19 #include "support/qstring_helpers.h"
20 #include "support/Systemcall.h"
21 #include "support/SystemcallPrivate.h"
22 #include "support/os.h"
23 #include "support/ProgressInterface.h"
33 #include <QCoreApplication>
39 struct Sleep : QThread
41 static void millisec(unsigned long ms)
43 QThread::usleep(ms * 1000);
56 class ProgressDummy : public ProgressInterface
61 void processStarted(QString const &) {}
62 void processFinished(QString const &) {}
63 void appendMessage(QString const &) {}
64 void appendError(QString const &) {}
65 void clearMessages() {}
68 void lyxerrConnect() {}
69 void lyxerrDisconnect() {}
71 void warning(QString const &, QString const &) {}
72 void toggleWarning(QString const &, QString const &, QString const &) {}
73 void error(QString const &, QString const &) {}
74 void information(QString const &, QString const &) {}
78 static ProgressInterface* progress_instance = 0;
80 void ProgressInterface::setInstance(ProgressInterface* p)
82 progress_instance = p;
86 ProgressInterface* ProgressInterface::instance()
88 if (!progress_instance) {
89 static ProgressDummy dummy;
92 return progress_instance;
100 int Systemcall::startscript(Starttype how, string const & what,
101 std::string const & path, bool /*process_events*/)
103 string const python_call = "python -tt";
104 string command = to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path)));
106 if (prefixIs(what, python_call))
107 command += os::python() + what.substr(python_call.length());
111 if (how == DontWait) {
112 switch (os::shell()) {
117 command = "start /min " + command;
120 } else if (os::shell() == os::CMD_EXE)
121 command = subst(command, "cmd /d /c ", "");
123 return ::system(command.c_str());
131 * This is a parser that (mostly) mimics the behavior of a posix shell but
132 * its output is tailored for being processed by QProcess.
134 * The escape character is the backslash.
135 * A backslash that is not quoted preserves the literal value of the following
136 * character, with the exception of a double-quote '"'. If a double-quote
137 * follows a backslash, it will be replaced by three consecutive double-quotes
138 * (this is how the QProcess parser recognizes a '"' as a simple character
139 * instead of a quoting character). Thus, for example:
145 * Characters enclosed in single-quotes ('') have their literal value preserved.
146 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
147 * be used to escape a single-quote in a single-quoted string. In other words,
148 * anything enclosed in single-quotes is passed as is, but the single-quotes
149 * themselves are eliminated. Thus, for example:
156 * Characters enclosed in double-quotes ("") have their literal value preserved,
157 * with the exception of the backslash. The backslash retains its special
158 * meaning as an escape character only when followed by a double-quote.
159 * Contrarily to the behavior of a posix shell, the double-quotes themselves
160 * are *not* eliminated. Thus, for example:
165 string const parsecmd(string const & inputcmd, string & outfile)
167 bool in_single_quote = false;
168 bool in_double_quote = false;
169 bool escaped = false;
170 string const python_call = "python -tt";
174 if (prefixIs(inputcmd, python_call)) {
176 start = python_call.length();
179 for (size_t i = start; i < inputcmd.length(); ++i) {
180 char c = inputcmd[i];
182 if (in_double_quote || escaped) {
183 if (in_double_quote && escaped)
187 in_single_quote = !in_single_quote;
191 if (in_single_quote) {
201 in_double_quote = !in_double_quote;
203 } else if (c == '\\' && !escaped) {
205 } else if (c == '>' && !(in_double_quote || escaped)) {
206 outfile = trim(inputcmd.substr(i + 1), " \"");
209 if (escaped && in_double_quote)
223 int Systemcall::startscript(Starttype how, string const & what,
224 string const & path, bool process_events)
227 QString cmd = QString::fromLocal8Bit(parsecmd(what, outfile).c_str());
229 SystemcallPrivate d(outfile);
232 d.startProcess(cmd, path);
233 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
234 LYXERR0("Systemcall: '" << cmd << "' did not start!");
235 LYXERR0("error " << d.errorMessage());
239 if (how == DontWait) {
240 QProcess* released = d.releaseProcess();
241 (void) released; // TODO who deletes it?
245 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
246 os::timeout_min() * 60 * 1000)) {
247 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
248 LYXERR0("error " << d.errorMessage());
249 LYXERR0("status " << d.exitStatusMessage());
253 int const exit_code = d.exitCode();
255 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
262 SystemcallPrivate::SystemcallPrivate(const std::string& of) :
263 process_(new QProcess),
267 process_events_(false)
269 if (!out_file_.empty()) {
270 // Check whether we have to simply throw away the output.
271 if (out_file_ != os::nulldev())
272 process_->setStandardOutputFile(QString::fromLocal8Bit(out_file_.c_str()));
275 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
276 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
277 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
278 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
279 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
283 void SystemcallPrivate::startProcess(QString const & cmd, string const & path)
287 state = SystemcallPrivate::Starting;
288 process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
293 void SystemcallPrivate::processEvents()
295 if(process_events_) {
296 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
301 void SystemcallPrivate::waitAndProcessEvents()
303 Sleep::millisec(100);
308 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
313 process_events_ = process_events;
315 // Block GUI while waiting,
316 // relay on QProcess' wait functions
317 if (!process_events_) {
318 if (waitwhile == Starting)
319 return process_->waitForStarted(timeout);
320 if (waitwhile == Running)
321 return process_->waitForFinished(timeout);
325 // process events while waiting, no timeout
327 while (state == waitwhile && state != Error) {
328 waitAndProcessEvents();
330 return state != Error;
333 // process events while waiting whith timeout
336 while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
337 waitAndProcessEvents();
339 return (state != Error) && (timer.elapsed() < timeout);
343 SystemcallPrivate::~SystemcallPrivate()
346 out_data_[out_index_] = '\0';
352 err_data_[err_index_] = '\0';
362 void SystemcallPrivate::stdOut()
366 process_->setReadChannel(QProcess::StandardOutput);
367 while (process_->getChar(&c)) {
368 out_data_[out_index_++] = c;
369 if (c == '\n' || out_index_ + 1 == buffer_size_) {
370 out_data_[out_index_] = '\0';
372 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
380 void SystemcallPrivate::stdErr()
384 process_->setReadChannel(QProcess::StandardError);
385 while (process_->getChar(&c)) {
386 err_data_[err_index_++] = c;
387 if (c == '\n' || err_index_ + 1 == buffer_size_) {
388 err_data_[err_index_] = '\0';
390 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
398 void SystemcallPrivate::processStarted()
400 if (state != Running) {
402 ProgressInterface::instance()->processStarted(cmd_);
407 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
409 if (state != Finished) {
411 ProgressInterface::instance()->processFinished(cmd_);
416 void SystemcallPrivate::processError(QProcess::ProcessError)
419 ProgressInterface::instance()->appendError(errorMessage());
423 QString SystemcallPrivate::errorMessage() const
426 return "No QProcess available";
429 switch (process_->error()) {
430 case QProcess::FailedToStart:
431 message = "The process failed to start. Either the invoked program is missing, "
432 "or you may have insufficient permissions to invoke the program.";
434 case QProcess::Crashed:
435 message = "The process crashed some time after starting successfully.";
437 case QProcess::Timedout:
438 message = "The process timed out. It might be restarted automatically.";
440 case QProcess::WriteError:
441 message = "An error occurred when attempting to write to the process-> For example, "
442 "the process may not be running, or it may have closed its input channel.";
444 case QProcess::ReadError:
445 message = "An error occurred when attempting to read from the process-> For example, "
446 "the process may not be running.";
448 case QProcess::UnknownError:
450 message = "An unknown error occured.";
457 QString SystemcallPrivate::exitStatusMessage() const
460 return "No QProcess available";
463 switch (process_->exitStatus()) {
464 case QProcess::NormalExit:
465 message = "The process exited normally.";
467 case QProcess::CrashExit:
468 message = "The process crashed.";
471 message = "Unknown exit state.";
478 int SystemcallPrivate::exitCode()
483 return process_->exitCode();
487 QProcess* SystemcallPrivate::releaseProcess()
489 QProcess* released = process_;
495 void SystemcallPrivate::killProcess()
497 killProcess(process_);
501 void SystemcallPrivate::killProcess(QProcess * p)
505 p->closeReadChannel(QProcess::StandardOutput);
506 p->closeReadChannel(QProcess::StandardError);
514 #include "moc_SystemcallPrivate.cpp"
517 } // namespace support