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, false);
255 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
256 LYXERR0("Systemcall: '" << cmd << "' did not start!");
257 LYXERR0("error " << d.errorMessage());
260 if (how == DontWait) {
265 d.startProcess(cmd, path, how == DontWait);
266 if (how == DontWait && d.state == SystemcallPrivate::Running)
269 if (d.state == SystemcallPrivate::Error
270 || !d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
271 LYXERR0("Systemcall: '" << cmd << "' did not start!");
272 LYXERR0("error " << d.errorMessage());
277 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
278 os::timeout_min() * 60 * 1000)) {
279 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
280 LYXERR0("error " << d.errorMessage());
281 LYXERR0("status " << d.exitStatusMessage());
285 int const exit_code = d.exitCode();
287 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
294 SystemcallPrivate::SystemcallPrivate(std::string const & sf,
295 std::string const & of,
296 std::string const & ef) :
297 process_(new QProcess),
303 process_events_(false)
305 if (!in_file_.empty())
306 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
307 if (!out_file_.empty()) {
308 if (out_file_[0] == '&') {
309 if (subst(out_file_, " ", "") == "&2"
310 && err_file_[0] != '&') {
311 out_file_ = err_file_;
312 process_->setProcessChannelMode(
313 QProcess::MergedChannels);
315 if (err_file_[0] == '&') {
316 // Leave alone things such as
317 // "1>&2 2>&1". Should not be harmful,
318 // but let's give anyway a warning.
319 LYXERR0("Unsupported stdout/stderr redirect.");
322 LYXERR0("Ambiguous stdout redirect: "
325 out_file_ = os::nulldev();
328 // Check whether we have to set the output file.
329 if (out_file_ != os::nulldev()) {
330 process_->setStandardOutputFile(QString::fromLocal8Bit(
334 if (!err_file_.empty()) {
335 if (err_file_[0] == '&') {
336 if (subst(err_file_, " ", "") == "&1"
337 && out_file_[0] != '&') {
338 process_->setProcessChannelMode(
339 QProcess::MergedChannels);
341 LYXERR0("Ambiguous stderr redirect: "
344 // In MergedChannels mode stderr goes to stdout.
345 err_file_ = os::nulldev();
347 // Check whether we have to set the error file.
348 if (err_file_ != os::nulldev()) {
349 process_->setStandardErrorFile(QString::fromLocal8Bit(
354 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
355 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
356 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
357 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
358 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
362 void SystemcallPrivate::startProcess(QString const & cmd, string const & path, bool detached)
366 state = SystemcallPrivate::Running;
367 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path)) + cmd_)) {
368 state = SystemcallPrivate::Error;
371 QProcess* released = releaseProcess();
373 } else if (process_) {
374 state = SystemcallPrivate::Starting;
375 process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
380 void SystemcallPrivate::processEvents()
382 if (process_events_) {
383 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
388 void SystemcallPrivate::waitAndProcessEvents()
390 Sleep::millisec(100);
397 bool queryStopCommand(QString const & cmd)
399 docstring text = bformat(_(
400 "The command\n%1$s\nhas not yet completed.\n\n"
401 "Do you want to stop it?"), qstring_to_ucs4(cmd));
402 return ProgressInterface::instance()->prompt(_("Stop command?"), text,
403 1, 1, _("&Stop it"), _("Let it &run")) == 0;
409 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
414 bool timedout = false;
415 process_events_ = process_events;
417 // Block GUI while waiting,
418 // relay on QProcess' wait functions
419 if (!process_events_) {
420 if (waitwhile == Starting)
421 return process_->waitForStarted(timeout);
422 if (waitwhile == Running) {
425 if (process_->waitForFinished(timeout))
427 bool stop = queryStopCommand(cmd_);
428 // The command may have finished in the meantime
429 if (process_->state() == QProcess::NotRunning)
443 // process events while waiting, no timeout
445 while (state == waitwhile && state != Error) {
446 waitAndProcessEvents();
448 return state != Error;
451 // process events while waiting with timeout
454 while (state == waitwhile && state != Error && !timedout) {
455 waitAndProcessEvents();
456 if (timer.elapsed() > timeout) {
457 bool stop = queryStopCommand(cmd_);
458 // The command may have finished in the meantime
459 if (process_->state() == QProcess::NotRunning)
468 return (state != Error) && !timedout;
472 SystemcallPrivate::~SystemcallPrivate()
475 out_data_[out_index_] = '\0';
481 err_data_[err_index_] = '\0';
491 void SystemcallPrivate::stdOut()
495 process_->setReadChannel(QProcess::StandardOutput);
496 while (process_->getChar(&c)) {
497 out_data_[out_index_++] = c;
498 if (c == '\n' || out_index_ + 1 == buffer_size_) {
499 out_data_[out_index_] = '\0';
501 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
509 void SystemcallPrivate::stdErr()
513 process_->setReadChannel(QProcess::StandardError);
514 while (process_->getChar(&c)) {
515 err_data_[err_index_++] = c;
516 if (c == '\n' || err_index_ + 1 == buffer_size_) {
517 err_data_[err_index_] = '\0';
519 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
527 void SystemcallPrivate::processStarted()
529 if (state != Running) {
531 ProgressInterface::instance()->processStarted(cmd_);
536 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
538 if (state != Finished) {
540 ProgressInterface::instance()->processFinished(cmd_);
545 void SystemcallPrivate::processError(QProcess::ProcessError)
548 ProgressInterface::instance()->appendError(errorMessage());
552 QString SystemcallPrivate::errorMessage() const
555 return "No QProcess available";
558 switch (process_->error()) {
559 case QProcess::FailedToStart:
560 message = "The process failed to start. Either the invoked program is missing, "
561 "or you may have insufficient permissions to invoke the program.";
563 case QProcess::Crashed:
564 message = "The process crashed some time after starting successfully.";
566 case QProcess::Timedout:
567 message = "The process timed out. It might be restarted automatically.";
569 case QProcess::WriteError:
570 message = "An error occurred when attempting to write to the process-> For example, "
571 "the process may not be running, or it may have closed its input channel.";
573 case QProcess::ReadError:
574 message = "An error occurred when attempting to read from the process-> For example, "
575 "the process may not be running.";
577 case QProcess::UnknownError:
579 message = "An unknown error occured.";
586 QString SystemcallPrivate::exitStatusMessage() const
589 return "No QProcess available";
592 switch (process_->exitStatus()) {
593 case QProcess::NormalExit:
594 message = "The process exited normally.";
596 case QProcess::CrashExit:
597 message = "The process crashed.";
600 message = "Unknown exit state.";
607 int SystemcallPrivate::exitCode()
612 return process_->exitCode();
616 QProcess* SystemcallPrivate::releaseProcess()
618 QProcess* released = process_;
624 void SystemcallPrivate::killProcess()
626 killProcess(process_);
630 void SystemcallPrivate::killProcess(QProcess * p)
634 p->closeReadChannel(QProcess::StandardOutput);
635 p->closeReadChannel(QProcess::StandardError);
643 #include "moc_SystemcallPrivate.cpp"
646 } // namespace support