1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2001 The LyX Team.
9 * ====================================================== */
14 #pragma implementation
19 #include "converter.h"
22 #include "bufferview_funcs.h"
24 #include "frontends/LyXView.h"
25 #include "lyx_cb.h" // ShowMessage()
27 #include "BufferView.h"
30 #include "frontends/Alert.h"
32 #include "support/filetools.h"
33 #include "support/lyxfunctional.h"
34 #include "support/path.h"
35 #include "support/systemcall.h"
37 #ifndef CXX_GLOBAL_CSTD
49 extern string system_lyxdir;
53 string const token_from("$$i");
54 string const token_base("$$b");
55 string const token_to("$$o");
56 string const token_lib("$$s");
58 //////////////////////////////////////////////////////////////////////////////
61 string const add_options(string const & command, string const & options)
64 string const tail = split(command, head, ' ');
65 return head + ' ' + options + ' ' + tail;
70 //////////////////////////////////////////////////////////////////////////////
72 bool Format::dummy() const
74 return extension().empty();
78 bool Format::isChildFormat() const
82 return isdigit(name_[name_.length() - 1]);
86 string const Format::parentFormat() const
88 return name_.substr(0, name_.length() - 1);
91 //////////////////////////////////////////////////////////////////////////////
93 // This method should return a reference, and throw an exception
94 // if the format named name cannot be found (Lgb)
95 Format const * Formats::getFormat(string const & name) const
97 FormatList::const_iterator cit =
98 find_if(formatlist.begin(), formatlist.end(),
99 lyx::compare_memfun(&Format::name, name));
100 if (cit != formatlist.end())
107 int Formats::getNumber(string const & name) const
109 FormatList::const_iterator cit =
110 find_if(formatlist.begin(), formatlist.end(),
111 lyx::compare_memfun(&Format::name, name));
112 if (cit != formatlist.end())
113 return cit - formatlist.begin();
119 void Formats::add(string const & name)
121 if (!getFormat(name))
122 add(name, name, name, string());
126 void Formats::add(string const & name, string const & extension,
127 string const & prettyname, string const & shortcut)
129 FormatList::iterator it =
130 find_if(formatlist.begin(), formatlist.end(),
131 lyx::compare_memfun(&Format::name, name));
132 if (it == formatlist.end())
133 formatlist.push_back(Format(name, extension, prettyname,
136 string viewer = it->viewer();
137 *it = Format(name, extension, prettyname, shortcut, viewer);
142 void Formats::erase(string const & name)
144 FormatList::iterator it =
145 find_if(formatlist.begin(), formatlist.end(),
146 lyx::compare_memfun(&Format::name, name));
147 if (it != formatlist.end())
148 formatlist.erase(it);
154 std::sort(formatlist.begin(), formatlist.end());
158 void Formats::setViewer(string const & name, string const & command)
161 FormatList::iterator it =
162 find_if(formatlist.begin(), formatlist.end(),
163 lyx::compare_memfun(&Format::name, name));
164 if (it != formatlist.end())
165 it->setViewer(command);
169 bool Formats::view(Buffer const * buffer, string const & filename,
170 string const & format_name) const
172 if (filename.empty())
175 Format const * format = getFormat(format_name);
176 if (format && format->viewer().empty() &&
177 format->isChildFormat())
178 format = getFormat(format->parentFormat());
179 if (!format || format->viewer().empty()) {
180 Alert::alert(_("Cannot view file"),
181 _("No information for viewing ")
182 + prettyName(format_name));
186 string command = format->viewer();
188 if (format_name == "dvi" &&
189 !lyxrc.view_dvi_paper_option.empty()) {
190 command += " " + lyxrc.view_dvi_paper_option;
191 string paper_size = converters.papersize(buffer);
192 if (paper_size == "letter")
194 command += " " + paper_size;
195 if (buffer->params.orientation
196 == BufferParams::ORIENTATION_LANDSCAPE)
200 command += " " + QuoteName(OnlyFilename((filename)));
202 lyxerr[Debug::FILES] << "Executing command: " << command << endl;
203 ShowMessage(buffer, _("Executing command:"), command);
205 Path p(OnlyPath(filename));
207 int const res = one.startscript(Systemcall::DontWait, command);
210 Alert::alert(_("Cannot view file"),
211 _("Error while executing"),
212 command.substr(0, 50));
219 string const Formats::prettyName(string const & name) const
221 Format const * format = getFormat(name);
223 return format->prettyname();
229 string const Formats::extension(string const & name) const
231 Format const * format = getFormat(name);
233 return format->extension();
238 //////////////////////////////////////////////////////////////////////////////
240 void Converter::readFlags()
242 string flag_list(flags);
243 while (!flag_list.empty()) {
244 string flag_name, flag_value;
245 flag_list = split(flag_list, flag_value, ',');
246 flag_value = split(flag_value, flag_name, '=');
247 if (flag_name == "latex")
249 else if (flag_name == "originaldir")
251 else if (flag_name == "needaux")
253 else if (flag_name == "resultdir")
254 result_dir = (flag_value.empty())
255 ? token_base : flag_value;
256 else if (flag_name == "resultfile")
257 result_file = flag_value;
258 else if (flag_name == "parselog")
259 parselog = flag_value;
261 if (!result_dir.empty() && result_file.empty())
262 result_file = "index." + formats.extension(to);
263 //if (!contains(command, token_from))
268 bool operator<(Converter const & a, Converter const & b)
270 // use the compare_ascii_no_case instead of compare_no_case,
271 // because in turkish, 'i' is not the lowercase version of 'I',
272 // and thus turkish locale breaks parsing of tags.
273 int const i = compare_ascii_no_case(a.From->prettyname(),
274 b.From->prettyname());
276 return compare_ascii_no_case(a.To->prettyname(), b.To->prettyname())
282 //////////////////////////////////////////////////////////////////////////////
284 class compare_Converter {
286 compare_Converter(string const & f, string const & t)
288 bool operator()(Converter const & c) {
289 return c.from == from && c.to == to;
297 Converter const * Converters::getConverter(string const & from,
300 ConverterList::const_iterator cit =
301 find_if(converterlist_.begin(), converterlist_.end(),
302 compare_Converter(from, to));
303 if (cit != converterlist_.end())
310 int Converters::getNumber(string const & from, string const & to)
312 ConverterList::const_iterator cit =
313 find_if(converterlist_.begin(), converterlist_.end(),
314 compare_Converter(from, to));
315 if (cit != converterlist_.end())
316 return cit - converterlist_.begin();
322 void Converters::add(string const & from, string const & to,
323 string const & command, string const & flags)
327 ConverterList::iterator it = find_if(converterlist_.begin(),
328 converterlist_.end(),
329 compare_Converter(from, to));
331 Converter converter(from, to, command, flags);
332 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
334 converter.command = command;
335 converter.flags = flags;
337 converter.readFlags();
339 if (converter.latex && (latex_command_.empty() || to == "dvi"))
340 latex_command_ = subst(command, token_from, "");
341 // If we have both latex & pdflatex, we set latex_command to latex.
342 // The latex_command is used to update the .aux file when running
343 // a converter that uses it.
345 if (it == converterlist_.end()) {
346 converterlist_.push_back(converter);
348 converter.From = it->From;
349 converter.To = it->To;
355 void Converters::erase(string const & from, string const & to)
357 ConverterList::iterator it = find_if(converterlist_.begin(),
358 converterlist_.end(),
359 compare_Converter(from, to));
360 if (it != converterlist_.end())
361 converterlist_.erase(it);
365 // This method updates the pointers From and To in all the converters.
366 // The code is not very efficient, but it doesn't matter as the number
367 // of formats and converters is small.
368 // Furthermore, this method is called only on startup, or after
369 // adding/deleting a format in FormPreferences (the latter calls can be
370 // eliminated if the formats in the Formats class are stored using a map or
371 // a list (instead of a vector), but this will cause other problems).
372 void Converters::update(Formats const & formats)
374 ConverterList::iterator it = converterlist_.begin();
375 ConverterList::iterator end = converterlist_.end();
376 for (; it != end; ++it) {
377 it->From = formats.getFormat(it->from);
378 it->To = formats.getFormat(it->to);
383 // This method updates the pointers From and To in the last converter.
384 // It is called when adding a new converter in FormPreferences
385 void Converters::updateLast(Formats const & formats)
387 if (converterlist_.begin() != converterlist_.end()) {
388 ConverterList::iterator it = converterlist_.end() - 1;
389 it->From = formats.getFormat(it->from);
390 it->To = formats.getFormat(it->to);
395 void Converters::sort()
397 std::sort(converterlist_.begin(), converterlist_.end());
401 int Converters::bfs_init(string const & start, bool clear_visited)
403 int const s = formats.getNumber(start);
409 fill(visited_.begin(), visited_.end(), false);
410 if (visited_[s] == false) {
418 vector<Format const *> const
419 Converters::getReachableTo(string const & target, bool clear_visited)
421 vector<Format const *> result;
422 int const s = bfs_init(target, clear_visited);
426 while (!Q_.empty()) {
427 int const i = Q_.front();
429 if (i != s || target != "lyx") {
430 result.push_back(&formats.get(i));
433 vector<int>::iterator it = vertices_[i].in_vertices.begin();
434 vector<int>::iterator end = vertices_[i].in_vertices.end();
435 for (; it != end; ++it) {
436 if (!visited_[*it]) {
437 visited_[*it] = true;
447 vector<Format const *> const
448 Converters::getReachable(string const & from, bool only_viewable,
451 vector<Format const *> result;
453 if (bfs_init(from, clear_visited) < 0)
456 while (!Q_.empty()) {
457 int const i = Q_.front();
459 Format const & format = formats.get(i);
460 if (format.name() == "lyx")
462 if (!only_viewable || !format.viewer().empty() ||
463 format.isChildFormat())
464 result.push_back(&format);
466 vector<int>::const_iterator cit =
467 vertices_[i].out_vertices.begin();
468 vector<int>::const_iterator end =
469 vertices_[i].out_vertices.end();
470 for (; cit != end; ++cit)
471 if (!visited_[*cit]) {
472 visited_[*cit] = true;
481 bool Converters::isReachable(string const & from, string const & to)
486 int const s = bfs_init(from);
487 int const t = formats.getNumber(to);
491 while (!Q_.empty()) {
492 int const i = Q_.front();
497 vector<int>::const_iterator cit =
498 vertices_[i].out_vertices.begin();
499 vector<int>::const_iterator end =
500 vertices_[i].out_vertices.end();
501 for (; cit != end; ++cit) {
502 if (!visited_[*cit]) {
503 visited_[*cit] = true;
513 Converters::EdgePath const
514 Converters::getPath(string const & from, string const & to)
520 int const s = bfs_init(from);
521 int t = formats.getNumber(to);
525 vector<int> prev_edge(formats.size());
526 vector<int> prev_vertex(formats.size());
529 while (!Q_.empty()) {
530 int const i = Q_.front();
537 vector<int>::const_iterator beg =
538 vertices_[i].out_vertices.begin();
539 vector<int>::const_iterator cit = beg;
540 vector<int>::const_iterator end =
541 vertices_[i].out_vertices.end();
542 for (; cit != end; ++cit)
543 if (!visited_[*cit]) {
547 int const k = cit - beg;
548 prev_edge[j] = vertices_[i].out_edges[k];
556 path.push_back(prev_edge[t]);
559 reverse(path.begin(), path.end());
564 bool Converters::usePdflatex(EdgePath const & path)
566 for (EdgePath::const_iterator cit = path.begin();
567 cit != path.end(); ++cit) {
568 Converter const & conv = converterlist_[*cit];
570 return contains(conv.to, "pdf");
576 bool Converters::convert(Buffer const * buffer,
577 string const & from_file, string const & to_file_base,
578 string const & from_format, string const & to_format,
581 to_file = ChangeExtension(to_file_base,
582 formats.extension(to_format));
584 if (from_format == to_format)
585 return move(from_file, to_file, false);
587 EdgePath edgepath = getPath(from_format, to_format);
588 if (edgepath.empty()) {
592 string path = OnlyPath(from_file);
595 bool run_latex = false;
596 string from_base = ChangeExtension(from_file, "");
597 string to_base = ChangeExtension(to_file, "");
599 string outfile = from_file;
600 for (EdgePath::const_iterator cit = edgepath.begin();
601 cit != edgepath.end(); ++cit) {
602 Converter const & conv = converterlist_[*cit];
603 bool dummy = conv.To->dummy() && conv.to != "program";
605 lyxerr[Debug::FILES] << "Converting from "
606 << conv.from << " to " << conv.to << endl;
608 outfile = conv.result_dir.empty()
609 ? ChangeExtension(from_file, conv.To->extension())
610 : AddName(subst(conv.result_dir,
611 token_base, from_base),
612 subst(conv.result_file,
613 token_base, OnlyFilename(from_base)));
617 string command = subst(conv.command, token_from, "");
618 lyxerr[Debug::FILES] << "Running " << command << endl;
619 if (!runLaTeX(buffer, command))
622 if (conv.need_aux && !run_latex
623 && !latex_command_.empty()) {
625 << "Running " << latex_command_
626 << " to update aux file"<< endl;
627 runLaTeX(buffer, latex_command_);
630 string const infile2 = (conv.original_dir)
631 ? infile : MakeRelPath(infile, path);
632 string const outfile2 = (conv.original_dir)
633 ? outfile : MakeRelPath(outfile, path);
634 string command = conv.command;
635 command = subst(command, token_from, QuoteName(infile2));
636 command = subst(command, token_base, QuoteName(from_base));
637 command = subst(command, token_to, QuoteName(outfile2));
638 command = subst(command, token_lib, system_lyxdir + "scripts");
640 if (!conv.parselog.empty())
641 command += " 2> " + QuoteName(infile2 + ".out");
643 if (conv.from == "dvi" && conv.to == "ps")
644 command = add_options(command,
645 dvips_options(buffer));
646 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
647 command = add_options(command,
648 dvipdfm_options(buffer));
650 lyxerr[Debug::FILES] << "Calling " << command << endl;
652 ShowMessage(buffer, _("Executing command:"), command);
654 Systemcall::Starttype type = (dummy)
655 ? Systemcall::DontWait : Systemcall::Wait;
658 if (conv.original_dir && buffer) {
659 Path p(buffer->filePath());
660 res = one.startscript(type, command);
662 res = one.startscript(type, command);
664 if (!conv.parselog.empty()) {
665 string const logfile = infile2 + ".log";
666 string const script = LibScriptSearch(conv.parselog);
667 string const command2 = script +
668 " < " + QuoteName(infile2 + ".out") +
669 " > " + QuoteName(logfile);
670 one.startscript(Systemcall::Wait, command2);
671 if (!scanLog(buffer, command, logfile))
676 if (conv.to == "program")
677 Alert::alert(_("There were errors during the Build process."),
678 _("You should try to fix them."));
680 Alert::alert(_("Cannot convert file"),
681 "Error while executing",
682 command.substr(0, 50));
688 Converter const & conv = converterlist_[edgepath.back()];
689 if (conv.To->dummy())
693 if (!conv.result_dir.empty()) {
694 to_file = AddName(subst(conv.result_dir, token_base, to_base),
695 subst(conv.result_file,
696 token_base, OnlyFilename(to_base)));
697 if (from_base != to_base) {
698 string from = subst(conv.result_dir,
699 token_base, from_base);
700 string to = subst(conv.result_dir,
701 token_base, to_base);
702 if (!lyx::rename(from, to)) {
703 Alert::alert(_("Error while trying to move directory:"),
710 return move(outfile, to_file, conv.latex);
713 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
714 // moves each /path/file*.ext file to /path2/file2*.ext2'
715 bool Converters::move(string const & from, string const & to, bool copy)
720 bool no_errors = true;
721 string const path = OnlyPath(from);
722 string const base = OnlyFilename(ChangeExtension(from, ""));
723 string const to_base = ChangeExtension(to, "");
724 string const to_extension = GetExtension(to);
726 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
727 for (vector<string>::const_iterator it = files.begin();
728 it != files.end(); ++it)
729 if (prefixIs(*it, base)) {
730 string const from2 = path + *it;
731 string to2 = to_base + it->substr(base.length());
732 to2 = ChangeExtension(to2, to_extension);
733 lyxerr[Debug::FILES] << "moving " << from2
734 << " to " << to2 << endl;
735 bool const moved = (copy)
736 ? lyx::copy(from2, to2)
737 : lyx::rename(from2, to2);
738 if (!moved && no_errors) {
739 Alert::alert(_("Error while trying to move file:"),
740 from2, _("to ") + to2);
748 bool Converters::convert(Buffer const * buffer,
749 string const & from_file, string const & to_file_base,
750 string const & from_format, string const & to_format)
753 return convert(buffer, from_file, to_file_base, from_format, to_format,
758 void Converters::buildGraph()
760 vertices_ = vector<Vertex>(formats.size());
761 visited_.resize(formats.size());
763 for (ConverterList::iterator it = converterlist_.begin();
764 it != converterlist_.end(); ++it) {
765 int const s = formats.getNumber(it->from);
766 int const t = formats.getNumber(it->to);
767 vertices_[t].in_vertices.push_back(s);
768 vertices_[s].out_vertices.push_back(t);
769 vertices_[s].out_edges.push_back(it - converterlist_.begin());
774 bool Converters::formatIsUsed(string const & format)
776 ConverterList::const_iterator cit = converterlist_.begin();
777 ConverterList::const_iterator end = converterlist_.end();
778 for (; cit != end; ++cit) {
779 if (cit->from == format || cit->to == format)
786 bool Converters::scanLog(Buffer const * buffer, string const & command,
787 string const & filename)
792 BufferView * bv = buffer->getUser();
794 bv->owner()->prohibitInput();
795 // all error insets should have been removed by now
798 LaTeX latex("", filename, "");
800 int result = latex.scanLogFile(terr);
802 if ((result & LaTeX::ERRORS)) {
803 // Insert all errors as errors boxes
804 bv->insertErrors(terr);
805 #warning repaint() or update() or nothing ?
809 bv->owner()->allowInput();
812 if ((result & LaTeX::ERRORS)) {
813 int num_errors = latex.getNumErrors();
816 if (num_errors == 1) {
817 s = _("One error detected");
818 t = _("You should try to fix it.");
820 s = tostr(num_errors);
821 s += _(" errors detected.");
822 t = _("You should try to fix them.");
825 split(command, head, ' ');
826 Alert::alert(_("There were errors during running of ") + head,
829 } else if (result & LaTeX::NO_OUTPUT) {
830 string const s = _("The operation resulted in");
831 string const t = _("an empty file.");
832 Alert::alert(_("Resulting file is empty"), s, t);
839 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
844 BufferView * bv = buffer->getUser();
847 bv->owner()->prohibitInput();
848 bv->owner()->message(_("Running LaTeX..."));
849 // all the autoinsets have already been removed
852 // do the LaTeX run(s)
853 string name = buffer->getLatexName();
854 LaTeX latex(command, name, buffer->filePath());
856 int result = latex.run(terr,
857 bv ? bv->owner()->getLyXFunc() : 0);
860 if ((result & LaTeX::ERRORS)) {
861 // Insert all errors as errors boxes
862 bv->insertErrors(terr);
863 #warning repaint() or update() or nothing ?
869 // check return value from latex.run().
870 if ((result & LaTeX::NO_LOGFILE)) {
871 Alert::alert(_("LaTeX did not work!"),
872 _("Missing log file:"), name);
873 } else if ((result & LaTeX::ERRORS)) {
874 int num_errors = latex.getNumErrors();
877 if (num_errors == 1) {
878 s = _("One error detected");
879 t = _("You should try to fix it.");
881 s = tostr(num_errors);
882 s += _(" errors detected.");
883 t = _("You should try to fix them.");
885 Alert::alert(_("There were errors during the LaTeX run."),
887 } else if (result & LaTeX::NO_OUTPUT) {
888 string const s = _("The operation resulted in");
889 string const t = _("an empty file.");
890 Alert::alert(_("Resulting file is empty"), s, t);
894 bv->owner()->allowInput();
896 int const ERROR_MASK =
901 return (result & ERROR_MASK) == 0;
906 string const Converters::papersize(Buffer const * buffer)
908 char real_papersize = buffer->params.papersize;
909 if (real_papersize == BufferParams::PAPER_DEFAULT)
910 real_papersize = lyxrc.default_papersize;
912 switch (real_papersize) {
913 case BufferParams::PAPER_A3PAPER:
915 case BufferParams::PAPER_A4PAPER:
917 case BufferParams::PAPER_A5PAPER:
919 case BufferParams::PAPER_B5PAPER:
921 case BufferParams::PAPER_EXECUTIVEPAPER:
923 case BufferParams::PAPER_LEGALPAPER:
925 case BufferParams::PAPER_USLETTER:
932 string const Converters::dvips_options(Buffer const * buffer)
938 if (buffer->params.use_geometry
939 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
940 && !lyxrc.print_paper_dimension_flag.empty()
941 && !buffer->params.paperwidth.empty()
942 && !buffer->params.paperheight.empty()) {
943 // using a custom papersize
944 result = lyxrc.print_paper_dimension_flag;
945 result += ' ' + buffer->params.paperwidth;
946 result += ',' + buffer->params.paperheight;
948 string const paper_option = papersize(buffer);
949 if (paper_option != "letter" ||
950 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
951 // dvips won't accept -t letter -t landscape. In all other
952 // cases, include the paper size explicitly.
953 result = lyxrc.print_paper_flag;
954 result += ' ' + paper_option;
957 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
958 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
959 result += ' ' + lyxrc.print_landscape_flag;
964 string const Converters::dvipdfm_options(Buffer const * buffer)
970 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
971 string const paper_size = papersize(buffer);
972 if (paper_size != "b5" && paper_size != "foolscap")
973 result = "-p "+ paper_size;
975 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
983 vector<Converters::Vertex> Converters::vertices_;
986 /// The global instance
988 Converters converters;
990 // The global copy after reading lyxrc.defaults
991 Formats system_formats;
992 Converters system_converters;