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 command = to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path)))
109 if (how == DontWait) {
110 switch (os::shell()) {
115 command = "start /min " + command;
118 } else if (os::shell() == os::CMD_EXE)
119 command = subst(command, "cmd /d /c ", "");
121 return ::system(command.c_str());
129 * This is a parser that (mostly) mimics the behavior of a posix shell as
130 * regards quoting, but its output is tailored for being processed by QProcess.
131 * Note that shell metacharacters are not parsed.
133 * The escape character is the backslash.
134 * A backslash that is not quoted preserves the literal value of the following
135 * character, with the exception of a double-quote '"'. If a double-quote
136 * follows a backslash, it will be replaced by three consecutive double-quotes
137 * (this is how the QProcess parser recognizes a '"' as a simple character
138 * instead of a quoting character). Thus, for example:
144 * Characters enclosed in single-quotes ('') have their literal value preserved.
145 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
146 * be used to escape a single-quote in a single-quoted string. In other words,
147 * anything enclosed in single-quotes is passed as is, but the single-quotes
148 * themselves are eliminated. Thus, for example:
155 * Characters enclosed in double-quotes ("") have their literal value preserved,
156 * with the exception of the backslash. The backslash retains its special
157 * meaning as an escape character only when followed by a double-quote.
158 * Contrarily to the behavior of a posix shell, the double-quotes themselves
159 * are *not* eliminated. Thus, for example:
164 string const parsecmd(string const & incmd, string & infile, string & outfile,
167 bool in_single_quote = false;
168 bool in_double_quote = false;
169 bool escaped = false;
170 string const python_call = "python -tt";
171 vector<string> outcmd(4);
174 if (prefixIs(incmd, python_call)) {
175 outcmd[0] = os::python();
176 start = python_call.length();
179 for (size_t i = start, o = 0; i < incmd.length(); ++i) {
182 if (in_double_quote || escaped) {
183 if (in_double_quote && escaped)
187 in_single_quote = !in_single_quote;
191 if (in_single_quote) {
197 // Don't triple double-quotes for redirection
198 // files as these won't be parsed by QProcess
199 outcmd[o] += string(o ? "\"" : "\"\"\"");
203 in_double_quote = !in_double_quote;
205 } else if (c == '\\' && !escaped) {
207 } else if (c == '>' && !(in_double_quote || escaped)) {
208 if (suffixIs(outcmd[o], " 2")) {
209 outcmd[o] = rtrim(outcmd[o], "2");
212 if (suffixIs(outcmd[o], " 1"))
213 outcmd[o] = rtrim(outcmd[o], "1");
216 } else if (c == '<' && !(in_double_quote || escaped)) {
219 if (escaped && in_double_quote)
225 infile = trim(outcmd[3], " \"");
226 outfile = trim(outcmd[1], " \"");
227 errfile = trim(outcmd[2], " \"");
228 return trim(outcmd[0]);
235 int Systemcall::startscript(Starttype how, string const & what,
236 string const & path, bool process_events)
238 string const what_ss = commandPrep(what);
239 LYXERR(Debug::INFO,"Running: " << what_ss);
244 QString const cmd = QString::fromLocal8Bit(
245 parsecmd(what_ss, infile, outfile, errfile).c_str());
247 SystemcallPrivate d(infile, outfile, errfile);
250 // QProcess::startDetached cannot provide environment variables. When the
251 // environment variables are set using the latexEnvCmdPrefix and the process
252 // is started with QProcess::startDetached, a console window is shown every
253 // time a viewer is started. To avoid this, we fall back on Windows to the
254 // original implementation that creates a QProcess object.
255 d.startProcess(cmd, path, false);
256 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
257 LYXERR0("Systemcall: '" << cmd << "' did not start!");
258 LYXERR0("error " << d.errorMessage());
261 if (how == DontWait) {
266 d.startProcess(cmd, path, how == DontWait);
267 if (how == DontWait && d.state == SystemcallPrivate::Running)
270 if (d.state == SystemcallPrivate::Error
271 || !d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
272 LYXERR0("Systemcall: '" << cmd << "' did not start!");
273 LYXERR0("error " << d.errorMessage());
278 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
279 os::timeout_min() * 60 * 1000)) {
280 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
281 LYXERR0("error " << d.errorMessage());
282 LYXERR0("status " << d.exitStatusMessage());
286 int const exit_code = d.exitCode();
288 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
295 SystemcallPrivate::SystemcallPrivate(std::string const & sf,
296 std::string const & of,
297 std::string const & ef) :
298 process_(new QProcess),
304 process_events_(false)
306 if (!in_file_.empty())
307 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
308 if (!out_file_.empty()) {
309 if (out_file_[0] == '&') {
310 if (subst(out_file_, " ", "") == "&2"
311 && err_file_[0] != '&') {
312 out_file_ = err_file_;
313 process_->setProcessChannelMode(
314 QProcess::MergedChannels);
316 if (err_file_[0] == '&') {
317 // Leave alone things such as
318 // "1>&2 2>&1". Should not be harmful,
319 // but let's give anyway a warning.
320 LYXERR0("Unsupported stdout/stderr redirect.");
323 LYXERR0("Ambiguous stdout redirect: "
326 out_file_ = os::nulldev();
329 // Check whether we have to set the output file.
330 if (out_file_ != os::nulldev()) {
331 process_->setStandardOutputFile(QString::fromLocal8Bit(
335 if (!err_file_.empty()) {
336 if (err_file_[0] == '&') {
337 if (subst(err_file_, " ", "") == "&1"
338 && out_file_[0] != '&') {
339 process_->setProcessChannelMode(
340 QProcess::MergedChannels);
342 LYXERR0("Ambiguous stderr redirect: "
345 // In MergedChannels mode stderr goes to stdout.
346 err_file_ = os::nulldev();
348 // Check whether we have to set the error file.
349 if (err_file_ != os::nulldev()) {
350 process_->setStandardErrorFile(QString::fromLocal8Bit(
355 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
356 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
357 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
358 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
359 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
363 void SystemcallPrivate::startProcess(QString const & cmd, string const & path, bool detached)
367 state = SystemcallPrivate::Running;
368 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path)) + cmd_)) {
369 state = SystemcallPrivate::Error;
372 QProcess* released = releaseProcess();
374 } else if (process_) {
375 state = SystemcallPrivate::Starting;
376 process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
381 void SystemcallPrivate::processEvents()
383 if (process_events_) {
384 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
389 void SystemcallPrivate::waitAndProcessEvents()
391 Sleep::millisec(100);
398 bool queryStopCommand(QString const & cmd)
400 docstring text = bformat(_(
401 "The command\n%1$s\nhas not yet completed.\n\n"
402 "Do you want to stop it?"), qstring_to_ucs4(cmd));
403 return ProgressInterface::instance()->prompt(_("Stop command?"), text,
404 1, 1, _("&Stop it"), _("Let it &run")) == 0;
410 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
415 bool timedout = false;
416 process_events_ = process_events;
418 // Block GUI while waiting,
419 // relay on QProcess' wait functions
420 if (!process_events_) {
421 if (waitwhile == Starting)
422 return process_->waitForStarted(timeout);
423 if (waitwhile == Running) {
426 if (process_->waitForFinished(timeout))
428 bool stop = queryStopCommand(cmd_);
429 // The command may have finished in the meantime
430 if (process_->state() == QProcess::NotRunning)
444 // process events while waiting, no timeout
446 while (state == waitwhile && state != Error) {
447 waitAndProcessEvents();
449 return state != Error;
452 // process events while waiting with timeout
455 while (state == waitwhile && state != Error && !timedout) {
456 waitAndProcessEvents();
457 if (timer.elapsed() > timeout) {
458 bool stop = queryStopCommand(cmd_);
459 // The command may have finished in the meantime
460 if (process_->state() == QProcess::NotRunning)
469 return (state != Error) && !timedout;
473 SystemcallPrivate::~SystemcallPrivate()
476 out_data_[out_index_] = '\0';
482 err_data_[err_index_] = '\0';
492 void SystemcallPrivate::stdOut()
496 process_->setReadChannel(QProcess::StandardOutput);
497 while (process_->getChar(&c)) {
498 out_data_[out_index_++] = c;
499 if (c == '\n' || out_index_ + 1 == buffer_size_) {
500 out_data_[out_index_] = '\0';
502 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
510 void SystemcallPrivate::stdErr()
514 process_->setReadChannel(QProcess::StandardError);
515 while (process_->getChar(&c)) {
516 err_data_[err_index_++] = c;
517 if (c == '\n' || err_index_ + 1 == buffer_size_) {
518 err_data_[err_index_] = '\0';
520 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
528 void SystemcallPrivate::processStarted()
530 if (state != Running) {
532 ProgressInterface::instance()->processStarted(cmd_);
537 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
539 if (state != Finished) {
541 ProgressInterface::instance()->processFinished(cmd_);
546 void SystemcallPrivate::processError(QProcess::ProcessError)
549 ProgressInterface::instance()->appendError(errorMessage());
553 QString SystemcallPrivate::errorMessage() const
556 return "No QProcess available";
559 switch (process_->error()) {
560 case QProcess::FailedToStart:
561 message = "The process failed to start. Either the invoked program is missing, "
562 "or you may have insufficient permissions to invoke the program.";
564 case QProcess::Crashed:
565 message = "The process crashed some time after starting successfully.";
567 case QProcess::Timedout:
568 message = "The process timed out. It might be restarted automatically.";
570 case QProcess::WriteError:
571 message = "An error occurred when attempting to write to the process-> For example, "
572 "the process may not be running, or it may have closed its input channel.";
574 case QProcess::ReadError:
575 message = "An error occurred when attempting to read from the process-> For example, "
576 "the process may not be running.";
578 case QProcess::UnknownError:
580 message = "An unknown error occured.";
587 QString SystemcallPrivate::exitStatusMessage() const
590 return "No QProcess available";
593 switch (process_->exitStatus()) {
594 case QProcess::NormalExit:
595 message = "The process exited normally.";
597 case QProcess::CrashExit:
598 message = "The process crashed.";
601 message = "Unknown exit state.";
608 int SystemcallPrivate::exitCode()
613 return process_->exitCode();
617 QProcess* SystemcallPrivate::releaseProcess()
619 QProcess* released = process_;
625 void SystemcallPrivate::killProcess()
627 killProcess(process_);
631 void SystemcallPrivate::killProcess(QProcess * p)
635 p->closeReadChannel(QProcess::StandardOutput);
636 p->closeReadChannel(QProcess::StandardError);
644 #include "moc_SystemcallPrivate.cpp"
647 } // namespace support