]> git.lyx.org Git - lyx.git/blob - src/support/Systemcall.cpp
Provide proper fallback if a bibliography processor is not found
[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 #include "LyXRC.h"
28
29 #include <cstdlib>
30 #include <iostream>
31
32 #include <QProcess>
33 #include <QElapsedTimer>
34 #include <QThread>
35 #include <QCoreApplication>
36 #include <QDebug>
37
38 #define USE_QPROCESS
39
40
41 struct Sleep : QThread
42 {
43         static void millisec(unsigned long ms)
44         {
45                 QThread::usleep(ms * 1000);
46         }
47 };
48
49
50
51
52 using namespace std;
53
54 namespace lyx {
55 namespace support {
56
57
58 class ProgressDummy : public ProgressInterface
59 {
60 public:
61         ProgressDummy() {}
62
63         void processStarted(QString const &) {}
64         void processFinished(QString const &) {}
65         void appendMessage(QString const &) {}
66         void appendError(QString const &) {}
67         void clearMessages() {}
68         void lyxerrFlush() {}
69
70         void lyxerrConnect() {}
71         void lyxerrDisconnect() {}
72
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; }
79 };
80
81
82 static ProgressInterface * progress_instance = 0;
83
84 void ProgressInterface::setInstance(ProgressInterface* p)
85 {
86         progress_instance = p;
87 }
88
89
90 ProgressInterface * ProgressInterface::instance()
91 {
92         if (!progress_instance) {
93                 static ProgressDummy dummy;
94                 return &dummy;
95         }
96         return progress_instance;
97 }
98
99
100
101
102 // Reuse of instance
103 #ifndef USE_QPROCESS
104 int Systemcall::startscript(Starttype how, string const & what,
105                             string const & path, string const & lpath,
106                             bool /*process_events*/)
107 {
108         string command =
109                 to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath)))
110                        + commandPrep(what);
111
112         if (how == DontWait) {
113                 switch (os::shell()) {
114                 case os::UNIX:
115                         command += " &";
116                         break;
117                 case os::CMD_EXE:
118                         command = "start /min " + command;
119                         break;
120                 }
121         } else if (os::shell() == os::CMD_EXE)
122                 command = subst(command, "cmd /d /c ", "");
123
124         return ::system(command.c_str());
125 }
126
127 #else
128
129 namespace {
130
131 /*
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.
135  *
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:
142  *     \\  ->  \
143  *     \a  ->  a
144  *     \"  ->  """
145  *
146  * Single-quotes.
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:
152  *    '\'    ->  \
153  *    '\\'   ->  \\
154  *    '\a'   ->  \a
155  *    'a\"b' ->  a\"b
156  *
157  * Double-quotes.
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:
163  *    "\\"   ->  "\\"
164  *    "\a"   ->  "\a"
165  *    "a\"b" ->  "a"""b"
166  */
167 string const parsecmd(string const & incmd, string & infile, string & outfile,
168                      string & errfile)
169 {
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);
175         size_t start = 0;
176
177         if (prefixIs(incmd, python_call)) {
178                 outcmd[0] = os::python();
179                 start = python_call.length();
180         }
181
182         for (size_t i = start, o = 0; i < incmd.length(); ++i) {
183                 char c = incmd[i];
184                 if (c == '\'') {
185                         if (in_double_quote || escaped) {
186                                 if (in_double_quote && escaped)
187                                         outcmd[o] += '\\';
188                                 outcmd[o] += c;
189                         } else
190                                 in_single_quote = !in_single_quote;
191                         escaped = false;
192                         continue;
193                 }
194                 if (in_single_quote) {
195                         outcmd[o] += c;
196                         continue;
197                 }
198                 if (c == '"') {
199                         if (escaped) {
200                                 // Don't triple double-quotes for redirection
201                                 // files as these won't be parsed by QProcess
202                                 outcmd[o] += string(o ? "\"" : "\"\"\"");
203                                 escaped = false;
204                         } else {
205                                 outcmd[o] += c;
206                                 in_double_quote = !in_double_quote;
207                         }
208                 } else if (c == '\\' && !escaped) {
209                         escaped = !escaped;
210                 } else if (c == '>' && !(in_double_quote || escaped)) {
211                         if (suffixIs(outcmd[o], " 2")) {
212                                 outcmd[o] = rtrim(outcmd[o], "2");
213                                 o = 2;
214                         } else {
215                                 if (suffixIs(outcmd[o], " 1"))
216                                         outcmd[o] = rtrim(outcmd[o], "1");
217                                 o = 1;
218                         }
219                 } else if (c == '<' && !(in_double_quote || escaped)) {
220                         o = 3;
221                 } else {
222                         if (escaped && in_double_quote)
223                                 outcmd[o] += '\\';
224                         outcmd[o] += c;
225                         escaped = false;
226                 }
227         }
228         infile  = trim(outcmd[3], " \"");
229         outfile = trim(outcmd[1], " \"");
230         errfile = trim(outcmd[2], " \"");
231         return trim(outcmd[0]);
232 }
233
234 } // namespace
235
236
237 int Systemcall::startscript(Starttype how, string const & what,
238                             string const & path, string const & lpath,
239                             bool process_events)
240 {
241         string const what_ss = commandPrep(what);
242         if (verbose)
243                 lyxerr << "\nRunning: " << what_ss << endl;
244         else
245                 LYXERR(Debug::INFO,"Running: " << what_ss);
246
247         string infile;
248         string outfile;
249         string errfile;
250         QString const cmd = QString::fromLocal8Bit(
251                         parsecmd(what_ss, infile, outfile, errfile).c_str());
252
253         SystemcallPrivate d(infile, outfile, errfile);
254
255         d.startProcess(cmd, path, lpath, how == DontWait);
256         if (how == DontWait && d.state == SystemcallPrivate::Running)
257                 return 0;
258
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());
263                 return 10;
264         }
265
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());
271                 return 20;
272         }
273
274         int const exit_code = d.exitCode();
275         if (exit_code) {
276                 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
277         }
278
279         return exit_code;
280 }
281
282
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)
287 {
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);
297                         } else {
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.");
303                                         err_file_.erase();
304                                 } else {
305                                         LYXERR0("Ambiguous stdout redirect: "
306                                                 << out_file_);
307                                 }
308                                 out_file_ = os::nulldev();
309                         }
310                 }
311                 // Check whether we have to set the output file.
312                 if (out_file_ != os::nulldev()) {
313                         process_->setStandardOutputFile(QString::fromLocal8Bit(
314                                                         out_file_.c_str()));
315                 }
316         }
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);
323                         } else {
324                                 LYXERR0("Ambiguous stderr redirect: "
325                                         << err_file_);
326                         }
327                         // In MergedChannels mode stderr goes to stdout.
328                         err_file_ = os::nulldev();
329                 }
330                 // Check whether we have to set the error file.
331                 if (err_file_ != os::nulldev()) {
332                         process_->setStandardErrorFile(QString::fromLocal8Bit(
333                                                         err_file_.c_str()));
334                 }
335         }
336
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)));
341 #else
342         connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
343 #endif
344         connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
345         connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
346 }
347
348
349 void SystemcallPrivate::startProcess(QString const & cmd, string const & path,
350                                      string const & lpath, bool detached)
351 {
352         cmd_ = cmd;
353 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
354         // FIXME pass command and arguments separated in the first place
355         /* The versions of startDetached() and start() that accept a
356          * QStringList object exist since Qt4, but it is only in Qt 5.15
357          * that splitCommand() was introduced and the plain versions of
358          * start/startDetached() have been deprecated.
359          * The cleanest solution would be to have parsecmd() produce a
360          * QStringList for arguments, instead of transforming the string
361          * into something that the QProcess splitter accepts.
362         */
363         QStringList arguments = QProcess::splitCommand(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
364         QString command = (arguments.empty()) ? QString() : arguments.first();
365         if (arguments.size() == 1)
366                 arguments.clear();
367         else if (!arguments.empty())
368                 arguments.removeFirst();
369 #endif
370         if (detached) {
371                 state = SystemcallPrivate::Running;
372 #ifdef Q_OS_WIN32
373                 // Avoid opening a console window when a viewer is started
374                 if (in_file_.empty())
375                         process_->setStandardInputFile(QProcess::nullDevice());
376                 if (out_file_.empty())
377                         process_->setStandardOutputFile(QProcess::nullDevice());
378                 if (err_file_.empty())
379                         process_->setStandardErrorFile(QProcess::nullDevice());
380 #endif
381 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
382                 if (!QProcess::startDetached(command, arguments)) {
383 #else
384                 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_)) {
385 #endif
386                         state = SystemcallPrivate::Error;
387                         return;
388                 }
389                 QProcess* released = releaseProcess();
390                 delete released;
391         } else if (process_) {
392                 state = SystemcallPrivate::Starting;
393 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
394                 process_->start(command, arguments);
395 #else
396                 process_->start(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
397 #endif
398         }
399 }
400
401
402 void SystemcallPrivate::processEvents()
403 {
404         if (process_events_) {
405                 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
406         }
407 }
408
409
410 void SystemcallPrivate::waitAndProcessEvents()
411 {
412         Sleep::millisec(100);
413         processEvents();
414 }
415
416
417 namespace {
418
419 bool queryStopCommand(QString const & cmd)
420 {
421         docstring text = bformat(_(
422                 "The command\n%1$s\nhas not yet completed.\n\n"
423                 "Do you want to stop it?"), qstring_to_ucs4(cmd));
424         return ProgressInterface::instance()->prompt(_("Stop command?"), text,
425                         1, 1, _("&Stop it"), _("Let it &run")) == 0;
426 }
427
428 } // namespace
429
430
431 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
432 {
433         if (!process_)
434                 return false;
435
436         bool timedout = false;
437         process_events_ = process_events;
438
439         // Block GUI while waiting,
440         // relay on QProcess' wait functions
441         if (!process_events_) {
442                 if (waitwhile == Starting)
443                         return process_->waitForStarted(timeout);
444                 if (waitwhile == Running) {
445                         int bump = 2;
446                         while (!timedout) {
447                                 if (process_->waitForFinished(timeout))
448                                         return true;
449                                 bool stop = queryStopCommand(cmd_);
450                                 // The command may have finished in the meantime
451                                 if (process_->state() == QProcess::NotRunning)
452                                         return true;
453                                 if (stop) {
454                                         timedout = true;
455                                         process_->kill();
456                                 } else {
457                                         timeout *= bump;
458                                         bump = 3;
459                                 }
460                         }
461                 }
462                 return false;
463         }
464
465         // process events while waiting, no timeout
466         if (timeout == -1) {
467                 while (state == waitwhile && state != Error) {
468                         waitAndProcessEvents();
469                 }
470                 return state != Error;
471         }
472
473         // process events while waiting with timeout
474         QElapsedTimer timer;
475         timer.start();
476         while (state == waitwhile && state != Error && !timedout) {
477                 waitAndProcessEvents();
478                 if (timer.elapsed() > timeout) {
479                         bool 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_ = 0;
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