]> git.lyx.org Git - lyx.git/blob - src/support/Systemcall.cpp
Properly check return values so TIMEOUT is recognized.
[lyx.git] / src / support / Systemcall.cpp
1 /**
2  * \file Systemcall.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Angus Leeming
8  * \author Enrico Forestieri
9  * \author Peter Kuemmel
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
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"
25
26 #include "LyX.h"
27
28 #include <cstdlib>
29 #include <iostream>
30
31 #include <QProcess>
32 #include <QElapsedTimer>
33 #include <QThread>
34 #include <QCoreApplication>
35 #include <QDebug>
36
37 #define USE_QPROCESS
38
39
40 struct Sleep : QThread
41 {
42         static void millisec(unsigned long ms)
43         {
44                 QThread::usleep(ms * 1000);
45         }
46 };
47
48
49
50
51 using namespace std;
52
53 namespace lyx {
54 namespace support {
55
56
57 class ProgressDummy : public ProgressInterface
58 {
59 public:
60         ProgressDummy() {}
61
62         void processStarted(QString const &) {}
63         void processFinished(QString const &) {}
64         void appendMessage(QString const &) {}
65         void appendError(QString const &) {}
66         void clearMessages() {}
67         void lyxerrFlush() {}
68
69         void lyxerrConnect() {}
70         void lyxerrDisconnect() {}
71
72         void warning(QString const &, QString const &) {}
73         void toggleWarning(QString const &, QString const &, QString const &) {}
74         void error(QString const &, 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; }
78 };
79
80
81 static ProgressInterface * progress_instance = nullptr;
82
83 void ProgressInterface::setInstance(ProgressInterface* p)
84 {
85         progress_instance = p;
86 }
87
88
89 ProgressInterface * ProgressInterface::instance()
90 {
91         if (!progress_instance) {
92                 static ProgressDummy dummy;
93                 return &dummy;
94         }
95         return progress_instance;
96 }
97
98
99
100
101 // Reuse of instance
102 #ifndef USE_QPROCESS
103 int Systemcall::startscript(Starttype how, string const & what,
104                             string const & path, string const & lpath,
105                             bool /*process_events*/)
106 {
107         string command =
108                 to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath)))
109                        + commandPrep(what);
110
111         if (how == DontWait) {
112                 switch (os::shell()) {
113                 case os::UNIX:
114                         command += " &";
115                         break;
116                 case os::CMD_EXE:
117                         command = "start /min " + command;
118                         break;
119                 }
120         } else if (os::shell() == os::CMD_EXE)
121                 command = subst(command, "cmd /d /c ", "");
122
123         return ::system(command.c_str());
124 }
125
126 #else
127
128 namespace {
129
130 /*
131  * This is a parser that (mostly) mimics the behavior of a posix shell as
132  * regards quoting, but its output is tailored for being processed by QProcess.
133  * Note that shell metacharacters are not parsed.
134  *
135  * The escape character is the backslash.
136  * A backslash that is not quoted preserves the literal value of the following
137  * character, with the exception of a double-quote '"'. If a double-quote
138  * follows a backslash, it will be replaced by three consecutive double-quotes
139  * (this is how the QProcess parser recognizes a '"' as a simple character
140  * instead of a quoting character). Thus, for example:
141  *     \\  ->  \
142  *     \a  ->  a
143  *     \"  ->  """
144  *
145  * Single-quotes.
146  * Characters enclosed in single-quotes ('') have their literal value preserved.
147  * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
148  * be used to escape a single-quote in a single-quoted string. In other words,
149  * anything enclosed in single-quotes is passed as is, but the single-quotes
150  * themselves are eliminated. Thus, for example:
151  *    '\'    ->  \
152  *    '\\'   ->  \\
153  *    '\a'   ->  \a
154  *    'a\"b' ->  a\"b
155  *
156  * Double-quotes.
157  * Characters enclosed in double-quotes ("") have their literal value preserved,
158  * with the exception of the backslash. The backslash retains its special
159  * meaning as an escape character only when followed by a double-quote.
160  * Contrarily to the behavior of a posix shell, the double-quotes themselves
161  * are *not* eliminated. Thus, for example:
162  *    "\\"   ->  "\\"
163  *    "\a"   ->  "\a"
164  *    "a\"b" ->  "a"""b"
165  */
166 string const parsecmd(string const & incmd, string & infile, string & outfile,
167                      string & errfile)
168 {
169         bool in_single_quote = false;
170         bool in_double_quote = false;
171         bool escaped = false;
172         string const python_call = "python -tt";
173         vector<string> outcmd(4);
174         size_t start = 0;
175
176         if (prefixIs(incmd, python_call)) {
177                 outcmd[0] = os::python();
178                 start = python_call.length();
179         }
180
181         for (size_t i = start, o = 0; i < incmd.length(); ++i) {
182                 char c = incmd[i];
183                 if (c == '\'') {
184                         if (in_double_quote || escaped) {
185                                 if (in_double_quote && escaped)
186                                         outcmd[o] += '\\';
187                                 outcmd[o] += c;
188                         } else
189                                 in_single_quote = !in_single_quote;
190                         escaped = false;
191                         continue;
192                 }
193                 if (in_single_quote) {
194                         outcmd[o] += c;
195                         continue;
196                 }
197                 if (c == '"') {
198                         if (escaped) {
199                                 // Don't triple double-quotes for redirection
200                                 // files as these won't be parsed by QProcess
201                                 outcmd[o] += string(o ? "\"" : "\"\"\"");
202                                 escaped = false;
203                         } else {
204                                 outcmd[o] += c;
205                                 in_double_quote = !in_double_quote;
206                         }
207                 } else if (c == '\\' && !escaped) {
208                         escaped = true;
209                 } else if (c == '>' && !(in_double_quote || escaped)) {
210                         if (suffixIs(outcmd[o], " 2")) {
211                                 outcmd[o] = rtrim(outcmd[o], "2");
212                                 o = 2;
213                         } else {
214                                 if (suffixIs(outcmd[o], " 1"))
215                                         outcmd[o] = rtrim(outcmd[o], "1");
216                                 o = 1;
217                         }
218                 } else if (c == '<' && !(in_double_quote || escaped)) {
219                         o = 3;
220                 } else {
221                         if (escaped && in_double_quote)
222                                 outcmd[o] += '\\';
223                         outcmd[o] += c;
224                         escaped = false;
225                 }
226         }
227         infile  = trim(outcmd[3], " \"");
228         outfile = trim(outcmd[1], " \"");
229         errfile = trim(outcmd[2], " \"");
230         return trim(outcmd[0]);
231 }
232
233 } // namespace
234
235
236 void Systemcall::killscript()
237 {
238         SystemcallPrivate::kill_script = true;
239 }
240
241
242 int Systemcall::startscript(Starttype how, string const & what,
243                             string const & path, string const & lpath,
244                             bool process_events)
245 {
246         string const what_ss = commandPrep(what);
247         if (verbose)
248                 lyxerr << "\nRunning: " << what_ss << endl;
249         else
250                 LYXERR(Debug::INFO,"Running: " << what_ss);
251
252         string infile;
253         string outfile;
254         string errfile;
255         QString const cmd = QString::fromLocal8Bit(
256                         parsecmd(what_ss, infile, outfile, errfile).c_str());
257
258         SystemcallPrivate d(infile, outfile, errfile);
259         bool do_events = process_events || how == WaitLoop;
260
261         d.startProcess(cmd, path, lpath, how == DontWait);
262         if (how == DontWait && d.state == SystemcallPrivate::Running)
263                 return OK;
264
265         if (d.state == SystemcallPrivate::Error
266                         || !d.waitWhile(SystemcallPrivate::Starting, do_events, -1)) {
267                 if (d.state == SystemcallPrivate::Error) {
268                         LYXERR0("Systemcall: '" << cmd << "' did not start!");
269                         LYXERR0("error " << d.errorMessage());
270                         return NOSTART;
271                 } else if (d.state == SystemcallPrivate::Killed) {
272                         LYXERR0("Killed: " << cmd);
273                         return KILLED;
274                 }
275         }
276
277         if (!d.waitWhile(SystemcallPrivate::Running, do_events,
278                          os::timeout_min() * 60 * 1000)) {
279                 if (d.state == SystemcallPrivate::Killed) {
280                         LYXERR0("Killed: " << cmd);
281                         return KILLED;
282                 }
283                 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
284                 LYXERR0("error " << d.errorMessage());
285                 LYXERR0("status " << d.exitStatusMessage());
286                 return TIMEOUT;
287         }
288
289         int const exit_code = d.exitCode();
290         if (exit_code) {
291                 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
292         }
293
294         return exit_code;
295 }
296
297
298 bool SystemcallPrivate::kill_script = false;
299
300
301 SystemcallPrivate::SystemcallPrivate(std::string const & sf, std::string const & of,
302                                      std::string const & ef)
303         : state(Error), process_(new QProcess), out_index_(0), err_index_(0),
304           in_file_(sf), out_file_(of), err_file_(ef), process_events_(false)
305 {
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);
315                         } else {
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.");
321                                         err_file_.erase();
322                                 } else {
323                                         LYXERR0("Ambiguous stdout redirect: "
324                                                 << out_file_);
325                                 }
326                                 out_file_ = os::nulldev();
327                         }
328                 }
329                 // Check whether we have to set the output file.
330                 if (out_file_ != os::nulldev()) {
331                         process_->setStandardOutputFile(QString::fromLocal8Bit(
332                                                         out_file_.c_str()));
333                 }
334         }
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);
341                         } else {
342                                 LYXERR0("Ambiguous stderr redirect: "
343                                         << err_file_);
344                         }
345                         // In MergedChannels mode stderr goes to stdout.
346                         err_file_ = os::nulldev();
347                 }
348                 // Check whether we have to set the error file.
349                 if (err_file_ != os::nulldev()) {
350                         process_->setStandardErrorFile(QString::fromLocal8Bit(
351                                                         err_file_.c_str()));
352                 }
353         }
354
355         connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
356         connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
357 #if QT_VERSION >= 0x050600
358         connect(process_, SIGNAL(errorOccurred(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
359 #else
360         connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
361 #endif
362         connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
363         connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
364 }
365
366
367 void SystemcallPrivate::startProcess(QString const & cmd, string const & path,
368                                      string const & lpath, bool detached)
369 {
370         cmd_ = cmd;
371         if (detached) {
372                 state = SystemcallPrivate::Running;
373 #ifdef Q_OS_WIN32
374                 // Avoid opening a console window when a viewer is started
375                 if (in_file_.empty())
376                         process_->setStandardInputFile(QProcess::nullDevice());
377                 if (out_file_.empty())
378                         process_->setStandardOutputFile(QProcess::nullDevice());
379                 if (err_file_.empty())
380                         process_->setStandardErrorFile(QProcess::nullDevice());
381 #endif
382                 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_)) {
383                         state = SystemcallPrivate::Error;
384                         return;
385                 }
386                 QProcess* released = releaseProcess();
387                 delete released;
388         } else if (process_) {
389                 state = SystemcallPrivate::Starting;
390                 process_->start(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
391         }
392 }
393
394
395 bool SystemcallPrivate::waitAndCheck()
396 {
397         Sleep::millisec(100);
398         if (kill_script) {
399                 // is there a better place to reset this?
400                 process_->kill();
401                 state = Killed;
402                 kill_script = false;
403                 LYXERR0("Export Canceled!!");
404                 return false;
405         }
406         QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
407         return true;
408 }
409
410
411 namespace {
412
413 bool queryStopCommand(QString const & cmd)
414 {
415         docstring text = bformat(_(
416                 "The command\n%1$s\nhas not yet completed.\n\n"
417                 "Do you want to stop it?"), qstring_to_ucs4(cmd));
418         return ProgressInterface::instance()->prompt(_("Stop command?"), text,
419                         1, 1, _("&Stop it"), _("Let it &run")) == 0;
420 }
421
422 } // namespace
423
424
425 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
426 {
427         timeout = 1000;
428         if (!process_)
429                 return false;
430
431         bool timedout = false;
432         process_events_ = process_events;
433
434         // Block GUI while waiting,
435         // relay on QProcess' wait functions
436         if (!process_events_) {
437                 if (waitwhile == Starting)
438                         return process_->waitForStarted(timeout);
439                 if (waitwhile == Running) {
440                         int bump = 2;
441                         while (!timedout) {
442                                 if (process_->waitForFinished(timeout))
443                                         return true;
444                                 bool const stop = queryStopCommand(cmd_);
445                                 // The command may have finished in the meantime
446                                 if (process_->state() == QProcess::NotRunning)
447                                         return true;
448                                 if (stop) {
449                                         timedout = true;
450                                         process_->kill();
451                                 } else {
452                                         timeout *= bump;
453                                         bump = 3;
454                                 }
455                         }
456                 }
457                 return false;
458         }
459
460         // process events while waiting, no timeout
461         if (timeout == -1) {
462                 while (state == waitwhile && state != Error) {
463                         // check for cancellation of background process
464                         if (!waitAndCheck())
465                                 return false;
466                 }
467                 return state != Error;
468         }
469
470         // process events while waiting with timeout
471         QElapsedTimer timer;
472         timer.start();
473         while (state == waitwhile && state != Error && !timedout) {
474                 // check for cancellation of background process
475                 if (!waitAndCheck())
476                         return false;
477
478                 if (timer.elapsed() > timeout) {
479                         bool const stop = queryStopCommand(cmd_);
480                         // The command may have finished in the meantime
481                         if (process_->state() == QProcess::NotRunning)
482                                 break;
483                         if (stop) {
484                                 timedout = true;
485                                 process_->kill();
486                         } else
487                                 timeout *= 3;
488                 }
489         }
490         return (state != Error) && !timedout;
491 }
492
493
494 SystemcallPrivate::~SystemcallPrivate()
495 {
496         if (out_index_) {
497                 out_data_[out_index_] = '\0';
498                 out_index_ = 0;
499                 cout << out_data_;
500         }
501         cout.flush();
502         if (err_index_) {
503                 err_data_[err_index_] = '\0';
504                 err_index_ = 0;
505                 cerr << err_data_;
506         }
507         cerr.flush();
508
509         killProcess();
510 }
511
512
513 void SystemcallPrivate::stdOut()
514 {
515         if (process_) {
516                 char c;
517                 process_->setReadChannel(QProcess::StandardOutput);
518                 while (process_->getChar(&c)) {
519                         out_data_[out_index_++] = c;
520                         if (c == '\n' || out_index_ + 1 == buffer_size_) {
521                                 out_data_[out_index_] = '\0';
522                                 out_index_ = 0;
523                                 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
524                                 cout << out_data_;
525                         }
526                 }
527         }
528 }
529
530
531 void SystemcallPrivate::stdErr()
532 {
533         if (process_) {
534                 char c;
535                 process_->setReadChannel(QProcess::StandardError);
536                 while (process_->getChar(&c)) {
537                         err_data_[err_index_++] = c;
538                         if (c == '\n' || err_index_ + 1 == buffer_size_) {
539                                 err_data_[err_index_] = '\0';
540                                 err_index_ = 0;
541                                 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
542                                 cerr << err_data_;
543                         }
544                 }
545         }
546 }
547
548
549 void SystemcallPrivate::processStarted()
550 {
551         if (state != Running) {
552                 state = Running;
553                 ProgressInterface::instance()->processStarted(cmd_);
554         }
555 }
556
557
558 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
559 {
560         if (state != Finished) {
561                 state = Finished;
562                 ProgressInterface::instance()->processFinished(cmd_);
563         }
564 }
565
566
567 void SystemcallPrivate::processError(QProcess::ProcessError)
568 {
569         state = Error;
570         ProgressInterface::instance()->appendError(errorMessage());
571 }
572
573
574 QString SystemcallPrivate::errorMessage() const
575 {
576         if (!process_)
577                 return "No QProcess available";
578
579         QString message;
580         switch (process_->error()) {
581                 case QProcess::FailedToStart:
582                         message = "The process failed to start. Either the invoked program is missing, "
583                                       "or you may have insufficient permissions to invoke the program.";
584                         break;
585                 case QProcess::Crashed:
586                         message = "The process crashed some time after starting successfully.";
587                         break;
588                 case QProcess::Timedout:
589                         message = "The process timed out. It might be restarted automatically.";
590                         break;
591                 case QProcess::WriteError:
592                         message = "An error occurred when attempting to write to the process-> For example, "
593                                       "the process may not be running, or it may have closed its input channel.";
594                         break;
595                 case QProcess::ReadError:
596                         message = "An error occurred when attempting to read from the process-> For example, "
597                                       "the process may not be running.";
598                         break;
599                 case QProcess::UnknownError:
600                 default:
601                         message = "An unknown error occurred.";
602                         break;
603         }
604         return message;
605 }
606
607
608 QString SystemcallPrivate::exitStatusMessage() const
609 {
610         if (!process_)
611                 return "No QProcess available";
612
613         QString message;
614         switch (process_->exitStatus()) {
615                 case QProcess::NormalExit:
616                         message = "The process exited normally.";
617                         break;
618                 case QProcess::CrashExit:
619                         message = "The process crashed.";
620                         break;
621                 default:
622                         message = "Unknown exit state.";
623                         break;
624         }
625         return message;
626 }
627
628
629 int SystemcallPrivate::exitCode()
630 {
631         // From Qt's documentation, in regards to QProcess::exitCode(),
632         // "This value is not valid unless exitStatus() returns NormalExit"
633         if (!process_ || process_->exitStatus() != QProcess::NormalExit)
634                 return -1;
635
636         return process_->exitCode();
637 }
638
639
640 QProcess* SystemcallPrivate::releaseProcess()
641 {
642         QProcess* released = process_;
643         process_ = nullptr;
644         return released;
645 }
646
647
648 void SystemcallPrivate::killProcess()
649 {
650         killProcess(process_);
651 }
652
653
654 void SystemcallPrivate::killProcess(QProcess * p)
655 {
656         if (p) {
657                 p->disconnect();
658                 p->closeReadChannel(QProcess::StandardOutput);
659                 p->closeReadChannel(QProcess::StandardError);
660                 p->close();
661                 delete p;
662         }
663 }
664
665
666
667 #include "moc_SystemcallPrivate.cpp"
668 #endif
669
670 } // namespace support
671 } // namespace lyx