]> git.lyx.org Git - lyx.git/blob - src/support/Systemcall.cpp
Fix problem with python and change of PATH
[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 "LyXRC.h"
27
28 #include <cstdlib>
29 #include <iostream>
30
31 #include <QProcess>
32 #include <QTime>
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 &) {}
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 = 0;
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                             std::string const & path, bool /*process_events*/)
105 {
106         string const python_call = "python -tt";
107         string command = to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path)));
108
109         if (prefixIs(what, python_call))
110                 command += os::python() + what.substr(python_call.length());
111         else
112                 command += what;
113
114         if (how == DontWait) {
115                 switch (os::shell()) {
116                 case os::UNIX:
117                         command += " &";
118                         break;
119                 case os::CMD_EXE:
120                         command = "start /min " + command;
121                         break;
122                 }
123         } else if (os::shell() == os::CMD_EXE)
124                 command = subst(command, "cmd /d /c ", "");
125
126         return ::system(command.c_str());
127 }
128
129 #else
130
131 namespace {
132
133 /*
134  * This is a parser that (mostly) mimics the behavior of a posix shell as
135  * regards quoting, but its output is tailored for being processed by QProcess.
136  * Note that shell metacharacters are not parsed.
137  *
138  * The escape character is the backslash.
139  * A backslash that is not quoted preserves the literal value of the following
140  * character, with the exception of a double-quote '"'. If a double-quote
141  * follows a backslash, it will be replaced by three consecutive double-quotes
142  * (this is how the QProcess parser recognizes a '"' as a simple character
143  * instead of a quoting character). Thus, for example:
144  *     \\  ->  \
145  *     \a  ->  a
146  *     \"  ->  """
147  *
148  * Single-quotes.
149  * Characters enclosed in single-quotes ('') have their literal value preserved.
150  * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
151  * be used to escape a single-quote in a single-quoted string. In other words,
152  * anything enclosed in single-quotes is passed as is, but the single-quotes
153  * themselves are eliminated. Thus, for example:
154  *    '\'    ->  \
155  *    '\\'   ->  \\
156  *    '\a'   ->  \a
157  *    'a\"b' ->  a\"b
158  *
159  * Double-quotes.
160  * Characters enclosed in double-quotes ("") have their literal value preserved,
161  * with the exception of the backslash. The backslash retains its special
162  * meaning as an escape character only when followed by a double-quote.
163  * Contrarily to the behavior of a posix shell, the double-quotes themselves
164  * are *not* eliminated. Thus, for example:
165  *    "\\"   ->  "\\"
166  *    "\a"   ->  "\a"
167  *    "a\"b" ->  "a"""b"
168  */
169 string const parsecmd(string const & incmd, string & infile, string & outfile,
170                      string & errfile)
171 {
172         bool in_single_quote = false;
173         bool in_double_quote = false;
174         bool escaped = false;
175         string const python_call = "python -tt";
176         vector<string> outcmd(4);
177         size_t start = 0;
178
179         if (prefixIs(incmd, python_call)) {
180                 outcmd[0] = os::python();
181                 start = python_call.length();
182         }
183
184         for (size_t i = start, o = 0; i < incmd.length(); ++i) {
185                 char c = incmd[i];
186                 if (c == '\'') {
187                         if (in_double_quote || escaped) {
188                                 if (in_double_quote && escaped)
189                                         outcmd[o] += '\\';
190                                 outcmd[o] += c;
191                         } else
192                                 in_single_quote = !in_single_quote;
193                         escaped = false;
194                         continue;
195                 }
196                 if (in_single_quote) {
197                         outcmd[o] += c;
198                         continue;
199                 }
200                 if (c == '"') {
201                         if (escaped) {
202                                 // Don't triple double-quotes for redirection
203                                 // files as these won't be parsed by QProcess
204                                 outcmd[o] += string(o ? "\"" : "\"\"\"");
205                                 escaped = false;
206                         } else {
207                                 outcmd[o] += c;
208                                 in_double_quote = !in_double_quote;
209                         }
210                 } else if (c == '\\' && !escaped) {
211                         escaped = !escaped;
212                 } else if (c == '>' && !(in_double_quote || escaped)) {
213                         if (suffixIs(outcmd[o], " 2")) {
214                                 outcmd[o] = rtrim(outcmd[o], "2");
215                                 o = 2;
216                         } else {
217                                 if (suffixIs(outcmd[o], " 1"))
218                                         outcmd[o] = rtrim(outcmd[o], "1");
219                                 o = 1;
220                         }
221                 } else if (c == '<' && !(in_double_quote || escaped)) {
222                         o = 3;
223                 } else {
224                         if (escaped && in_double_quote)
225                                 outcmd[o] += '\\';
226                         outcmd[o] += c;
227                         escaped = false;
228                 }
229         }
230         infile  = trim(outcmd[3], " \"");
231         outfile = trim(outcmd[1], " \"");
232         errfile = trim(outcmd[2], " \"");
233         return trim(outcmd[0]);
234 }
235
236 } // namespace anon
237
238
239
240 int Systemcall::startscript(Starttype how, string const & what,
241                             string const & path, bool process_events)
242 {
243         LYXERR(Debug::INFO,"Running: " << what);
244
245         string infile;
246         string outfile;
247         string errfile;
248         QString const cmd = QString::fromLocal8Bit(
249                         parsecmd(what, infile, outfile, errfile).c_str());
250
251         SystemcallPrivate d(infile, outfile, errfile);
252
253 #ifdef Q_OS_WIN32
254         // QProcess::startDetached cannot provide environment variables. When the
255         // environment variables are set using the latexEnvCmdPrefix and the process
256         // is started with QProcess::startDetached, a console window is shown every 
257         // time a viewer is started. To avoid this, we fall back on Windows to the 
258         // original implementation that creates a QProcess object.
259         d.startProcess(cmd, path, false);
260         if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
261                 LYXERR0("Systemcall: '" << cmd << "' did not start!");
262                 LYXERR0("error " << d.errorMessage());
263                 return 10;
264         }
265         if (how == DontWait) {
266                 d.releaseProcess();
267                 return 0;
268         }
269 #else
270         d.startProcess(cmd, path, how == DontWait);
271         if (how == DontWait && d.state == SystemcallPrivate::Running)
272                 return 0;
273
274         if (d.state == SystemcallPrivate::Error
275                         || !d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
276                 LYXERR0("Systemcall: '" << cmd << "' did not start!");
277                 LYXERR0("error " << d.errorMessage());
278                 return 10;
279         }
280 #endif
281
282         if (!d.waitWhile(SystemcallPrivate::Running, process_events,
283                          os::timeout_min() * 60 * 1000)) {
284                 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
285                 LYXERR0("error " << d.errorMessage());
286                 LYXERR0("status " << d.exitStatusMessage());
287                 return 20;
288         }
289
290         int const exit_code = d.exitCode();
291         if (exit_code) {
292                 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
293         }
294
295         return exit_code;
296 }
297
298
299 SystemcallPrivate::SystemcallPrivate(std::string const & sf,
300                                      std::string const & of,
301                                      std::string const & ef) :
302                                 process_(new QProcess), 
303                                 out_index_(0),
304                                 err_index_(0),
305                                 in_file_(sf),
306                                 out_file_(of), 
307                                 err_file_(ef), 
308                                 process_events_(false)
309 {
310         if (!in_file_.empty())
311                 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
312         if (!out_file_.empty()) {
313                 if (out_file_[0] == '&') {
314                         if (subst(out_file_, " ", "") == "&2"
315                             && err_file_[0] != '&') {
316                                 out_file_ = err_file_;
317                                 process_->setProcessChannelMode(
318                                                 QProcess::MergedChannels);
319                         } else {
320                                 if (err_file_[0] == '&') {
321                                         // Leave alone things such as
322                                         // "1>&2 2>&1". Should not be harmful,
323                                         // but let's give anyway a warning.
324                                         LYXERR0("Unsupported stdout/stderr redirect.");
325                                         err_file_.erase();
326                                 } else {
327                                         LYXERR0("Ambiguous stdout redirect: "
328                                                 << out_file_);
329                                 }
330                                 out_file_ = os::nulldev();
331                         }
332                 }
333                 // Check whether we have to set the output file.
334                 if (out_file_ != os::nulldev()) {
335                         process_->setStandardOutputFile(QString::fromLocal8Bit(
336                                                         out_file_.c_str()));
337                 }
338         }
339         if (!err_file_.empty()) {
340                 if (err_file_[0] == '&') {
341                         if (subst(err_file_, " ", "") == "&1"
342                             && out_file_[0] != '&') {
343                                 process_->setProcessChannelMode(
344                                                 QProcess::MergedChannels);
345                         } else {
346                                 LYXERR0("Ambiguous stderr redirect: "
347                                         << err_file_);
348                         }
349                         // In MergedChannels mode stderr goes to stdout.
350                         err_file_ = os::nulldev();
351                 }
352                 // Check whether we have to set the error file.
353                 if (err_file_ != os::nulldev()) {
354                         process_->setStandardErrorFile(QString::fromLocal8Bit(
355                                                         err_file_.c_str()));
356                 }
357         }
358
359         connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
360         connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
361         connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
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, bool detached)
368 {
369         cmd_ = cmd;
370         if (detached) {
371                 state = SystemcallPrivate::Running;
372                 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path)) + cmd_)) {
373                         state = SystemcallPrivate::Error;
374                         return;
375                 }
376                 QProcess* released = releaseProcess();
377                 delete released;
378         } else if (process_) {
379                 state = SystemcallPrivate::Starting;
380                 process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
381         }
382 }
383
384
385 void SystemcallPrivate::processEvents()
386 {
387         if (process_events_) {
388                 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
389         }
390 }
391
392
393 void SystemcallPrivate::waitAndProcessEvents()
394 {
395         Sleep::millisec(100);
396         processEvents();
397 }
398
399
400 namespace {
401
402 bool queryStopCommand(QString const & cmd)
403 {
404         docstring text = bformat(_(
405                 "The command\n%1$s\nhas not yet completed.\n\n"
406                 "Do you want to stop it?"), qstring_to_ucs4(cmd));
407         return ProgressInterface::instance()->prompt(_("Stop command?"), text,
408                         1, 1, _("&Stop it"), _("Let it &run")) == 0;
409 }
410
411 }
412
413
414 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
415 {
416         if (!process_)
417                 return false;
418
419         bool timedout = false;
420         process_events_ = process_events;
421
422         // Block GUI while waiting,
423         // relay on QProcess' wait functions
424         if (!process_events_) {
425                 if (waitwhile == Starting)
426                         return process_->waitForStarted(timeout);
427                 if (waitwhile == Running) {
428                         int bump = 2;
429                         while (!timedout) {
430                                 if (process_->waitForFinished(timeout))
431                                         return true;
432                                 bool stop = queryStopCommand(cmd_);
433                                 // The command may have finished in the meantime
434                                 if (process_->state() == QProcess::NotRunning)
435                                         return true;
436                                 if (stop) {
437                                         timedout = true;
438                                         process_->kill();
439                                 } else {
440                                         timeout *= bump;
441                                         bump = 3;
442                                 }
443                         }
444                 }
445                 return false;
446         }
447
448         // process events while waiting, no timeout
449         if (timeout == -1) {
450                 while (state == waitwhile && state != Error) {
451                         waitAndProcessEvents();
452                 }
453                 return state != Error;
454         } 
455
456         // process events while waiting with timeout
457         QTime timer;
458         timer.start();
459         while (state == waitwhile && state != Error && !timedout) {
460                 waitAndProcessEvents();
461                 if (timer.elapsed() > timeout) {
462                         bool stop = queryStopCommand(cmd_);
463                         // The command may have finished in the meantime
464                         if (process_->state() == QProcess::NotRunning)
465                                 break;
466                         if (stop) {
467                                 timedout = true;
468                                 process_->kill();
469                         } else
470                                 timeout *= 3;
471                 }
472         }
473         return (state != Error) && !timedout;
474 }
475
476
477 SystemcallPrivate::~SystemcallPrivate()
478 {
479         if (out_index_) {
480                 out_data_[out_index_] = '\0';
481                 out_index_ = 0;
482                 cout << out_data_;
483         }
484         cout.flush();
485         if (err_index_) {
486                 err_data_[err_index_] = '\0';
487                 err_index_ = 0;
488                 cerr << err_data_;
489         }
490         cerr.flush();
491
492         killProcess();
493 }
494
495
496 void SystemcallPrivate::stdOut()
497 {
498         if (process_) {
499                 char c;
500                 process_->setReadChannel(QProcess::StandardOutput);
501                 while (process_->getChar(&c)) {
502                         out_data_[out_index_++] = c;
503                         if (c == '\n' || out_index_ + 1 == buffer_size_) {
504                                 out_data_[out_index_] = '\0';
505                                 out_index_ = 0;
506                                 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
507                                 cout << out_data_;
508                         }
509                 }
510         }
511 }
512
513
514 void SystemcallPrivate::stdErr()
515 {
516         if (process_) {
517                 char c;
518                 process_->setReadChannel(QProcess::StandardError);
519                 while (process_->getChar(&c)) {
520                         err_data_[err_index_++] = c;
521                         if (c == '\n' || err_index_ + 1 == buffer_size_) {
522                                 err_data_[err_index_] = '\0';
523                                 err_index_ = 0;
524                                 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
525                                 cerr << err_data_;
526                         }
527                 }
528         }
529 }
530
531
532 void SystemcallPrivate::processStarted()
533 {
534         if (state != Running) {
535                 state = Running;
536                 ProgressInterface::instance()->processStarted(cmd_);
537         }
538 }
539
540
541 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
542 {
543         if (state != Finished) {
544                 state = Finished;
545                 ProgressInterface::instance()->processFinished(cmd_);
546         }
547 }
548
549
550 void SystemcallPrivate::processError(QProcess::ProcessError)
551 {
552         state = Error;
553         ProgressInterface::instance()->appendError(errorMessage());
554 }
555
556
557 QString SystemcallPrivate::errorMessage() const 
558 {
559         if (!process_)
560                 return "No QProcess available";
561
562         QString message;
563         switch (process_->error()) {
564                 case QProcess::FailedToStart:
565                         message = "The process failed to start. Either the invoked program is missing, "
566                                       "or you may have insufficient permissions to invoke the program.";
567                         break;
568                 case QProcess::Crashed:
569                         message = "The process crashed some time after starting successfully.";
570                         break;
571                 case QProcess::Timedout:
572                         message = "The process timed out. It might be restarted automatically.";
573                         break;
574                 case QProcess::WriteError:
575                         message = "An error occurred when attempting to write to the process-> For example, "
576                                       "the process may not be running, or it may have closed its input channel.";
577                         break;
578                 case QProcess::ReadError:
579                         message = "An error occurred when attempting to read from the process-> For example, "
580                                       "the process may not be running.";
581                         break;
582                 case QProcess::UnknownError:
583                 default:
584                         message = "An unknown error occured.";
585                         break;
586         }
587         return message;
588 }
589
590
591 QString SystemcallPrivate::exitStatusMessage() const
592 {
593         if (!process_)
594                 return "No QProcess available";
595
596         QString message;
597         switch (process_->exitStatus()) {
598                 case QProcess::NormalExit:
599                         message = "The process exited normally.";
600                         break;
601                 case QProcess::CrashExit:
602                         message = "The process crashed.";
603                         break;
604                 default:
605                         message = "Unknown exit state.";
606                         break;
607         }
608         return message;
609 }
610
611
612 int SystemcallPrivate::exitCode()
613 {
614         if (!process_)
615                 return -1;
616
617         return process_->exitCode();
618 }
619
620
621 QProcess* SystemcallPrivate::releaseProcess()
622 {
623         QProcess* released = process_;
624         process_ = 0;
625         return released;
626 }
627
628
629 void SystemcallPrivate::killProcess()
630 {
631         killProcess(process_);
632 }
633
634
635 void SystemcallPrivate::killProcess(QProcess * p)
636 {
637         if (p) {
638                 p->disconnect();
639                 p->closeReadChannel(QProcess::StandardOutput);
640                 p->closeReadChannel(QProcess::StandardError);
641                 p->close();
642                 delete p;
643         }
644 }
645
646
647
648 #include "moc_SystemcallPrivate.cpp"
649 #endif
650
651 } // namespace support
652 } // namespace lyx