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
17 #include "converter.h"
20 #include "bufferview_funcs.h"
22 #include "lyx_cb.h" // ShowMessage()
24 #include "BufferView.h"
27 #include "frontends/Alert.h"
28 #include "frontends/LyXView.h"
30 #include "support/filetools.h"
31 #include "support/lyxfunctional.h"
32 #include "support/path.h"
33 #include "support/systemcall.h"
35 #include "BoostFormat.h"
39 #ifndef CXX_GLOBAL_CSTD
53 string const token_from("$$i");
54 string const token_base("$$b");
55 string const token_to("$$o");
56 string const token_path("$$p");
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()) {
181 Alert::alert(_("Cannot view file"),
182 boost::io::str(boost::format(_("No information for viewing %1$s"))
183 % prettyName(format_name)));
185 Alert::alert(_("Cannot view file"),
186 _("No information for viewing ")
187 + prettyName(format_name));
192 string command = format->viewer();
194 if (format_name == "dvi" &&
195 !lyxrc.view_dvi_paper_option.empty()) {
196 command += " " + lyxrc.view_dvi_paper_option;
197 string paper_size = converters.papersize(buffer);
198 if (paper_size == "letter")
200 command += " " + paper_size;
201 if (buffer->params.orientation
202 == BufferParams::ORIENTATION_LANDSCAPE)
206 if (!contains(command, token_from))
207 command += " " + token_from;
209 command = subst(command, token_from,
210 QuoteName(OnlyFilename(filename)));
211 command = subst(command, token_path, QuoteName(OnlyPath(filename)));
213 lyxerr[Debug::FILES] << "Executing command: " << command << endl;
214 ShowMessage(buffer, _("Executing command:"), command);
216 Path p(OnlyPath(filename));
218 int const res = one.startscript(Systemcall::DontWait, command);
221 Alert::alert(_("Cannot view file"),
222 _("Error while executing"),
223 command.substr(0, 50));
230 string const Formats::prettyName(string const & name) const
232 Format const * format = getFormat(name);
234 return format->prettyname();
240 string const Formats::extension(string const & name) const
242 Format const * format = getFormat(name);
244 return format->extension();
249 //////////////////////////////////////////////////////////////////////////////
251 void Converter::readFlags()
253 string flag_list(flags);
254 while (!flag_list.empty()) {
255 string flag_name, flag_value;
256 flag_list = split(flag_list, flag_value, ',');
257 flag_value = split(flag_value, flag_name, '=');
258 if (flag_name == "latex")
260 else if (flag_name == "originaldir")
262 else if (flag_name == "needaux")
264 else if (flag_name == "resultdir")
265 result_dir = (flag_value.empty())
266 ? token_base : flag_value;
267 else if (flag_name == "resultfile")
268 result_file = flag_value;
269 else if (flag_name == "parselog")
270 parselog = flag_value;
272 if (!result_dir.empty() && result_file.empty())
273 result_file = "index." + formats.extension(to);
274 //if (!contains(command, token_from))
279 bool operator<(Converter const & a, Converter const & b)
281 // use the compare_ascii_no_case instead of compare_no_case,
282 // because in turkish, 'i' is not the lowercase version of 'I',
283 // and thus turkish locale breaks parsing of tags.
284 int const i = compare_ascii_no_case(a.From->prettyname(),
285 b.From->prettyname());
287 return compare_ascii_no_case(a.To->prettyname(), b.To->prettyname())
293 //////////////////////////////////////////////////////////////////////////////
295 class compare_Converter {
297 compare_Converter(string const & f, string const & t)
299 bool operator()(Converter const & c) {
300 return c.from == from && c.to == to;
308 Converter const * Converters::getConverter(string const & from,
311 ConverterList::const_iterator cit =
312 find_if(converterlist_.begin(), converterlist_.end(),
313 compare_Converter(from, to));
314 if (cit != converterlist_.end())
321 int Converters::getNumber(string const & from, string const & to)
323 ConverterList::const_iterator cit =
324 find_if(converterlist_.begin(), converterlist_.end(),
325 compare_Converter(from, to));
326 if (cit != converterlist_.end())
327 return cit - converterlist_.begin();
333 void Converters::add(string const & from, string const & to,
334 string const & command, string const & flags)
338 ConverterList::iterator it = find_if(converterlist_.begin(),
339 converterlist_.end(),
340 compare_Converter(from, to));
342 Converter converter(from, to, command, flags);
343 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
345 converter.command = command;
346 converter.flags = flags;
348 converter.readFlags();
350 if (converter.latex && (latex_command_.empty() || to == "dvi"))
351 latex_command_ = subst(command, token_from, "");
352 // If we have both latex & pdflatex, we set latex_command to latex.
353 // The latex_command is used to update the .aux file when running
354 // a converter that uses it.
356 if (it == converterlist_.end()) {
357 converterlist_.push_back(converter);
359 converter.From = it->From;
360 converter.To = it->To;
366 void Converters::erase(string const & from, string const & to)
368 ConverterList::iterator it = find_if(converterlist_.begin(),
369 converterlist_.end(),
370 compare_Converter(from, to));
371 if (it != converterlist_.end())
372 converterlist_.erase(it);
376 // This method updates the pointers From and To in all the converters.
377 // The code is not very efficient, but it doesn't matter as the number
378 // of formats and converters is small.
379 // Furthermore, this method is called only on startup, or after
380 // adding/deleting a format in FormPreferences (the latter calls can be
381 // eliminated if the formats in the Formats class are stored using a map or
382 // a list (instead of a vector), but this will cause other problems).
383 void Converters::update(Formats const & formats)
385 ConverterList::iterator it = converterlist_.begin();
386 ConverterList::iterator end = converterlist_.end();
387 for (; it != end; ++it) {
388 it->From = formats.getFormat(it->from);
389 it->To = formats.getFormat(it->to);
394 // This method updates the pointers From and To in the last converter.
395 // It is called when adding a new converter in FormPreferences
396 void Converters::updateLast(Formats const & formats)
398 if (converterlist_.begin() != converterlist_.end()) {
399 ConverterList::iterator it = converterlist_.end() - 1;
400 it->From = formats.getFormat(it->from);
401 it->To = formats.getFormat(it->to);
406 void Converters::sort()
408 std::sort(converterlist_.begin(), converterlist_.end());
412 int Converters::bfs_init(string const & start, bool clear_visited)
414 int const s = formats.getNumber(start);
420 fill(visited_.begin(), visited_.end(), false);
421 if (visited_[s] == false) {
429 vector<Format const *> const
430 Converters::getReachableTo(string const & target, bool clear_visited)
432 vector<Format const *> result;
433 int const s = bfs_init(target, clear_visited);
437 while (!Q_.empty()) {
438 int const i = Q_.front();
440 if (i != s || target != "lyx") {
441 result.push_back(&formats.get(i));
444 vector<int>::iterator it = vertices_[i].in_vertices.begin();
445 vector<int>::iterator end = vertices_[i].in_vertices.end();
446 for (; it != end; ++it) {
447 if (!visited_[*it]) {
448 visited_[*it] = true;
458 vector<Format const *> const
459 Converters::getReachable(string const & from, bool only_viewable,
462 vector<Format const *> result;
464 if (bfs_init(from, clear_visited) < 0)
467 while (!Q_.empty()) {
468 int const i = Q_.front();
470 Format const & format = formats.get(i);
471 if (format.name() == "lyx")
473 if (!only_viewable || !format.viewer().empty() ||
474 format.isChildFormat())
475 result.push_back(&format);
477 vector<int>::const_iterator cit =
478 vertices_[i].out_vertices.begin();
479 vector<int>::const_iterator end =
480 vertices_[i].out_vertices.end();
481 for (; cit != end; ++cit)
482 if (!visited_[*cit]) {
483 visited_[*cit] = true;
492 bool Converters::isReachable(string const & from, string const & to)
497 int const s = bfs_init(from);
498 int const t = formats.getNumber(to);
502 while (!Q_.empty()) {
503 int const i = Q_.front();
508 vector<int>::const_iterator cit =
509 vertices_[i].out_vertices.begin();
510 vector<int>::const_iterator end =
511 vertices_[i].out_vertices.end();
512 for (; cit != end; ++cit) {
513 if (!visited_[*cit]) {
514 visited_[*cit] = true;
524 Converters::EdgePath const
525 Converters::getPath(string const & from, string const & to)
531 int const s = bfs_init(from);
532 int t = formats.getNumber(to);
536 vector<int> prev_edge(formats.size());
537 vector<int> prev_vertex(formats.size());
540 while (!Q_.empty()) {
541 int const i = Q_.front();
548 vector<int>::const_iterator beg =
549 vertices_[i].out_vertices.begin();
550 vector<int>::const_iterator cit = beg;
551 vector<int>::const_iterator end =
552 vertices_[i].out_vertices.end();
553 for (; cit != end; ++cit)
554 if (!visited_[*cit]) {
558 int const k = cit - beg;
559 prev_edge[j] = vertices_[i].out_edges[k];
567 path.push_back(prev_edge[t]);
570 reverse(path.begin(), path.end());
575 bool Converters::usePdflatex(EdgePath const & path)
577 for (EdgePath::const_iterator cit = path.begin();
578 cit != path.end(); ++cit) {
579 Converter const & conv = converterlist_[*cit];
581 return contains(conv.to, "pdf");
587 bool Converters::convert(Buffer const * buffer,
588 string const & from_file, string const & to_file_base,
589 string const & from_format, string const & to_format,
592 to_file = ChangeExtension(to_file_base,
593 formats.extension(to_format));
595 if (from_format == to_format)
596 return move(from_file, to_file, false);
598 EdgePath edgepath = getPath(from_format, to_format);
599 if (edgepath.empty()) {
603 string path = OnlyPath(from_file);
606 bool run_latex = false;
607 string from_base = ChangeExtension(from_file, "");
608 string to_base = ChangeExtension(to_file, "");
610 string outfile = from_file;
611 for (EdgePath::const_iterator cit = edgepath.begin();
612 cit != edgepath.end(); ++cit) {
613 Converter const & conv = converterlist_[*cit];
614 bool dummy = conv.To->dummy() && conv.to != "program";
616 lyxerr[Debug::FILES] << "Converting from "
617 << conv.from << " to " << conv.to << endl;
619 outfile = conv.result_dir.empty()
620 ? ChangeExtension(from_file, conv.To->extension())
621 : AddName(subst(conv.result_dir,
622 token_base, from_base),
623 subst(conv.result_file,
624 token_base, OnlyFilename(from_base)));
628 string command = subst(conv.command, token_from, "");
629 lyxerr[Debug::FILES] << "Running " << command << endl;
630 if (!runLaTeX(buffer, command))
633 if (conv.need_aux && !run_latex
634 && !latex_command_.empty()) {
636 << "Running " << latex_command_
637 << " to update aux file"<< endl;
638 runLaTeX(buffer, latex_command_);
641 string infile2 = (conv.original_dir)
642 ? infile : MakeRelPath(infile, path);
643 string outfile2 = (conv.original_dir)
644 ? outfile : MakeRelPath(outfile, path);
646 string command = conv.command;
647 command = subst(command, token_from, QuoteName(infile2));
648 command = subst(command, token_base, QuoteName(from_base));
649 command = subst(command, token_to, QuoteName(outfile2));
650 command = LibScriptSearch(command);
652 if (!conv.parselog.empty())
653 command += " 2> " + QuoteName(infile2 + ".out");
655 if (conv.from == "dvi" && conv.to == "ps")
656 command = add_options(command,
657 dvips_options(buffer));
658 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
659 command = add_options(command,
660 dvipdfm_options(buffer));
662 lyxerr[Debug::FILES] << "Calling " << command << endl;
664 ShowMessage(buffer, _("Executing command:"), command);
666 Systemcall::Starttype type = (dummy)
667 ? Systemcall::DontWait : Systemcall::Wait;
670 if (conv.original_dir && buffer) {
671 Path p(buffer->filePath());
672 res = one.startscript(type, command);
674 res = one.startscript(type, command);
676 if (!conv.parselog.empty()) {
677 string const logfile = infile2 + ".log";
678 string const script = LibScriptSearch(conv.parselog);
679 string const command2 = script +
680 " < " + QuoteName(infile2 + ".out") +
681 " > " + QuoteName(logfile);
682 one.startscript(Systemcall::Wait, command2);
683 if (!scanLog(buffer, command, logfile))
688 if (conv.to == "program")
689 Alert::alert(_("There were errors during the Build process."),
690 _("You should try to fix them."));
692 Alert::alert(_("Cannot convert file"),
693 _("Error while executing"),
694 command.substr(0, 50));
700 Converter const & conv = converterlist_[edgepath.back()];
701 if (conv.To->dummy())
705 if (!conv.result_dir.empty()) {
706 to_file = AddName(subst(conv.result_dir, token_base, to_base),
707 subst(conv.result_file,
708 token_base, OnlyFilename(to_base)));
709 if (from_base != to_base) {
710 string from = subst(conv.result_dir,
711 token_base, from_base);
712 string to = subst(conv.result_dir,
713 token_base, to_base);
714 if (!lyx::rename(from, to)) {
716 Alert::alert(_("Error while trying to move directory:"),
717 from, boost::io::str(boost::format(_("to %1$s")) % to));
719 Alert::alert(_("Error while trying to move directory:"),
720 from, _("to ") + to);
727 return move(outfile, to_file, conv.latex);
731 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
732 // moves each /path/file*.ext file to /path2/file2*.ext2'
733 bool Converters::move(string const & from, string const & to, bool copy)
738 bool no_errors = true;
739 string const path = OnlyPath(from);
740 string const base = OnlyFilename(ChangeExtension(from, ""));
741 string const to_base = ChangeExtension(to, "");
742 string const to_extension = GetExtension(to);
744 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
745 for (vector<string>::const_iterator it = files.begin();
746 it != files.end(); ++it)
747 if (prefixIs(*it, base)) {
748 string const from2 = path + *it;
749 string to2 = to_base + it->substr(base.length());
750 to2 = ChangeExtension(to2, to_extension);
751 lyxerr[Debug::FILES] << "moving " << from2
752 << " to " << to2 << endl;
753 bool const moved = (copy)
754 ? lyx::copy(from2, to2)
755 : lyx::rename(from2, to2);
756 if (!moved && no_errors) {
758 Alert::alert(_("Error while trying to move file:"),
759 from2, boost::io::str(boost::format(_("to %1$s")) % to2));
761 Alert::alert(_("Error while trying to move file:"),
762 from2, _("to ") + to2);
771 bool Converters::convert(Buffer const * buffer,
772 string const & from_file, string const & to_file_base,
773 string const & from_format, string const & to_format)
776 return convert(buffer, from_file, to_file_base, from_format, to_format,
781 void Converters::buildGraph()
783 vertices_ = vector<Vertex>(formats.size());
784 visited_.resize(formats.size());
786 for (ConverterList::iterator it = converterlist_.begin();
787 it != converterlist_.end(); ++it) {
788 int const s = formats.getNumber(it->from);
789 int const t = formats.getNumber(it->to);
790 vertices_[t].in_vertices.push_back(s);
791 vertices_[s].out_vertices.push_back(t);
792 vertices_[s].out_edges.push_back(it - converterlist_.begin());
797 bool Converters::formatIsUsed(string const & format)
799 ConverterList::const_iterator cit = converterlist_.begin();
800 ConverterList::const_iterator end = converterlist_.end();
801 for (; cit != end; ++cit) {
802 if (cit->from == format || cit->to == format)
809 bool Converters::scanLog(Buffer const * buffer, string const & command,
810 string const & filename)
815 BufferView * bv = buffer->getUser();
817 bv->owner()->prohibitInput();
818 // all error insets should have been removed by now
821 LaTeX latex("", filename, "");
823 int result = latex.scanLogFile(terr);
825 if ((result & LaTeX::ERRORS)) {
826 // Insert all errors as errors boxes
827 bv->insertErrors(terr);
828 #warning repaint() or update() or nothing ?
832 bv->owner()->allowInput();
835 if ((result & LaTeX::ERRORS)) {
836 int num_errors = latex.getNumErrors();
839 if (num_errors == 1) {
840 s = _("One error detected");
841 t = _("You should try to fix it.");
843 s = tostr(num_errors);
844 s += _(" errors detected.");
845 t = _("You should try to fix them.");
848 split(command, head, ' ');
850 Alert::alert(boost::io::str(boost::format(_("There were errors during running of %1$s")) % head),
853 Alert::alert(_("There were errors during running of ") + head,
857 } else if (result & LaTeX::NO_OUTPUT) {
858 string const s = _("The operation resulted in");
859 string const t = _("an empty file.");
860 Alert::alert(_("Resulting file is empty"), s, t);
867 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
872 BufferView * bv = buffer->getUser();
875 bv->owner()->prohibitInput();
876 bv->owner()->message(_("Running LaTeX..."));
877 // all the autoinsets have already been removed
880 // do the LaTeX run(s)
881 string name = buffer->getLatexName();
882 LaTeX latex(command, name, buffer->filePath());
884 int result = latex.run(terr,
885 bv ? &bv->owner()->getLyXFunc() : 0);
888 if ((result & LaTeX::ERRORS)) {
889 // Insert all errors as errors boxes
890 bv->insertErrors(terr);
891 #warning repaint() or update() or nothing ?
897 // check return value from latex.run().
898 if ((result & LaTeX::NO_LOGFILE)) {
899 Alert::alert(_("LaTeX did not work!"),
900 _("Missing log file:"), name);
901 } else if ((result & LaTeX::ERRORS)) {
902 int num_errors = latex.getNumErrors();
905 if (num_errors == 1) {
906 s = _("One error detected");
907 t = _("You should try to fix it.");
909 s = tostr(num_errors);
910 s += _(" errors detected.");
911 t = _("You should try to fix them.");
913 Alert::alert(_("There were errors during the LaTeX run."),
915 } else if (result & LaTeX::NO_OUTPUT) {
916 string const s = _("The operation resulted in");
917 string const t = _("an empty file.");
918 Alert::alert(_("Resulting file is empty"), s, t);
922 bv->owner()->allowInput();
924 int const ERROR_MASK =
929 return (result & ERROR_MASK) == 0;
934 string const Converters::papersize(Buffer const * buffer)
936 char real_papersize = buffer->params.papersize;
937 if (real_papersize == BufferParams::PAPER_DEFAULT)
938 real_papersize = lyxrc.default_papersize;
940 switch (real_papersize) {
941 case BufferParams::PAPER_A3PAPER:
943 case BufferParams::PAPER_A4PAPER:
945 case BufferParams::PAPER_A5PAPER:
947 case BufferParams::PAPER_B5PAPER:
949 case BufferParams::PAPER_EXECUTIVEPAPER:
951 case BufferParams::PAPER_LEGALPAPER:
953 case BufferParams::PAPER_USLETTER:
960 string const Converters::dvips_options(Buffer const * buffer)
966 if (buffer->params.use_geometry
967 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
968 && !lyxrc.print_paper_dimension_flag.empty()
969 && !buffer->params.paperwidth.empty()
970 && !buffer->params.paperheight.empty()) {
971 // using a custom papersize
972 result = lyxrc.print_paper_dimension_flag;
973 result += ' ' + buffer->params.paperwidth;
974 result += ',' + buffer->params.paperheight;
976 string const paper_option = papersize(buffer);
977 if (paper_option != "letter" ||
978 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
979 // dvips won't accept -t letter -t landscape. In all other
980 // cases, include the paper size explicitly.
981 result = lyxrc.print_paper_flag;
982 result += ' ' + paper_option;
985 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
986 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
987 result += ' ' + lyxrc.print_landscape_flag;
992 string const Converters::dvipdfm_options(Buffer const * buffer)
998 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
999 string const paper_size = papersize(buffer);
1000 if (paper_size != "b5" && paper_size != "foolscap")
1001 result = "-p "+ paper_size;
1003 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1011 vector<Converters::Vertex> Converters::vertices_;
1014 /// The global instance
1016 Converters converters;
1018 // The global copy after reading lyxrc.defaults
1019 Formats system_formats;
1020 Converters system_converters;