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"
35 #include <QCoreApplication>
41 struct Sleep : QThread
43 static void millisec(unsigned long ms)
45 QThread::usleep(ms * 1000);
58 class ProgressDummy : public ProgressInterface
63 void processStarted(QString const &) {}
64 void processFinished(QString const &) {}
65 void appendMessage(QString const &) {}
66 void appendError(QString const &) {}
67 void clearMessages() {}
70 void lyxerrConnect() {}
71 void lyxerrDisconnect() {}
73 void warning(QString const &, QString const &) {}
74 void toggleWarning(QString const &, QString const &, QString const &) {}
75 void error(QString const &, QString const &, QString const &) {}
76 void information(QString const &, QString const &) {}
77 int prompt(docstring const &, docstring const &, int default_but, int,
78 docstring const &, docstring const &) { return default_but; }
82 static ProgressInterface * progress_instance = 0;
84 void ProgressInterface::setInstance(ProgressInterface* p)
86 progress_instance = p;
90 ProgressInterface * ProgressInterface::instance()
92 if (!progress_instance) {
93 static ProgressDummy dummy;
96 return progress_instance;
104 int Systemcall::startscript(Starttype how, string const & what,
105 string const & path, string const & lpath,
106 bool /*process_events*/)
109 to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath)))
112 if (how == DontWait) {
113 switch (os::shell()) {
118 command = "start /min " + command;
121 } else if (os::shell() == os::CMD_EXE)
122 command = subst(command, "cmd /d /c ", "");
124 return ::system(command.c_str());
132 * This is a parser that (mostly) mimics the behavior of a posix shell as
133 * regards quoting, but its output is tailored for being processed by QProcess.
134 * Note that shell metacharacters are not parsed.
136 * The escape character is the backslash.
137 * A backslash that is not quoted preserves the literal value of the following
138 * character, with the exception of a double-quote '"'. If a double-quote
139 * follows a backslash, it will be replaced by three consecutive double-quotes
140 * (this is how the QProcess parser recognizes a '"' as a simple character
141 * instead of a quoting character). Thus, for example:
147 * Characters enclosed in single-quotes ('') have their literal value preserved.
148 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
149 * be used to escape a single-quote in a single-quoted string. In other words,
150 * anything enclosed in single-quotes is passed as is, but the single-quotes
151 * themselves are eliminated. Thus, for example:
158 * Characters enclosed in double-quotes ("") have their literal value preserved,
159 * with the exception of the backslash. The backslash retains its special
160 * meaning as an escape character only when followed by a double-quote.
161 * Contrarily to the behavior of a posix shell, the double-quotes themselves
162 * are *not* eliminated. Thus, for example:
167 string const parsecmd(string const & incmd, string & infile, string & outfile,
170 bool in_single_quote = false;
171 bool in_double_quote = false;
172 bool escaped = false;
173 string const python_call = "python -tt";
174 vector<string> outcmd(4);
177 if (prefixIs(incmd, python_call)) {
178 outcmd[0] = os::python();
179 start = python_call.length();
182 for (size_t i = start, o = 0; i < incmd.length(); ++i) {
185 if (in_double_quote || escaped) {
186 if (in_double_quote && escaped)
190 in_single_quote = !in_single_quote;
194 if (in_single_quote) {
200 // Don't triple double-quotes for redirection
201 // files as these won't be parsed by QProcess
202 outcmd[o] += string(o ? "\"" : "\"\"\"");
206 in_double_quote = !in_double_quote;
208 } else if (c == '\\' && !escaped) {
210 } else if (c == '>' && !(in_double_quote || escaped)) {
211 if (suffixIs(outcmd[o], " 2")) {
212 outcmd[o] = rtrim(outcmd[o], "2");
215 if (suffixIs(outcmd[o], " 1"))
216 outcmd[o] = rtrim(outcmd[o], "1");
219 } else if (c == '<' && !(in_double_quote || escaped)) {
222 if (escaped && in_double_quote)
228 infile = trim(outcmd[3], " \"");
229 outfile = trim(outcmd[1], " \"");
230 errfile = trim(outcmd[2], " \"");
231 return trim(outcmd[0]);
237 int Systemcall::startscript(Starttype how, string const & what,
238 string const & path, string const & lpath,
241 string const what_ss = commandPrep(what);
243 lyxerr << "\nRunning: " << what_ss << endl;
245 LYXERR(Debug::INFO,"Running: " << what_ss);
250 QString const cmd = QString::fromLocal8Bit(
251 parsecmd(what_ss, infile, outfile, errfile).c_str());
253 SystemcallPrivate d(infile, outfile, errfile);
255 d.startProcess(cmd, path, lpath, how == DontWait);
256 if (how == DontWait && d.state == SystemcallPrivate::Running)
259 if (d.state == SystemcallPrivate::Error
260 || !d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
261 LYXERR0("Systemcall: '" << cmd << "' did not start!");
262 LYXERR0("error " << d.errorMessage());
266 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
267 os::timeout_min() * 60 * 1000)) {
268 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
269 LYXERR0("error " << d.errorMessage());
270 LYXERR0("status " << d.exitStatusMessage());
274 int const exit_code = d.exitCode();
276 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
283 SystemcallPrivate::SystemcallPrivate(std::string const & sf, std::string const & of,
284 std::string const & ef)
285 : state(Error), process_(new QProcess), out_index_(0), err_index_(0),
286 in_file_(sf), out_file_(of), err_file_(ef), process_events_(false)
288 if (!in_file_.empty())
289 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
290 if (!out_file_.empty()) {
291 if (out_file_[0] == '&') {
292 if (subst(out_file_, " ", "") == "&2"
293 && err_file_[0] != '&') {
294 out_file_ = err_file_;
295 process_->setProcessChannelMode(
296 QProcess::MergedChannels);
298 if (err_file_[0] == '&') {
299 // Leave alone things such as
300 // "1>&2 2>&1". Should not be harmful,
301 // but let's give anyway a warning.
302 LYXERR0("Unsupported stdout/stderr redirect.");
305 LYXERR0("Ambiguous stdout redirect: "
308 out_file_ = os::nulldev();
311 // Check whether we have to set the output file.
312 if (out_file_ != os::nulldev()) {
313 process_->setStandardOutputFile(QString::fromLocal8Bit(
317 if (!err_file_.empty()) {
318 if (err_file_[0] == '&') {
319 if (subst(err_file_, " ", "") == "&1"
320 && out_file_[0] != '&') {
321 process_->setProcessChannelMode(
322 QProcess::MergedChannels);
324 LYXERR0("Ambiguous stderr redirect: "
327 // In MergedChannels mode stderr goes to stdout.
328 err_file_ = os::nulldev();
330 // Check whether we have to set the error file.
331 if (err_file_ != os::nulldev()) {
332 process_->setStandardErrorFile(QString::fromLocal8Bit(
337 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
338 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
339 #if QT_VERSION >= 0x050600
340 connect(process_, SIGNAL(errorOccurred(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
342 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,
350 string const & lpath, bool detached)
354 state = SystemcallPrivate::Running;
356 // Avoid opening a console window when a viewer is started
357 if (in_file_.empty())
358 process_->setStandardInputFile(QProcess::nullDevice());
359 if (out_file_.empty())
360 process_->setStandardOutputFile(QProcess::nullDevice());
361 if (err_file_.empty())
362 process_->setStandardErrorFile(QProcess::nullDevice());
364 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_)) {
365 state = SystemcallPrivate::Error;
368 QProcess* released = releaseProcess();
370 } else if (process_) {
371 state = SystemcallPrivate::Starting;
372 process_->start(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
377 void SystemcallPrivate::processEvents()
379 if (process_events_) {
380 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
385 void SystemcallPrivate::waitAndProcessEvents()
387 Sleep::millisec(100);
394 bool queryStopCommand(QString const & cmd)
396 docstring text = bformat(_(
397 "The command\n%1$s\nhas not yet completed.\n\n"
398 "Do you want to stop it?"), qstring_to_ucs4(cmd));
399 return ProgressInterface::instance()->prompt(_("Stop command?"), text,
400 1, 1, _("&Stop it"), _("Let it &run")) == 0;
406 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
411 bool timedout = false;
412 process_events_ = process_events;
414 // Block GUI while waiting,
415 // relay on QProcess' wait functions
416 if (!process_events_) {
417 if (waitwhile == Starting)
418 return process_->waitForStarted(timeout);
419 if (waitwhile == Running) {
422 if (process_->waitForFinished(timeout))
424 bool stop = queryStopCommand(cmd_);
425 // The command may have finished in the meantime
426 if (process_->state() == QProcess::NotRunning)
440 // process events while waiting, no timeout
442 while (state == waitwhile && state != Error) {
443 waitAndProcessEvents();
445 return state != Error;
448 // process events while waiting with timeout
451 while (state == waitwhile && state != Error && !timedout) {
452 waitAndProcessEvents();
453 if (timer.elapsed() > timeout) {
454 bool stop = queryStopCommand(cmd_);
455 // The command may have finished in the meantime
456 if (process_->state() == QProcess::NotRunning)
465 return (state != Error) && !timedout;
469 SystemcallPrivate::~SystemcallPrivate()
472 out_data_[out_index_] = '\0';
478 err_data_[err_index_] = '\0';
488 void SystemcallPrivate::stdOut()
492 process_->setReadChannel(QProcess::StandardOutput);
493 while (process_->getChar(&c)) {
494 out_data_[out_index_++] = c;
495 if (c == '\n' || out_index_ + 1 == buffer_size_) {
496 out_data_[out_index_] = '\0';
498 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
506 void SystemcallPrivate::stdErr()
510 process_->setReadChannel(QProcess::StandardError);
511 while (process_->getChar(&c)) {
512 err_data_[err_index_++] = c;
513 if (c == '\n' || err_index_ + 1 == buffer_size_) {
514 err_data_[err_index_] = '\0';
516 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
524 void SystemcallPrivate::processStarted()
526 if (state != Running) {
528 ProgressInterface::instance()->processStarted(cmd_);
533 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
535 if (state != Finished) {
537 ProgressInterface::instance()->processFinished(cmd_);
542 void SystemcallPrivate::processError(QProcess::ProcessError)
545 ProgressInterface::instance()->appendError(errorMessage());
549 QString SystemcallPrivate::errorMessage() const
552 return "No QProcess available";
555 switch (process_->error()) {
556 case QProcess::FailedToStart:
557 message = "The process failed to start. Either the invoked program is missing, "
558 "or you may have insufficient permissions to invoke the program.";
560 case QProcess::Crashed:
561 message = "The process crashed some time after starting successfully.";
563 case QProcess::Timedout:
564 message = "The process timed out. It might be restarted automatically.";
566 case QProcess::WriteError:
567 message = "An error occurred when attempting to write to the process-> For example, "
568 "the process may not be running, or it may have closed its input channel.";
570 case QProcess::ReadError:
571 message = "An error occurred when attempting to read from the process-> For example, "
572 "the process may not be running.";
574 case QProcess::UnknownError:
576 message = "An unknown error occurred.";
583 QString SystemcallPrivate::exitStatusMessage() const
586 return "No QProcess available";
589 switch (process_->exitStatus()) {
590 case QProcess::NormalExit:
591 message = "The process exited normally.";
593 case QProcess::CrashExit:
594 message = "The process crashed.";
597 message = "Unknown exit state.";
604 int SystemcallPrivate::exitCode()
606 // From Qt's documentation, in regards to QProcess::exitCode(),
607 // "This value is not valid unless exitStatus() returns NormalExit"
608 if (!process_ || process_->exitStatus() != QProcess::NormalExit)
611 return process_->exitCode();
615 QProcess* SystemcallPrivate::releaseProcess()
617 QProcess* released = process_;
623 void SystemcallPrivate::killProcess()
625 killProcess(process_);
629 void SystemcallPrivate::killProcess(QProcess * p)
633 p->closeReadChannel(QProcess::StandardOutput);
634 p->closeReadChannel(QProcess::StandardError);
642 #include "moc_SystemcallPrivate.cpp"
645 } // namespace support