]> git.lyx.org Git - lyx.git/blob - src/support/Systemcall.cpp
Account for old versions of Pygments
[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 <QTime>
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 anon
235
236
237
238 int Systemcall::startscript(Starttype how, string const & what,
239                             string const & path, string const & lpath,
240                             bool process_events)
241 {
242         string const what_ss = commandPrep(what);
243         if (verbose)
244                 lyxerr << "\nRunning: " << what_ss << endl;
245         else
246                 LYXERR(Debug::INFO,"Running: " << what_ss);
247
248         string infile;
249         string outfile;
250         string errfile;
251         QString const cmd = QString::fromLocal8Bit(
252                         parsecmd(what_ss, infile, outfile, errfile).c_str());
253
254         SystemcallPrivate d(infile, outfile, errfile);
255
256 #ifdef Q_OS_WIN32
257         // QProcess::startDetached cannot provide environment variables. When the
258         // environment variables are set using the latexEnvCmdPrefix and the process
259         // is started with QProcess::startDetached, a console window is shown every 
260         // time a viewer is started. To avoid this, we fall back on Windows to the 
261         // original implementation that creates a QProcess object.
262         d.startProcess(cmd, path, lpath, false);
263         if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
264                 LYXERR0("Systemcall: '" << cmd << "' did not start!");
265                 LYXERR0("error " << d.errorMessage());
266                 return 10;
267         }
268         if (how == DontWait) {
269                 d.releaseProcess();
270                 return 0;
271         }
272 #else
273         d.startProcess(cmd, path, lpath, how == DontWait);
274         if (how == DontWait && d.state == SystemcallPrivate::Running)
275                 return 0;
276
277         if (d.state == SystemcallPrivate::Error
278                         || !d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
279                 LYXERR0("Systemcall: '" << cmd << "' did not start!");
280                 LYXERR0("error " << d.errorMessage());
281                 return 10;
282         }
283 #endif
284
285         if (!d.waitWhile(SystemcallPrivate::Running, process_events,
286                          os::timeout_min() * 60 * 1000)) {
287                 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
288                 LYXERR0("error " << d.errorMessage());
289                 LYXERR0("status " << d.exitStatusMessage());
290                 return 20;
291         }
292
293         int const exit_code = d.exitCode();
294         if (exit_code) {
295                 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
296         }
297
298         return exit_code;
299 }
300
301
302 SystemcallPrivate::SystemcallPrivate(std::string const & sf, std::string const & of,
303                                      std::string const & ef)
304         : state(Error), process_(new QProcess), out_index_(0), err_index_(0),
305           in_file_(sf), out_file_(of), err_file_(ef), process_events_(false)
306 {
307         if (!in_file_.empty())
308                 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
309         if (!out_file_.empty()) {
310                 if (out_file_[0] == '&') {
311                         if (subst(out_file_, " ", "") == "&2"
312                             && err_file_[0] != '&') {
313                                 out_file_ = err_file_;
314                                 process_->setProcessChannelMode(
315                                                 QProcess::MergedChannels);
316                         } else {
317                                 if (err_file_[0] == '&') {
318                                         // Leave alone things such as
319                                         // "1>&2 2>&1". Should not be harmful,
320                                         // but let's give anyway a warning.
321                                         LYXERR0("Unsupported stdout/stderr redirect.");
322                                         err_file_.erase();
323                                 } else {
324                                         LYXERR0("Ambiguous stdout redirect: "
325                                                 << out_file_);
326                                 }
327                                 out_file_ = os::nulldev();
328                         }
329                 }
330                 // Check whether we have to set the output file.
331                 if (out_file_ != os::nulldev()) {
332                         process_->setStandardOutputFile(QString::fromLocal8Bit(
333                                                         out_file_.c_str()));
334                 }
335         }
336         if (!err_file_.empty()) {
337                 if (err_file_[0] == '&') {
338                         if (subst(err_file_, " ", "") == "&1"
339                             && out_file_[0] != '&') {
340                                 process_->setProcessChannelMode(
341                                                 QProcess::MergedChannels);
342                         } else {
343                                 LYXERR0("Ambiguous stderr redirect: "
344                                         << err_file_);
345                         }
346                         // In MergedChannels mode stderr goes to stdout.
347                         err_file_ = os::nulldev();
348                 }
349                 // Check whether we have to set the error file.
350                 if (err_file_ != os::nulldev()) {
351                         process_->setStandardErrorFile(QString::fromLocal8Bit(
352                                                         err_file_.c_str()));
353                 }
354         }
355
356         connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
357         connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
358 #if QT_VERSION >= 0x050600
359         connect(process_, SIGNAL(errorOccurred(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
360 #else
361         connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
362 #endif
363         connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
364         connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
365 }
366
367
368 void SystemcallPrivate::startProcess(QString const & cmd, string const & path,
369                                      string const & lpath, bool detached)
370 {
371         cmd_ = cmd;
372         if (detached) {
373                 state = SystemcallPrivate::Running;
374                 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_)) {
375                         state = SystemcallPrivate::Error;
376                         return;
377                 }
378                 QProcess* released = releaseProcess();
379                 delete released;
380         } else if (process_) {
381                 state = SystemcallPrivate::Starting;
382                 process_->start(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
383         }
384 }
385
386
387 void SystemcallPrivate::processEvents()
388 {
389         if (process_events_) {
390                 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
391         }
392 }
393
394
395 void SystemcallPrivate::waitAndProcessEvents()
396 {
397         Sleep::millisec(100);
398         processEvents();
399 }
400
401
402 namespace {
403
404 bool queryStopCommand(QString const & cmd)
405 {
406         docstring text = bformat(_(
407                 "The command\n%1$s\nhas not yet completed.\n\n"
408                 "Do you want to stop it?"), qstring_to_ucs4(cmd));
409         return ProgressInterface::instance()->prompt(_("Stop command?"), text,
410                         1, 1, _("&Stop it"), _("Let it &run")) == 0;
411 }
412
413 }
414
415
416 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
417 {
418         if (!process_)
419                 return false;
420
421         bool timedout = false;
422         process_events_ = process_events;
423
424         // Block GUI while waiting,
425         // relay on QProcess' wait functions
426         if (!process_events_) {
427                 if (waitwhile == Starting)
428                         return process_->waitForStarted(timeout);
429                 if (waitwhile == Running) {
430                         int bump = 2;
431                         while (!timedout) {
432                                 if (process_->waitForFinished(timeout))
433                                         return true;
434                                 bool stop = queryStopCommand(cmd_);
435                                 // The command may have finished in the meantime
436                                 if (process_->state() == QProcess::NotRunning)
437                                         return true;
438                                 if (stop) {
439                                         timedout = true;
440                                         process_->kill();
441                                 } else {
442                                         timeout *= bump;
443                                         bump = 3;
444                                 }
445                         }
446                 }
447                 return false;
448         }
449
450         // process events while waiting, no timeout
451         if (timeout == -1) {
452                 while (state == waitwhile && state != Error) {
453                         waitAndProcessEvents();
454                 }
455                 return state != Error;
456         } 
457
458         // process events while waiting with timeout
459         QTime timer;
460         timer.start();
461         while (state == waitwhile && state != Error && !timedout) {
462                 waitAndProcessEvents();
463                 if (timer.elapsed() > timeout) {
464                         bool stop = queryStopCommand(cmd_);
465                         // The command may have finished in the meantime
466                         if (process_->state() == QProcess::NotRunning)
467                                 break;
468                         if (stop) {
469                                 timedout = true;
470                                 process_->kill();
471                         } else
472                                 timeout *= 3;
473                 }
474         }
475         return (state != Error) && !timedout;
476 }
477
478
479 SystemcallPrivate::~SystemcallPrivate()
480 {
481         if (out_index_) {
482                 out_data_[out_index_] = '\0';
483                 out_index_ = 0;
484                 cout << out_data_;
485         }
486         cout.flush();
487         if (err_index_) {
488                 err_data_[err_index_] = '\0';
489                 err_index_ = 0;
490                 cerr << err_data_;
491         }
492         cerr.flush();
493
494         killProcess();
495 }
496
497
498 void SystemcallPrivate::stdOut()
499 {
500         if (process_) {
501                 char c;
502                 process_->setReadChannel(QProcess::StandardOutput);
503                 while (process_->getChar(&c)) {
504                         out_data_[out_index_++] = c;
505                         if (c == '\n' || out_index_ + 1 == buffer_size_) {
506                                 out_data_[out_index_] = '\0';
507                                 out_index_ = 0;
508                                 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
509                                 cout << out_data_;
510                         }
511                 }
512         }
513 }
514
515
516 void SystemcallPrivate::stdErr()
517 {
518         if (process_) {
519                 char c;
520                 process_->setReadChannel(QProcess::StandardError);
521                 while (process_->getChar(&c)) {
522                         err_data_[err_index_++] = c;
523                         if (c == '\n' || err_index_ + 1 == buffer_size_) {
524                                 err_data_[err_index_] = '\0';
525                                 err_index_ = 0;
526                                 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
527                                 cerr << err_data_;
528                         }
529                 }
530         }
531 }
532
533
534 void SystemcallPrivate::processStarted()
535 {
536         if (state != Running) {
537                 state = Running;
538                 ProgressInterface::instance()->processStarted(cmd_);
539         }
540 }
541
542
543 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
544 {
545         if (state != Finished) {
546                 state = Finished;
547                 ProgressInterface::instance()->processFinished(cmd_);
548         }
549 }
550
551
552 void SystemcallPrivate::processError(QProcess::ProcessError)
553 {
554         state = Error;
555         ProgressInterface::instance()->appendError(errorMessage());
556 }
557
558
559 QString SystemcallPrivate::errorMessage() const 
560 {
561         if (!process_)
562                 return "No QProcess available";
563
564         QString message;
565         switch (process_->error()) {
566                 case QProcess::FailedToStart:
567                         message = "The process failed to start. Either the invoked program is missing, "
568                                       "or you may have insufficient permissions to invoke the program.";
569                         break;
570                 case QProcess::Crashed:
571                         message = "The process crashed some time after starting successfully.";
572                         break;
573                 case QProcess::Timedout:
574                         message = "The process timed out. It might be restarted automatically.";
575                         break;
576                 case QProcess::WriteError:
577                         message = "An error occurred when attempting to write to the process-> For example, "
578                                       "the process may not be running, or it may have closed its input channel.";
579                         break;
580                 case QProcess::ReadError:
581                         message = "An error occurred when attempting to read from the process-> For example, "
582                                       "the process may not be running.";
583                         break;
584                 case QProcess::UnknownError:
585                 default:
586                         message = "An unknown error occurred.";
587                         break;
588         }
589         return message;
590 }
591
592
593 QString SystemcallPrivate::exitStatusMessage() const
594 {
595         if (!process_)
596                 return "No QProcess available";
597
598         QString message;
599         switch (process_->exitStatus()) {
600                 case QProcess::NormalExit:
601                         message = "The process exited normally.";
602                         break;
603                 case QProcess::CrashExit:
604                         message = "The process crashed.";
605                         break;
606                 default:
607                         message = "Unknown exit state.";
608                         break;
609         }
610         return message;
611 }
612
613
614 int SystemcallPrivate::exitCode()
615 {
616         // From Qt's documentation, in regards to QProcess::exitCode(),
617         // "This value is not valid unless exitStatus() returns NormalExit"
618         if (!process_ || process_->exitStatus() != QProcess::NormalExit)
619                 return -1;
620
621         return process_->exitCode();
622 }
623
624
625 QProcess* SystemcallPrivate::releaseProcess()
626 {
627         QProcess* released = process_;
628         process_ = 0;
629         return released;
630 }
631
632
633 void SystemcallPrivate::killProcess()
634 {
635         killProcess(process_);
636 }
637
638
639 void SystemcallPrivate::killProcess(QProcess * p)
640 {
641         if (p) {
642                 p->disconnect();
643                 p->closeReadChannel(QProcess::StandardOutput);
644                 p->closeReadChannel(QProcess::StandardError);
645                 p->close();
646                 delete p;
647         }
648 }
649
650
651
652 #include "moc_SystemcallPrivate.cpp"
653 #endif
654
655 } // namespace support
656 } // namespace lyx