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, how == DontWait);
255 if (how == DontWait && d.state == SystemcallPrivate::Running) {
258 if (d.state == SystemcallPrivate::Error
259 || !d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
260 LYXERR0("Systemcall: '" << cmd << "' did not start!");
261 LYXERR0("error " << d.errorMessage());
265 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
266 os::timeout_min() * 60 * 1000)) {
267 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
268 LYXERR0("error " << d.errorMessage());
269 LYXERR0("status " << d.exitStatusMessage());
273 int const exit_code = d.exitCode();
275 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
282 SystemcallPrivate::SystemcallPrivate(std::string const & sf,
283 std::string const & of,
284 std::string const & ef) :
285 process_(new QProcess),
291 process_events_(false)
293 if (!in_file_.empty())
294 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
295 if (!out_file_.empty()) {
296 if (out_file_[0] == '&') {
297 if (subst(out_file_, " ", "") == "&2"
298 && err_file_[0] != '&') {
299 out_file_ = err_file_;
300 process_->setProcessChannelMode(
301 QProcess::MergedChannels);
303 if (err_file_[0] == '&') {
304 // Leave alone things such as
305 // "1>&2 2>&1". Should not be harmful,
306 // but let's give anyway a warning.
307 LYXERR0("Unsupported stdout/stderr redirect.");
310 LYXERR0("Ambiguous stdout redirect: "
313 out_file_ = os::nulldev();
316 // Check whether we have to set the output file.
317 if (out_file_ != os::nulldev()) {
318 process_->setStandardOutputFile(QString::fromLocal8Bit(
322 if (!err_file_.empty()) {
323 if (err_file_[0] == '&') {
324 if (subst(err_file_, " ", "") == "&1"
325 && out_file_[0] != '&') {
326 process_->setProcessChannelMode(
327 QProcess::MergedChannels);
329 LYXERR0("Ambiguous stderr redirect: "
332 // In MergedChannels mode stderr goes to stdout.
333 err_file_ = os::nulldev();
335 // Check whether we have to set the error file.
336 if (err_file_ != os::nulldev()) {
337 process_->setStandardErrorFile(QString::fromLocal8Bit(
342 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
343 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
344 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
345 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
346 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
350 void SystemcallPrivate::startProcess(QString const & cmd, string const & path, bool detached)
354 state = SystemcallPrivate::Running;
355 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path)) + cmd_)) {
356 state = SystemcallPrivate::Error;
359 QProcess* released = releaseProcess();
361 } else if (process_) {
362 state = SystemcallPrivate::Starting;
363 process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
368 void SystemcallPrivate::processEvents()
370 if (process_events_) {
371 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
376 void SystemcallPrivate::waitAndProcessEvents()
378 Sleep::millisec(100);
385 bool queryStopCommand(QString const & cmd)
387 docstring text = bformat(_(
388 "The command\n%1$s\nhas not yet completed.\n\n"
389 "Do you want to stop it?"), qstring_to_ucs4(cmd));
390 return ProgressInterface::instance()->prompt(_("Stop command?"), text,
391 1, 1, _("&Stop it"), _("Let it &run")) == 0;
397 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
402 bool timedout = false;
403 process_events_ = process_events;
405 // Block GUI while waiting,
406 // relay on QProcess' wait functions
407 if (!process_events_) {
408 if (waitwhile == Starting)
409 return process_->waitForStarted(timeout);
410 if (waitwhile == Running) {
413 if (process_->waitForFinished(timeout))
415 bool stop = queryStopCommand(cmd_);
416 // The command may have finished in the meantime
417 if (process_->state() == QProcess::NotRunning)
431 // process events while waiting, no timeout
433 while (state == waitwhile && state != Error) {
434 waitAndProcessEvents();
436 return state != Error;
439 // process events while waiting with timeout
442 while (state == waitwhile && state != Error && !timedout) {
443 waitAndProcessEvents();
444 if (timer.elapsed() > timeout) {
445 bool stop = queryStopCommand(cmd_);
446 // The command may have finished in the meantime
447 if (process_->state() == QProcess::NotRunning)
456 return (state != Error) && !timedout;
460 SystemcallPrivate::~SystemcallPrivate()
463 out_data_[out_index_] = '\0';
469 err_data_[err_index_] = '\0';
479 void SystemcallPrivate::stdOut()
483 process_->setReadChannel(QProcess::StandardOutput);
484 while (process_->getChar(&c)) {
485 out_data_[out_index_++] = c;
486 if (c == '\n' || out_index_ + 1 == buffer_size_) {
487 out_data_[out_index_] = '\0';
489 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
497 void SystemcallPrivate::stdErr()
501 process_->setReadChannel(QProcess::StandardError);
502 while (process_->getChar(&c)) {
503 err_data_[err_index_++] = c;
504 if (c == '\n' || err_index_ + 1 == buffer_size_) {
505 err_data_[err_index_] = '\0';
507 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
515 void SystemcallPrivate::processStarted()
517 if (state != Running) {
519 ProgressInterface::instance()->processStarted(cmd_);
524 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
526 if (state != Finished) {
528 ProgressInterface::instance()->processFinished(cmd_);
533 void SystemcallPrivate::processError(QProcess::ProcessError)
536 ProgressInterface::instance()->appendError(errorMessage());
540 QString SystemcallPrivate::errorMessage() const
543 return "No QProcess available";
546 switch (process_->error()) {
547 case QProcess::FailedToStart:
548 message = "The process failed to start. Either the invoked program is missing, "
549 "or you may have insufficient permissions to invoke the program.";
551 case QProcess::Crashed:
552 message = "The process crashed some time after starting successfully.";
554 case QProcess::Timedout:
555 message = "The process timed out. It might be restarted automatically.";
557 case QProcess::WriteError:
558 message = "An error occurred when attempting to write to the process-> For example, "
559 "the process may not be running, or it may have closed its input channel.";
561 case QProcess::ReadError:
562 message = "An error occurred when attempting to read from the process-> For example, "
563 "the process may not be running.";
565 case QProcess::UnknownError:
567 message = "An unknown error occured.";
574 QString SystemcallPrivate::exitStatusMessage() const
577 return "No QProcess available";
580 switch (process_->exitStatus()) {
581 case QProcess::NormalExit:
582 message = "The process exited normally.";
584 case QProcess::CrashExit:
585 message = "The process crashed.";
588 message = "Unknown exit state.";
595 int SystemcallPrivate::exitCode()
600 return process_->exitCode();
604 QProcess* SystemcallPrivate::releaseProcess()
606 QProcess* released = process_;
612 void SystemcallPrivate::killProcess()
614 killProcess(process_);
618 void SystemcallPrivate::killProcess(QProcess * p)
622 p->closeReadChannel(QProcess::StandardOutput);
623 p->closeReadChannel(QProcess::StandardError);
631 #include "moc_SystemcallPrivate.cpp"
634 } // namespace support