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 as
132 * regards quoting, but its output is tailored for being processed by QProcess.
133 * Note that shell metacharacters are not parsed and only output redirection
134 * is taken into account.
136 * The escape character is the backslash.
137 * A backslash that is not quoted preserves the literal value of the following
138 * character, with the exception of a double-quote '"'. If a double-quote
139 * follows a backslash, it will be replaced by three consecutive double-quotes
140 * (this is how the QProcess parser recognizes a '"' as a simple character
141 * instead of a quoting character). Thus, for example:
147 * Characters enclosed in single-quotes ('') have their literal value preserved.
148 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
149 * be used to escape a single-quote in a single-quoted string. In other words,
150 * anything enclosed in single-quotes is passed as is, but the single-quotes
151 * themselves are eliminated. Thus, for example:
158 * Characters enclosed in double-quotes ("") have their literal value preserved,
159 * with the exception of the backslash. The backslash retains its special
160 * meaning as an escape character only when followed by a double-quote.
161 * Contrarily to the behavior of a posix shell, the double-quotes themselves
162 * are *not* eliminated. Thus, for example:
167 string const parsecmd(string const & incmd, string & outfile, string & errfile)
169 bool in_single_quote = false;
170 bool in_double_quote = false;
171 bool escaped = false;
172 string const python_call = "python -tt";
173 vector<string> outcmd(3);
176 if (prefixIs(incmd, python_call)) {
177 outcmd[0] = os::python();
178 start = python_call.length();
181 for (size_t i = start, o = 0; i < incmd.length(); ++i) {
184 if (in_double_quote || escaped) {
185 if (in_double_quote && escaped)
189 in_single_quote = !in_single_quote;
193 if (in_single_quote) {
199 // Don't triple double-quotes for redirection
200 // files as these won't be parsed by QProcess
201 outcmd[o] += string(o ? "\"" : "\"\"\"");
205 in_double_quote = !in_double_quote;
207 } else if (c == '\\' && !escaped) {
209 } else if (c == '>' && !(in_double_quote || escaped)) {
210 if (suffixIs(outcmd[o], " 2")) {
211 outcmd[o] = rtrim(outcmd[o], "2");
214 if (suffixIs(outcmd[o], " 1"))
215 outcmd[o] = rtrim(outcmd[o], "1");
219 if (escaped && in_double_quote)
225 outfile = trim(outcmd[1], " \"");
226 errfile = trim(outcmd[2], " \"");
227 return trim(outcmd[0]);
234 int Systemcall::startscript(Starttype how, string const & what,
235 string const & path, bool process_events)
237 lyxerr << "\nRunning: " << what << endl;
241 QString cmd = QString::fromLocal8Bit(
242 parsecmd(what, outfile, errfile).c_str());
244 SystemcallPrivate d(outfile, errfile);
247 d.startProcess(cmd, path);
248 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
249 LYXERR0("Systemcall: '" << cmd << "' did not start!");
250 LYXERR0("error " << d.errorMessage());
254 if (how == DontWait) {
255 QProcess* released = d.releaseProcess();
256 (void) released; // TODO who deletes it?
260 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
261 os::timeout_min() * 60 * 1000)) {
262 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
263 LYXERR0("error " << d.errorMessage());
264 LYXERR0("status " << d.exitStatusMessage());
268 int const exit_code = d.exitCode();
270 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
277 SystemcallPrivate::SystemcallPrivate(std::string const & of,
278 std::string const & ef) :
279 process_(new QProcess),
284 process_events_(false)
286 if (!out_file_.empty()) {
287 if (out_file_[0] == '&') {
288 if (subst(out_file_, " ", "") == "&2"
289 && err_file_[0] != '&') {
290 out_file_ = err_file_;
291 process_->setProcessChannelMode(
292 QProcess::MergedChannels);
294 if (err_file_[0] == '&') {
295 // Leave alone things such as
296 // "1>&2 2>&1". Should not be harmful,
297 // but let's give anyway a warning.
298 LYXERR0("Unsupported stdout/stderr redirect.");
301 LYXERR0("Ambiguous stdout redirect: "
304 out_file_ = os::nulldev();
307 // Check whether we have to set the output file.
308 if (out_file_ != os::nulldev()) {
309 process_->setStandardOutputFile(QString::fromLocal8Bit(
313 if (!err_file_.empty()) {
314 if (err_file_[0] == '&') {
315 if (subst(err_file_, " ", "") == "&1"
316 && out_file_[0] != '&') {
317 process_->setProcessChannelMode(
318 QProcess::MergedChannels);
320 LYXERR0("Ambiguous stderr redirect: "
323 // In MergedChannels mode stderr goes to stdout.
324 err_file_ = os::nulldev();
326 // Check whether we have to set the error file.
327 if (err_file_ != os::nulldev()) {
328 process_->setStandardErrorFile(QString::fromLocal8Bit(
333 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
334 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
335 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
336 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
337 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
341 void SystemcallPrivate::startProcess(QString const & cmd, string const & path)
345 state = SystemcallPrivate::Starting;
346 process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
351 void SystemcallPrivate::processEvents()
353 if(process_events_) {
354 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
359 void SystemcallPrivate::waitAndProcessEvents()
361 Sleep::millisec(100);
366 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
371 process_events_ = process_events;
373 // Block GUI while waiting,
374 // relay on QProcess' wait functions
375 if (!process_events_) {
376 if (waitwhile == Starting)
377 return process_->waitForStarted(timeout);
378 if (waitwhile == Running)
379 return process_->waitForFinished(timeout);
383 // process events while waiting, no timeout
385 while (state == waitwhile && state != Error) {
386 waitAndProcessEvents();
388 return state != Error;
391 // process events while waiting whith timeout
394 while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
395 waitAndProcessEvents();
397 return (state != Error) && (timer.elapsed() < timeout);
401 SystemcallPrivate::~SystemcallPrivate()
404 out_data_[out_index_] = '\0';
410 err_data_[err_index_] = '\0';
420 void SystemcallPrivate::stdOut()
424 process_->setReadChannel(QProcess::StandardOutput);
425 while (process_->getChar(&c)) {
426 out_data_[out_index_++] = c;
427 if (c == '\n' || out_index_ + 1 == buffer_size_) {
428 out_data_[out_index_] = '\0';
430 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
438 void SystemcallPrivate::stdErr()
442 process_->setReadChannel(QProcess::StandardError);
443 while (process_->getChar(&c)) {
444 err_data_[err_index_++] = c;
445 if (c == '\n' || err_index_ + 1 == buffer_size_) {
446 err_data_[err_index_] = '\0';
448 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
456 void SystemcallPrivate::processStarted()
458 if (state != Running) {
460 ProgressInterface::instance()->processStarted(cmd_);
465 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
467 if (state != Finished) {
469 ProgressInterface::instance()->processFinished(cmd_);
474 void SystemcallPrivate::processError(QProcess::ProcessError)
477 ProgressInterface::instance()->appendError(errorMessage());
481 QString SystemcallPrivate::errorMessage() const
484 return "No QProcess available";
487 switch (process_->error()) {
488 case QProcess::FailedToStart:
489 message = "The process failed to start. Either the invoked program is missing, "
490 "or you may have insufficient permissions to invoke the program.";
492 case QProcess::Crashed:
493 message = "The process crashed some time after starting successfully.";
495 case QProcess::Timedout:
496 message = "The process timed out. It might be restarted automatically.";
498 case QProcess::WriteError:
499 message = "An error occurred when attempting to write to the process-> For example, "
500 "the process may not be running, or it may have closed its input channel.";
502 case QProcess::ReadError:
503 message = "An error occurred when attempting to read from the process-> For example, "
504 "the process may not be running.";
506 case QProcess::UnknownError:
508 message = "An unknown error occured.";
515 QString SystemcallPrivate::exitStatusMessage() const
518 return "No QProcess available";
521 switch (process_->exitStatus()) {
522 case QProcess::NormalExit:
523 message = "The process exited normally.";
525 case QProcess::CrashExit:
526 message = "The process crashed.";
529 message = "Unknown exit state.";
536 int SystemcallPrivate::exitCode()
541 return process_->exitCode();
545 QProcess* SystemcallPrivate::releaseProcess()
547 QProcess* released = process_;
553 void SystemcallPrivate::killProcess()
555 killProcess(process_);
559 void SystemcallPrivate::killProcess(QProcess * p)
563 p->closeReadChannel(QProcess::StandardOutput);
564 p->closeReadChannel(QProcess::StandardError);
572 #include "moc_SystemcallPrivate.cpp"
575 } // namespace support