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
51 string const token_from("$$i");
52 string const token_base("$$b");
53 string const token_to("$$o");
55 //////////////////////////////////////////////////////////////////////////////
58 string const add_options(string const & command, string const & options)
61 string const tail = split(command, head, ' ');
62 return head + ' ' + options + ' ' + tail;
67 //////////////////////////////////////////////////////////////////////////////
69 bool Format::dummy() const
71 return extension().empty();
75 bool Format::isChildFormat() const
79 return isdigit(name_[name_.length() - 1]);
83 string const Format::parentFormat() const
85 return name_.substr(0, name_.length() - 1);
88 //////////////////////////////////////////////////////////////////////////////
90 // This method should return a reference, and throw an exception
91 // if the format named name cannot be found (Lgb)
92 Format const * Formats::getFormat(string const & name) const
94 FormatList::const_iterator cit =
95 find_if(formatlist.begin(), formatlist.end(),
96 lyx::compare_memfun(&Format::name, name));
97 if (cit != formatlist.end())
104 int Formats::getNumber(string const & name) const
106 FormatList::const_iterator cit =
107 find_if(formatlist.begin(), formatlist.end(),
108 lyx::compare_memfun(&Format::name, name));
109 if (cit != formatlist.end())
110 return cit - formatlist.begin();
116 void Formats::add(string const & name)
118 if (!getFormat(name))
119 add(name, name, name, string());
123 void Formats::add(string const & name, string const & extension,
124 string const & prettyname, string const & shortcut)
126 FormatList::iterator it =
127 find_if(formatlist.begin(), formatlist.end(),
128 lyx::compare_memfun(&Format::name, name));
129 if (it == formatlist.end())
130 formatlist.push_back(Format(name, extension, prettyname,
133 string viewer = it->viewer();
134 *it = Format(name, extension, prettyname, shortcut, viewer);
139 void Formats::erase(string const & name)
141 FormatList::iterator it =
142 find_if(formatlist.begin(), formatlist.end(),
143 lyx::compare_memfun(&Format::name, name));
144 if (it != formatlist.end())
145 formatlist.erase(it);
151 std::sort(formatlist.begin(), formatlist.end());
155 void Formats::setViewer(string const & name, string const & command)
158 FormatList::iterator it =
159 find_if(formatlist.begin(), formatlist.end(),
160 lyx::compare_memfun(&Format::name, name));
161 if (it != formatlist.end())
162 it->setViewer(command);
166 bool Formats::view(Buffer const * buffer, string const & filename,
167 string const & format_name) const
169 if (filename.empty())
172 Format const * format = getFormat(format_name);
173 if (format && format->viewer().empty() &&
174 format->isChildFormat())
175 format = getFormat(format->parentFormat());
176 if (!format || format->viewer().empty()) {
177 Alert::alert(_("Cannot view file"),
178 _("No information for viewing ")
179 + prettyName(format_name));
183 string command = format->viewer();
185 if (format_name == "dvi" &&
186 !lyxrc.view_dvi_paper_option.empty()) {
187 command += " " + lyxrc.view_dvi_paper_option;
188 string paper_size = converters.papersize(buffer);
189 if (paper_size == "letter")
191 command += " " + paper_size;
192 if (buffer->params.orientation
193 == BufferParams::ORIENTATION_LANDSCAPE)
197 command += " " + QuoteName(OnlyFilename((filename)));
199 lyxerr[Debug::FILES] << "Executing command: " << command << endl;
200 ShowMessage(buffer, _("Executing command:"), command);
202 Path p(OnlyPath(filename));
204 int const res = one.startscript(Systemcall::DontWait, command);
207 Alert::alert(_("Cannot view file"),
208 _("Error while executing"),
209 command.substr(0, 50));
216 string const Formats::prettyName(string const & name) const
218 Format const * format = getFormat(name);
220 return format->prettyname();
226 string const Formats::extension(string const & name) const
228 Format const * format = getFormat(name);
230 return format->extension();
235 //////////////////////////////////////////////////////////////////////////////
237 void Converter::readFlags()
239 string flag_list(flags);
240 while (!flag_list.empty()) {
241 string flag_name, flag_value;
242 flag_list = split(flag_list, flag_value, ',');
243 flag_value = split(flag_value, flag_name, '=');
244 if (flag_name == "latex")
246 else if (flag_name == "originaldir")
248 else if (flag_name == "needaux")
250 else if (flag_name == "resultdir")
251 result_dir = (flag_value.empty())
252 ? token_base : flag_value;
253 else if (flag_name == "resultfile")
254 result_file = flag_value;
255 else if (flag_name == "parselog")
256 parselog = flag_value;
258 if (!result_dir.empty() && result_file.empty())
259 result_file = "index." + formats.extension(to);
260 //if (!contains(command, token_from))
265 bool operator<(Converter const & a, Converter const & b)
267 int const i = compare_no_case(a.From->prettyname(),
268 b.From->prettyname());
270 return compare_no_case(a.To->prettyname(), b.To->prettyname())
276 //////////////////////////////////////////////////////////////////////////////
278 class compare_Converter {
280 compare_Converter(string const & f, string const & t)
282 bool operator()(Converter const & c) {
283 return c.from == from && c.to == to;
291 Converter const * Converters::getConverter(string const & from,
294 ConverterList::const_iterator cit =
295 find_if(converterlist_.begin(), converterlist_.end(),
296 compare_Converter(from, to));
297 if (cit != converterlist_.end())
304 int Converters::getNumber(string const & from, string const & to)
306 ConverterList::const_iterator cit =
307 find_if(converterlist_.begin(), converterlist_.end(),
308 compare_Converter(from, to));
309 if (cit != converterlist_.end())
310 return cit - converterlist_.begin();
316 void Converters::add(string const & from, string const & to,
317 string const & command, string const & flags)
321 ConverterList::iterator it = find_if(converterlist_.begin(),
322 converterlist_.end(),
323 compare_Converter(from, to));
325 Converter converter(from, to, command, flags);
326 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
328 converter.command = command;
329 converter.flags = flags;
331 converter.readFlags();
333 if (converter.latex && (latex_command_.empty() || to == "dvi"))
334 latex_command_ = subst(command, token_from, "");
335 // If we have both latex & pdflatex, we set latex_command to latex.
336 // The latex_command is used to update the .aux file when running
337 // a converter that uses it.
339 if (it == converterlist_.end()) {
340 converterlist_.push_back(converter);
342 converter.From = it->From;
343 converter.To = it->To;
349 void Converters::erase(string const & from, string const & to)
351 ConverterList::iterator it = find_if(converterlist_.begin(),
352 converterlist_.end(),
353 compare_Converter(from, to));
354 if (it != converterlist_.end())
355 converterlist_.erase(it);
359 // This method updates the pointers From and To in all the converters.
360 // The code is not very efficient, but it doesn't matter as the number
361 // of formats and converters is small.
362 // Furthermore, this method is called only on startup, or after
363 // adding/deleting a format in FormPreferences (the latter calls can be
364 // eliminated if the formats in the Formats class are stored using a map or
365 // a list (instead of a vector), but this will cause other problems).
366 void Converters::update(Formats const & formats)
368 ConverterList::iterator it = converterlist_.begin();
369 ConverterList::iterator end = converterlist_.end();
370 for (; it != end; ++it) {
371 it->From = formats.getFormat(it->from);
372 it->To = formats.getFormat(it->to);
377 // This method updates the pointers From and To in the last converter.
378 // It is called when adding a new converter in FormPreferences
379 void Converters::updateLast(Formats const & formats)
381 if (converterlist_.begin() != converterlist_.end()) {
382 ConverterList::iterator it = converterlist_.end() - 1;
383 it->From = formats.getFormat(it->from);
384 it->To = formats.getFormat(it->to);
389 void Converters::sort()
391 std::sort(converterlist_.begin(), converterlist_.end());
395 int Converters::bfs_init(string const & start, bool clear_visited)
397 int const s = formats.getNumber(start);
403 fill(visited_.begin(), visited_.end(), false);
404 if (visited_[s] == false) {
412 vector<Format const *> const
413 Converters::getReachableTo(string const & target, bool clear_visited)
415 vector<Format const *> result;
416 int const s = bfs_init(target, clear_visited);
420 while (!Q_.empty()) {
421 int const i = Q_.front();
423 if (i != s || target != "lyx") {
424 result.push_back(&formats.get(i));
427 vector<int>::iterator it = vertices_[i].in_vertices.begin();
428 vector<int>::iterator end = vertices_[i].in_vertices.end();
429 for (; it != end; ++it) {
430 if (!visited_[*it]) {
431 visited_[*it] = true;
441 vector<Format const *> const
442 Converters::getReachable(string const & from, bool only_viewable,
445 vector<Format const *> result;
447 if (bfs_init(from, clear_visited) < 0)
450 while (!Q_.empty()) {
451 int const i = Q_.front();
453 Format const & format = formats.get(i);
454 if (format.name() == "lyx")
456 if (!only_viewable || !format.viewer().empty() ||
457 format.isChildFormat())
458 result.push_back(&format);
460 vector<int>::const_iterator cit =
461 vertices_[i].out_vertices.begin();
462 vector<int>::const_iterator end =
463 vertices_[i].out_vertices.end();
464 for (; cit != end; ++cit)
465 if (!visited_[*cit]) {
466 visited_[*cit] = true;
475 bool Converters::isReachable(string const & from, string const & to)
480 int const s = bfs_init(from);
481 int const t = formats.getNumber(to);
485 while (!Q_.empty()) {
486 int const i = Q_.front();
491 vector<int>::const_iterator cit =
492 vertices_[i].out_vertices.begin();
493 vector<int>::const_iterator end =
494 vertices_[i].out_vertices.end();
495 for (; cit != end; ++cit) {
496 if (!visited_[*cit]) {
497 visited_[*cit] = true;
507 Converters::EdgePath const
508 Converters::getPath(string const & from, string const & to)
514 int const s = bfs_init(from);
515 int t = formats.getNumber(to);
519 vector<int> prev_edge(formats.size());
520 vector<int> prev_vertex(formats.size());
523 while (!Q_.empty()) {
524 int const i = Q_.front();
531 vector<int>::const_iterator beg =
532 vertices_[i].out_vertices.begin();
533 vector<int>::const_iterator cit = beg;
534 vector<int>::const_iterator end =
535 vertices_[i].out_vertices.end();
536 for (; cit != end; ++cit)
537 if (!visited_[*cit]) {
541 int const k = cit - beg;
542 prev_edge[j] = vertices_[i].out_edges[k];
550 path.push_back(prev_edge[t]);
553 reverse(path.begin(), path.end());
558 bool Converters::usePdflatex(EdgePath const & path)
560 for (EdgePath::const_iterator cit = path.begin();
561 cit != path.end(); ++cit) {
562 Converter const & conv = converterlist_[*cit];
564 return contains(conv.to, "pdf");
570 bool Converters::convert(Buffer const * buffer,
571 string const & from_file, string const & to_file_base,
572 string const & from_format, string const & to_format,
575 to_file = ChangeExtension(to_file_base,
576 formats.extension(to_format));
578 if (from_format == to_format)
579 return move(from_file, to_file, false);
581 EdgePath edgepath = getPath(from_format, to_format);
582 if (edgepath.empty()) {
586 string path = OnlyPath(from_file);
589 bool run_latex = false;
590 string from_base = ChangeExtension(from_file, "");
591 string to_base = ChangeExtension(to_file, "");
593 string outfile = from_file;
594 for (EdgePath::const_iterator cit = edgepath.begin();
595 cit != edgepath.end(); ++cit) {
596 Converter const & conv = converterlist_[*cit];
597 bool dummy = conv.To->dummy() && conv.to != "program";
599 lyxerr[Debug::FILES] << "Converting from "
600 << conv.from << " to " << conv.to << endl;
602 outfile = conv.result_dir.empty()
603 ? ChangeExtension(from_file, conv.To->extension())
604 : AddName(subst(conv.result_dir,
605 token_base, from_base),
606 subst(conv.result_file,
607 token_base, OnlyFilename(from_base)));
611 string command = subst(conv.command, token_from, "");
612 lyxerr[Debug::FILES] << "Running " << command << endl;
613 if (!runLaTeX(buffer, command))
616 if (conv.need_aux && !run_latex
617 && !latex_command_.empty()) {
619 << "Running " << latex_command_
620 << " to update aux file"<< endl;
621 runLaTeX(buffer, latex_command_);
624 string infile2 = (conv.original_dir)
625 ? infile : MakeRelPath(infile, path);
626 string outfile2 = (conv.original_dir)
627 ? outfile : MakeRelPath(outfile, path);
629 string command = conv.command;
630 command = subst(command, token_from, QuoteName(infile2));
631 command = subst(command, token_base, QuoteName(from_base));
632 command = subst(command, token_to, QuoteName(outfile2));
634 if (!conv.parselog.empty())
635 command += " 2> " + QuoteName(infile2 + ".out");
637 if (conv.from == "dvi" && conv.to == "ps")
638 command = add_options(command,
639 dvips_options(buffer));
640 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
641 command = add_options(command,
642 dvipdfm_options(buffer));
644 lyxerr[Debug::FILES] << "Calling " << command << endl;
646 ShowMessage(buffer, _("Executing command:"), command);
648 Systemcall::Starttype type = (dummy)
649 ? Systemcall::DontWait : Systemcall::Wait;
652 if (conv.original_dir && buffer) {
653 Path p(buffer->filePath());
654 res = one.startscript(type, command);
656 res = one.startscript(type, command);
658 if (!conv.parselog.empty()) {
659 string const logfile = infile2 + ".log";
660 string const script = LibScriptSearch(conv.parselog);
661 string const command2 = script +
662 " < " + QuoteName(infile2 + ".out") +
663 " > " + QuoteName(logfile);
664 one.startscript(Systemcall::Wait, command2);
665 if (!scanLog(buffer, command, logfile))
670 if (conv.to == "program")
671 Alert::alert(_("There were errors during the Build process."),
672 _("You should try to fix them."));
674 Alert::alert(_("Cannot convert file"),
675 "Error while executing",
676 command.substr(0, 50));
682 Converter const & conv = converterlist_[edgepath.back()];
683 if (conv.To->dummy())
687 if (!conv.result_dir.empty()) {
688 to_file = AddName(subst(conv.result_dir, token_base, to_base),
689 subst(conv.result_file,
690 token_base, OnlyFilename(to_base)));
691 if (from_base != to_base) {
692 string from = subst(conv.result_dir,
693 token_base, from_base);
694 string to = subst(conv.result_dir,
695 token_base, to_base);
696 if (!lyx::rename(from, to)) {
697 Alert::alert(_("Error while trying to move directory:"),
704 return move(outfile, to_file, conv.latex);
707 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
708 // moves each /path/file*.ext file to /path2/file2*.ext2'
709 bool Converters::move(string const & from, string const & to, bool copy)
714 bool no_errors = true;
715 string const path = OnlyPath(from);
716 string const base = OnlyFilename(ChangeExtension(from, ""));
717 string const to_base = ChangeExtension(to, "");
718 string const to_extension = GetExtension(to);
720 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
721 for (vector<string>::const_iterator it = files.begin();
722 it != files.end(); ++it)
723 if (prefixIs(*it, base)) {
724 string const from2 = path + *it;
725 string to2 = to_base + it->substr(base.length());
726 to2 = ChangeExtension(to2, to_extension);
727 lyxerr[Debug::FILES] << "moving " << from2
728 << " to " << to2 << endl;
729 bool const moved = (copy)
730 ? lyx::copy(from2, to2)
731 : lyx::rename(from2, to2);
732 if (!moved && no_errors) {
733 Alert::alert(_("Error while trying to move file:"),
734 from2, _("to ") + to2);
742 bool Converters::convert(Buffer const * buffer,
743 string const & from_file, string const & to_file_base,
744 string const & from_format, string const & to_format)
747 return convert(buffer, from_file, to_file_base, from_format, to_format,
752 void Converters::buildGraph()
754 vertices_ = vector<Vertex>(formats.size());
755 visited_.resize(formats.size());
757 for (ConverterList::iterator it = converterlist_.begin();
758 it != converterlist_.end(); ++it) {
759 int const s = formats.getNumber(it->from);
760 int const t = formats.getNumber(it->to);
761 vertices_[t].in_vertices.push_back(s);
762 vertices_[s].out_vertices.push_back(t);
763 vertices_[s].out_edges.push_back(it - converterlist_.begin());
768 bool Converters::formatIsUsed(string const & format)
770 ConverterList::const_iterator cit = converterlist_.begin();
771 ConverterList::const_iterator end = converterlist_.end();
772 for (; cit != end; ++cit) {
773 if (cit->from == format || cit->to == format)
780 bool Converters::scanLog(Buffer const * buffer, string const & command,
781 string const & filename)
786 BufferView * bv = buffer->getUser();
788 bv->owner()->prohibitInput();
789 // all error insets should have been removed by now
792 LaTeX latex("", filename, "");
794 int result = latex.scanLogFile(terr);
796 if ((result & LaTeX::ERRORS)) {
797 // Insert all errors as errors boxes
798 bv->insertErrors(terr);
799 #warning repaint() or update() or nothing ?
803 bv->owner()->allowInput();
806 if ((result & LaTeX::ERRORS)) {
807 int num_errors = latex.getNumErrors();
810 if (num_errors == 1) {
811 s = _("One error detected");
812 t = _("You should try to fix it.");
814 s = tostr(num_errors);
815 s += _(" errors detected.");
816 t = _("You should try to fix them.");
819 split(command, head, ' ');
820 Alert::alert(_("There were errors during running of ") + head,
823 } else if (result & LaTeX::NO_OUTPUT) {
824 string const s = _("The operation resulted in");
825 string const t = _("an empty file.");
826 Alert::alert(_("Resulting file is empty"), s, t);
833 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
838 BufferView * bv = buffer->getUser();
841 bv->owner()->prohibitInput();
842 bv->owner()->message(_("Running LaTeX..."));
843 // all the autoinsets have already been removed
846 // do the LaTeX run(s)
847 string name = buffer->getLatexName();
848 LaTeX latex(command, name, buffer->filePath());
850 int result = latex.run(terr,
851 bv ? bv->owner()->getLyXFunc() : 0);
854 if ((result & LaTeX::ERRORS)) {
855 // Insert all errors as errors boxes
856 bv->insertErrors(terr);
857 #warning repaint() or update() or nothing ?
863 // check return value from latex.run().
864 if ((result & LaTeX::NO_LOGFILE)) {
865 Alert::alert(_("LaTeX did not work!"),
866 _("Missing log file:"), name);
867 } else if ((result & LaTeX::ERRORS)) {
868 int num_errors = latex.getNumErrors();
871 if (num_errors == 1) {
872 s = _("One error detected");
873 t = _("You should try to fix it.");
875 s = tostr(num_errors);
876 s += _(" errors detected.");
877 t = _("You should try to fix them.");
879 Alert::alert(_("There were errors during the LaTeX run."),
881 } else if (result & LaTeX::NO_OUTPUT) {
882 string const s = _("The operation resulted in");
883 string const t = _("an empty file.");
884 Alert::alert(_("Resulting file is empty"), s, t);
888 bv->owner()->allowInput();
890 int const ERROR_MASK =
895 return (result & ERROR_MASK) == 0;
900 string const Converters::papersize(Buffer const * buffer)
902 char real_papersize = buffer->params.papersize;
903 if (real_papersize == BufferParams::PAPER_DEFAULT)
904 real_papersize = lyxrc.default_papersize;
906 switch (real_papersize) {
907 case BufferParams::PAPER_A3PAPER:
909 case BufferParams::PAPER_A4PAPER:
911 case BufferParams::PAPER_A5PAPER:
913 case BufferParams::PAPER_B5PAPER:
915 case BufferParams::PAPER_EXECUTIVEPAPER:
917 case BufferParams::PAPER_LEGALPAPER:
919 case BufferParams::PAPER_USLETTER:
926 string const Converters::dvips_options(Buffer const * buffer)
932 if (buffer->params.use_geometry
933 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
934 && !lyxrc.print_paper_dimension_flag.empty()
935 && !buffer->params.paperwidth.empty()
936 && !buffer->params.paperheight.empty()) {
937 // using a custom papersize
938 result = lyxrc.print_paper_dimension_flag;
939 result += ' ' + buffer->params.paperwidth;
940 result += ',' + buffer->params.paperheight;
942 string const paper_option = papersize(buffer);
943 if (paper_option != "letter" ||
944 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
945 // dvips won't accept -t letter -t landscape. In all other
946 // cases, include the paper size explicitly.
947 result = lyxrc.print_paper_flag;
948 result += ' ' + paper_option;
951 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
952 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
953 result += ' ' + lyxrc.print_landscape_flag;
958 string const Converters::dvipdfm_options(Buffer const * buffer)
964 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
965 string const paper_size = papersize(buffer);
966 if (paper_size != "b5" && paper_size != "foolscap")
967 result = "-p "+ paper_size;
969 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
977 vector<Converters::Vertex> Converters::vertices_;
980 /// The global instance
982 Converters converters;
984 // The global copy after reading lyxrc.defaults
985 Formats system_formats;
986 Converters system_converters;