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/gettext.h"
19 #include "support/lstrings.h"
20 #include "support/qstring_helpers.h"
21 #include "support/Systemcall.h"
22 #include "support/SystemcallPrivate.h"
23 #include "support/os.h"
24 #include "support/ProgressInterface.h"
34 #include <QCoreApplication>
40 struct Sleep : QThread
42 static void millisec(unsigned long ms)
44 QThread::usleep(ms * 1000);
57 class ProgressDummy : public ProgressInterface
62 void processStarted(QString const &) {}
63 void processFinished(QString const &) {}
64 void appendMessage(QString const &) {}
65 void appendError(QString const &) {}
66 void clearMessages() {}
69 void lyxerrConnect() {}
70 void lyxerrDisconnect() {}
72 void warning(QString const &, QString const &) {}
73 void toggleWarning(QString const &, QString const &, QString const &) {}
74 void error(QString const &, QString const &) {}
75 void information(QString const &, QString const &) {}
76 int prompt(docstring const &, docstring const &, int default_but, int,
77 docstring const &, docstring const &) { return default_but; }
81 static ProgressInterface* progress_instance = 0;
83 void ProgressInterface::setInstance(ProgressInterface* p)
85 progress_instance = p;
89 ProgressInterface* ProgressInterface::instance()
91 if (!progress_instance) {
92 static ProgressDummy dummy;
95 return progress_instance;
103 int Systemcall::startscript(Starttype how, string const & what,
104 std::string const & path, bool /*process_events*/)
106 string const python_call = "python -tt";
107 string command = to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path)));
109 if (prefixIs(what, python_call))
110 command += os::python() + what.substr(python_call.length());
114 if (how == DontWait) {
115 switch (os::shell()) {
120 command = "start /min " + command;
123 } else if (os::shell() == os::CMD_EXE)
124 command = subst(command, "cmd /d /c ", "");
126 return ::system(command.c_str());
134 * This is a parser that (mostly) mimics the behavior of a posix shell as
135 * regards quoting, but its output is tailored for being processed by QProcess.
136 * Note that shell metacharacters are not parsed.
138 * The escape character is the backslash.
139 * A backslash that is not quoted preserves the literal value of the following
140 * character, with the exception of a double-quote '"'. If a double-quote
141 * follows a backslash, it will be replaced by three consecutive double-quotes
142 * (this is how the QProcess parser recognizes a '"' as a simple character
143 * instead of a quoting character). Thus, for example:
149 * Characters enclosed in single-quotes ('') have their literal value preserved.
150 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
151 * be used to escape a single-quote in a single-quoted string. In other words,
152 * anything enclosed in single-quotes is passed as is, but the single-quotes
153 * themselves are eliminated. Thus, for example:
160 * Characters enclosed in double-quotes ("") have their literal value preserved,
161 * with the exception of the backslash. The backslash retains its special
162 * meaning as an escape character only when followed by a double-quote.
163 * Contrarily to the behavior of a posix shell, the double-quotes themselves
164 * are *not* eliminated. Thus, for example:
169 string const parsecmd(string const & incmd, string & infile, string & outfile,
172 bool in_single_quote = false;
173 bool in_double_quote = false;
174 bool escaped = false;
175 string const python_call = "python -tt";
176 vector<string> outcmd(4);
179 if (prefixIs(incmd, python_call)) {
180 outcmd[0] = os::python();
181 start = python_call.length();
184 for (size_t i = start, o = 0; i < incmd.length(); ++i) {
187 if (in_double_quote || escaped) {
188 if (in_double_quote && escaped)
192 in_single_quote = !in_single_quote;
196 if (in_single_quote) {
202 // Don't triple double-quotes for redirection
203 // files as these won't be parsed by QProcess
204 outcmd[o] += string(o ? "\"" : "\"\"\"");
208 in_double_quote = !in_double_quote;
210 } else if (c == '\\' && !escaped) {
212 } else if (c == '>' && !(in_double_quote || escaped)) {
213 if (suffixIs(outcmd[o], " 2")) {
214 outcmd[o] = rtrim(outcmd[o], "2");
217 if (suffixIs(outcmd[o], " 1"))
218 outcmd[o] = rtrim(outcmd[o], "1");
221 } else if (c == '<' && !(in_double_quote || escaped)) {
224 if (escaped && in_double_quote)
230 infile = trim(outcmd[3], " \"");
231 outfile = trim(outcmd[1], " \"");
232 errfile = trim(outcmd[2], " \"");
233 return trim(outcmd[0]);
240 int Systemcall::startscript(Starttype how, string const & what,
241 string const & path, bool process_events)
243 LYXERR(Debug::INFO,"Running: " << what);
248 QString const cmd = QString::fromLocal8Bit(
249 parsecmd(what, infile, outfile, errfile).c_str());
251 SystemcallPrivate d(infile, outfile, errfile);
254 d.startProcess(cmd, path);
255 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
256 LYXERR0("Systemcall: '" << cmd << "' did not start!");
257 LYXERR0("error " << d.errorMessage());
261 if (how == DontWait) {
262 QProcess* released = d.releaseProcess();
263 (void) released; // TODO who deletes it?
267 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
268 os::timeout_min() * 60 * 1000)) {
269 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
270 LYXERR0("error " << d.errorMessage());
271 LYXERR0("status " << d.exitStatusMessage());
275 int const exit_code = d.exitCode();
277 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
284 SystemcallPrivate::SystemcallPrivate(std::string const & sf,
285 std::string const & of,
286 std::string const & ef) :
287 process_(new QProcess),
293 process_events_(false)
295 if (!in_file_.empty())
296 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
297 if (!out_file_.empty()) {
298 if (out_file_[0] == '&') {
299 if (subst(out_file_, " ", "") == "&2"
300 && err_file_[0] != '&') {
301 out_file_ = err_file_;
302 process_->setProcessChannelMode(
303 QProcess::MergedChannels);
305 if (err_file_[0] == '&') {
306 // Leave alone things such as
307 // "1>&2 2>&1". Should not be harmful,
308 // but let's give anyway a warning.
309 LYXERR0("Unsupported stdout/stderr redirect.");
312 LYXERR0("Ambiguous stdout redirect: "
315 out_file_ = os::nulldev();
318 // Check whether we have to set the output file.
319 if (out_file_ != os::nulldev()) {
320 process_->setStandardOutputFile(QString::fromLocal8Bit(
324 if (!err_file_.empty()) {
325 if (err_file_[0] == '&') {
326 if (subst(err_file_, " ", "") == "&1"
327 && out_file_[0] != '&') {
328 process_->setProcessChannelMode(
329 QProcess::MergedChannels);
331 LYXERR0("Ambiguous stderr redirect: "
334 // In MergedChannels mode stderr goes to stdout.
335 err_file_ = os::nulldev();
337 // Check whether we have to set the error file.
338 if (err_file_ != os::nulldev()) {
339 process_->setStandardErrorFile(QString::fromLocal8Bit(
344 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
345 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
346 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
347 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
348 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
352 void SystemcallPrivate::startProcess(QString const & cmd, string const & path)
356 state = SystemcallPrivate::Starting;
357 process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
362 void SystemcallPrivate::processEvents()
364 if (process_events_) {
365 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
370 void SystemcallPrivate::waitAndProcessEvents()
372 Sleep::millisec(100);
379 bool queryStopCommand(QString const & cmd)
381 docstring text = bformat(_(
382 "The command\n%1$s\nhas not yet completed.\n\n"
383 "Do you want to stop it?"), qstring_to_ucs4(cmd));
384 return ProgressInterface::instance()->prompt(_("Stop command?"), text,
385 1, 1, _("&Stop it"), _("Let it &run")) == 0;
391 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
396 bool timedout = false;
397 process_events_ = process_events;
399 // Block GUI while waiting,
400 // relay on QProcess' wait functions
401 if (!process_events_) {
402 if (waitwhile == Starting)
403 return process_->waitForStarted(timeout);
404 if (waitwhile == Running) {
407 if (process_->waitForFinished(timeout))
409 bool stop = queryStopCommand(cmd_);
410 // The command may have finished in the meantime
411 if (process_->state() == QProcess::NotRunning)
425 // process events while waiting, no timeout
427 while (state == waitwhile && state != Error) {
428 waitAndProcessEvents();
430 return state != Error;
433 // process events while waiting with timeout
436 while (state == waitwhile && state != Error && !timedout) {
437 waitAndProcessEvents();
438 if (timer.elapsed() > timeout) {
439 bool stop = queryStopCommand(cmd_);
440 // The command may have finished in the meantime
441 if (process_->state() == QProcess::NotRunning)
450 return (state != Error) && !timedout;
454 SystemcallPrivate::~SystemcallPrivate()
457 out_data_[out_index_] = '\0';
463 err_data_[err_index_] = '\0';
473 void SystemcallPrivate::stdOut()
477 process_->setReadChannel(QProcess::StandardOutput);
478 while (process_->getChar(&c)) {
479 out_data_[out_index_++] = c;
480 if (c == '\n' || out_index_ + 1 == buffer_size_) {
481 out_data_[out_index_] = '\0';
483 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
491 void SystemcallPrivate::stdErr()
495 process_->setReadChannel(QProcess::StandardError);
496 while (process_->getChar(&c)) {
497 err_data_[err_index_++] = c;
498 if (c == '\n' || err_index_ + 1 == buffer_size_) {
499 err_data_[err_index_] = '\0';
501 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
509 void SystemcallPrivate::processStarted()
511 if (state != Running) {
513 ProgressInterface::instance()->processStarted(cmd_);
518 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
520 if (state != Finished) {
522 ProgressInterface::instance()->processFinished(cmd_);
527 void SystemcallPrivate::processError(QProcess::ProcessError)
530 ProgressInterface::instance()->appendError(errorMessage());
534 QString SystemcallPrivate::errorMessage() const
537 return "No QProcess available";
540 switch (process_->error()) {
541 case QProcess::FailedToStart:
542 message = "The process failed to start. Either the invoked program is missing, "
543 "or you may have insufficient permissions to invoke the program.";
545 case QProcess::Crashed:
546 message = "The process crashed some time after starting successfully.";
548 case QProcess::Timedout:
549 message = "The process timed out. It might be restarted automatically.";
551 case QProcess::WriteError:
552 message = "An error occurred when attempting to write to the process-> For example, "
553 "the process may not be running, or it may have closed its input channel.";
555 case QProcess::ReadError:
556 message = "An error occurred when attempting to read from the process-> For example, "
557 "the process may not be running.";
559 case QProcess::UnknownError:
561 message = "An unknown error occured.";
568 QString SystemcallPrivate::exitStatusMessage() const
571 return "No QProcess available";
574 switch (process_->exitStatus()) {
575 case QProcess::NormalExit:
576 message = "The process exited normally.";
578 case QProcess::CrashExit:
579 message = "The process crashed.";
582 message = "Unknown exit state.";
589 int SystemcallPrivate::exitCode()
594 return process_->exitCode();
598 QProcess* SystemcallPrivate::releaseProcess()
600 QProcess* released = process_;
606 void SystemcallPrivate::killProcess()
608 killProcess(process_);
612 void SystemcallPrivate::killProcess(QProcess * p)
616 p->closeReadChannel(QProcess::StandardOutput);
617 p->closeReadChannel(QProcess::StandardError);
625 #include "moc_SystemcallPrivate.cpp"
628 } // namespace support