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.
135 * The escape character is the backslash.
136 * A backslash that is not quoted preserves the literal value of the following
137 * character, with the exception of a double-quote '"'. If a double-quote
138 * follows a backslash, it will be replaced by three consecutive double-quotes
139 * (this is how the QProcess parser recognizes a '"' as a simple character
140 * instead of a quoting character). Thus, for example:
146 * Characters enclosed in single-quotes ('') have their literal value preserved.
147 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
148 * be used to escape a single-quote in a single-quoted string. In other words,
149 * anything enclosed in single-quotes is passed as is, but the single-quotes
150 * themselves are eliminated. Thus, for example:
157 * Characters enclosed in double-quotes ("") have their literal value preserved,
158 * with the exception of the backslash. The backslash retains its special
159 * meaning as an escape character only when followed by a double-quote.
160 * Contrarily to the behavior of a posix shell, the double-quotes themselves
161 * are *not* eliminated. Thus, for example:
166 string const parsecmd(string const & incmd, string & infile, string & outfile,
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(4);
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");
218 } else if (c == '<' && !(in_double_quote || escaped)) {
221 if (escaped && in_double_quote)
227 infile = trim(outcmd[3], " \"");
228 outfile = trim(outcmd[1], " \"");
229 errfile = trim(outcmd[2], " \"");
230 return trim(outcmd[0]);
237 int Systemcall::startscript(Starttype how, string const & what,
238 string const & path, bool process_events)
240 lyxerr << "\nRunning: " << what << endl;
245 QString cmd = QString::fromLocal8Bit(
246 parsecmd(what, infile, outfile, errfile).c_str());
248 SystemcallPrivate d(infile, outfile, errfile);
251 d.startProcess(cmd, path);
252 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
253 LYXERR0("Systemcall: '" << cmd << "' did not start!");
254 LYXERR0("error " << d.errorMessage());
258 if (how == DontWait) {
259 QProcess* released = d.releaseProcess();
260 (void) released; // TODO who deletes it?
264 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
265 os::timeout_min() * 60 * 1000)) {
266 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
267 LYXERR0("error " << d.errorMessage());
268 LYXERR0("status " << d.exitStatusMessage());
272 int const exit_code = d.exitCode();
274 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
281 SystemcallPrivate::SystemcallPrivate(std::string const & sf,
282 std::string const & of,
283 std::string const & ef) :
284 process_(new QProcess),
290 process_events_(false)
292 if (!in_file_.empty())
293 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
294 if (!out_file_.empty()) {
295 if (out_file_[0] == '&') {
296 if (subst(out_file_, " ", "") == "&2"
297 && err_file_[0] != '&') {
298 out_file_ = err_file_;
299 process_->setProcessChannelMode(
300 QProcess::MergedChannels);
302 if (err_file_[0] == '&') {
303 // Leave alone things such as
304 // "1>&2 2>&1". Should not be harmful,
305 // but let's give anyway a warning.
306 LYXERR0("Unsupported stdout/stderr redirect.");
309 LYXERR0("Ambiguous stdout redirect: "
312 out_file_ = os::nulldev();
315 // Check whether we have to set the output file.
316 if (out_file_ != os::nulldev()) {
317 process_->setStandardOutputFile(QString::fromLocal8Bit(
321 if (!err_file_.empty()) {
322 if (err_file_[0] == '&') {
323 if (subst(err_file_, " ", "") == "&1"
324 && out_file_[0] != '&') {
325 process_->setProcessChannelMode(
326 QProcess::MergedChannels);
328 LYXERR0("Ambiguous stderr redirect: "
331 // In MergedChannels mode stderr goes to stdout.
332 err_file_ = os::nulldev();
334 // Check whether we have to set the error file.
335 if (err_file_ != os::nulldev()) {
336 process_->setStandardErrorFile(QString::fromLocal8Bit(
341 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
342 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
343 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
344 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
345 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
349 void SystemcallPrivate::startProcess(QString const & cmd, string const & path)
353 state = SystemcallPrivate::Starting;
354 process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
359 void SystemcallPrivate::processEvents()
361 if(process_events_) {
362 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
367 void SystemcallPrivate::waitAndProcessEvents()
369 Sleep::millisec(100);
374 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
379 process_events_ = process_events;
381 // Block GUI while waiting,
382 // relay on QProcess' wait functions
383 if (!process_events_) {
384 if (waitwhile == Starting)
385 return process_->waitForStarted(timeout);
386 if (waitwhile == Running)
387 return process_->waitForFinished(timeout);
391 // process events while waiting, no timeout
393 while (state == waitwhile && state != Error) {
394 waitAndProcessEvents();
396 return state != Error;
399 // process events while waiting whith timeout
402 while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
403 waitAndProcessEvents();
405 return (state != Error) && (timer.elapsed() < timeout);
409 SystemcallPrivate::~SystemcallPrivate()
412 out_data_[out_index_] = '\0';
418 err_data_[err_index_] = '\0';
428 void SystemcallPrivate::stdOut()
432 process_->setReadChannel(QProcess::StandardOutput);
433 while (process_->getChar(&c)) {
434 out_data_[out_index_++] = c;
435 if (c == '\n' || out_index_ + 1 == buffer_size_) {
436 out_data_[out_index_] = '\0';
438 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
446 void SystemcallPrivate::stdErr()
450 process_->setReadChannel(QProcess::StandardError);
451 while (process_->getChar(&c)) {
452 err_data_[err_index_++] = c;
453 if (c == '\n' || err_index_ + 1 == buffer_size_) {
454 err_data_[err_index_] = '\0';
456 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
464 void SystemcallPrivate::processStarted()
466 if (state != Running) {
468 ProgressInterface::instance()->processStarted(cmd_);
473 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
475 if (state != Finished) {
477 ProgressInterface::instance()->processFinished(cmd_);
482 void SystemcallPrivate::processError(QProcess::ProcessError)
485 ProgressInterface::instance()->appendError(errorMessage());
489 QString SystemcallPrivate::errorMessage() const
492 return "No QProcess available";
495 switch (process_->error()) {
496 case QProcess::FailedToStart:
497 message = "The process failed to start. Either the invoked program is missing, "
498 "or you may have insufficient permissions to invoke the program.";
500 case QProcess::Crashed:
501 message = "The process crashed some time after starting successfully.";
503 case QProcess::Timedout:
504 message = "The process timed out. It might be restarted automatically.";
506 case QProcess::WriteError:
507 message = "An error occurred when attempting to write to the process-> For example, "
508 "the process may not be running, or it may have closed its input channel.";
510 case QProcess::ReadError:
511 message = "An error occurred when attempting to read from the process-> For example, "
512 "the process may not be running.";
514 case QProcess::UnknownError:
516 message = "An unknown error occured.";
523 QString SystemcallPrivate::exitStatusMessage() const
526 return "No QProcess available";
529 switch (process_->exitStatus()) {
530 case QProcess::NormalExit:
531 message = "The process exited normally.";
533 case QProcess::CrashExit:
534 message = "The process crashed.";
537 message = "Unknown exit state.";
544 int SystemcallPrivate::exitCode()
549 return process_->exitCode();
553 QProcess* SystemcallPrivate::releaseProcess()
555 QProcess* released = process_;
561 void SystemcallPrivate::killProcess()
563 killProcess(process_);
567 void SystemcallPrivate::killProcess(QProcess * p)
571 p->closeReadChannel(QProcess::StandardOutput);
572 p->closeReadChannel(QProcess::StandardError);
580 #include "moc_SystemcallPrivate.cpp"
583 } // namespace support