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"
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"
47 string const token_from("$$i");
48 string const token_base("$$b");
49 string const token_to("$$o");
51 //////////////////////////////////////////////////////////////////////////////
54 string const add_options(string const & command, string const & options)
57 string const tail = split(command, head, ' ');
58 return head + ' ' + options + ' ' + tail;
63 //////////////////////////////////////////////////////////////////////////////
65 bool Format::dummy() const
67 return extension().empty();
71 bool Format::isChildFormat() const
75 return isdigit(name_[name_.length() - 1]);
79 string const Format::parentFormat() const
81 return name_.substr(0, name_.length() - 1);
84 //////////////////////////////////////////////////////////////////////////////
86 // This method should return a reference, and throw an exception
87 // if the format named name cannot be found (Lgb)
88 Format const * Formats::getFormat(string const & name) const
90 FormatList::const_iterator cit =
91 find_if(formatlist.begin(), formatlist.end(),
92 lyx::compare_memfun(&Format::name, name));
93 if (cit != formatlist.end())
100 int Formats::getNumber(string const & name) const
102 FormatList::const_iterator cit =
103 find_if(formatlist.begin(), formatlist.end(),
104 lyx::compare_memfun(&Format::name, name));
105 if (cit != formatlist.end())
106 return cit - formatlist.begin();
112 void Formats::add(string const & name)
114 if (!getFormat(name))
115 add(name, name, name, string());
119 void Formats::add(string const & name, string const & extension,
120 string const & prettyname, string const & shortcut)
122 FormatList::iterator it =
123 find_if(formatlist.begin(), formatlist.end(),
124 lyx::compare_memfun(&Format::name, name));
125 if (it == formatlist.end())
126 formatlist.push_back(Format(name, extension, prettyname,
129 string viewer = it->viewer();
130 *it = Format(name, extension, prettyname, shortcut, viewer);
135 void Formats::erase(string const & name)
137 FormatList::iterator it =
138 find_if(formatlist.begin(), formatlist.end(),
139 lyx::compare_memfun(&Format::name, name));
140 if (it != formatlist.end())
141 formatlist.erase(it);
147 std::sort(formatlist.begin(), formatlist.end());
151 void Formats::setViewer(string const & name, string const & command)
154 FormatList::iterator it =
155 find_if(formatlist.begin(), formatlist.end(),
156 lyx::compare_memfun(&Format::name, name));
157 if (it != formatlist.end())
158 it->setViewer(command);
162 bool Formats::view(Buffer const * buffer, string const & filename,
163 string const & format_name) const
165 if (filename.empty())
168 Format const * format = getFormat(format_name);
169 if (format && format->viewer().empty() &&
170 format->isChildFormat())
171 format = getFormat(format->parentFormat());
172 if (!format || format->viewer().empty()) {
173 Alert::alert(_("Cannot view file"),
174 _("No information for viewing ")
175 + prettyName(format_name));
179 string command = format->viewer();
181 if (format_name == "dvi" &&
182 !lyxrc.view_dvi_paper_option.empty()) {
183 command += " " + lyxrc.view_dvi_paper_option;
184 string paper_size = converters.papersize(buffer);
185 if (paper_size == "letter")
187 command += " " + paper_size;
188 if (buffer->params.orientation
189 == BufferParams::ORIENTATION_LANDSCAPE)
193 command += " " + QuoteName(OnlyFilename((filename)));
195 lyxerr[Debug::FILES] << "Executing command: " << command << endl;
196 ShowMessage(buffer, _("Executing command:"), command);
198 Path p(OnlyPath(filename));
200 int const res = one.startscript(Systemcall::DontWait, command);
203 Alert::alert(_("Cannot view file"),
204 _("Error while executing"),
205 command.substr(0, 50));
212 string const Formats::prettyName(string const & name) const
214 Format const * format = getFormat(name);
216 return format->prettyname();
222 string const Formats::extension(string const & name) const
224 Format const * format = getFormat(name);
226 return format->extension();
231 //////////////////////////////////////////////////////////////////////////////
233 void Converter::readFlags()
235 string flag_list(flags);
236 while (!flag_list.empty()) {
237 string flag_name, flag_value;
238 flag_list = split(flag_list, flag_value, ',');
239 flag_value = split(flag_value, flag_name, '=');
240 if (flag_name == "latex")
242 else if (flag_name == "originaldir")
244 else if (flag_name == "needaux")
246 else if (flag_name == "resultdir")
247 result_dir = (flag_value.empty())
248 ? token_base : flag_value;
249 else if (flag_name == "resultfile")
250 result_file = flag_value;
251 else if (flag_name == "parselog")
252 parselog = flag_value;
254 if (!result_dir.empty() && result_file.empty())
255 result_file = "index." + formats.extension(to);
256 //if (!contains(command, token_from))
261 bool operator<(Converter const & a, Converter const & b)
263 int const i = compare_no_case(a.From->prettyname(),
264 b.From->prettyname());
266 return compare_no_case(a.To->prettyname(), b.To->prettyname())
272 //////////////////////////////////////////////////////////////////////////////
274 class compare_Converter {
276 compare_Converter(string const & f, string const & t)
278 bool operator()(Converter const & c) {
279 return c.from == from && c.to == to;
287 Converter const * Converters::getConverter(string const & from,
290 ConverterList::const_iterator cit =
291 find_if(converterlist_.begin(), converterlist_.end(),
292 compare_Converter(from, to));
293 if (cit != converterlist_.end())
300 int Converters::getNumber(string const & from, string const & to)
302 ConverterList::const_iterator cit =
303 find_if(converterlist_.begin(), converterlist_.end(),
304 compare_Converter(from, to));
305 if (cit != converterlist_.end())
306 return cit - converterlist_.begin();
312 void Converters::add(string const & from, string const & to,
313 string const & command, string const & flags)
317 ConverterList::iterator it = find_if(converterlist_.begin(),
318 converterlist_.end(),
319 compare_Converter(from, to));
321 Converter converter(from, to, command, flags);
322 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
324 converter.command = command;
325 converter.flags = flags;
327 converter.readFlags();
329 if (converter.latex && (latex_command_.empty() || to == "dvi"))
330 latex_command_ = subst(command, token_from, "");
331 // If we have both latex & pdflatex, we set latex_command to latex.
332 // The latex_command is used to update the .aux file when running
333 // a converter that uses it.
335 if (it == converterlist_.end()) {
336 converterlist_.push_back(converter);
338 converter.From = it->From;
339 converter.To = it->To;
345 void Converters::erase(string const & from, string const & to)
347 ConverterList::iterator it = find_if(converterlist_.begin(),
348 converterlist_.end(),
349 compare_Converter(from, to));
350 if (it != converterlist_.end())
351 converterlist_.erase(it);
355 // This method updates the pointers From and To in all the converters.
356 // The code is not very efficient, but it doesn't matter as the number
357 // of formats and converters is small.
358 // Furthermore, this method is called only on startup, or after
359 // adding/deleting a format in FormPreferences (the latter calls can be
360 // eliminated if the formats in the Formats class are stored using a map or
361 // a list (instead of a vector), but this will cause other problems).
362 void Converters::update(Formats const & formats)
364 ConverterList::iterator it = converterlist_.begin();
365 ConverterList::iterator end = converterlist_.end();
366 for (; it != end; ++it) {
367 it->From = formats.getFormat(it->from);
368 it->To = formats.getFormat(it->to);
373 // This method updates the pointers From and To in the last converter.
374 // It is called when adding a new converter in FormPreferences
375 void Converters::updateLast(Formats const & formats)
377 if (converterlist_.begin() != converterlist_.end()) {
378 ConverterList::iterator it = converterlist_.end() - 1;
379 it->From = formats.getFormat(it->from);
380 it->To = formats.getFormat(it->to);
385 void Converters::sort()
387 std::sort(converterlist_.begin(), converterlist_.end());
391 int Converters::bfs_init(string const & start, bool clear_visited)
393 int const s = formats.getNumber(start);
399 fill(visited_.begin(), visited_.end(), false);
400 if (visited_[s] == false) {
408 vector<Format const *> const
409 Converters::getReachableTo(string const & target, bool clear_visited)
411 vector<Format const *> result;
412 int const s = bfs_init(target, clear_visited);
416 while (!Q_.empty()) {
417 int const i = Q_.front();
419 if (i != s || target != "lyx") {
420 result.push_back(&formats.get(i));
423 vector<int>::iterator it = vertices_[i].in_vertices.begin();
424 vector<int>::iterator end = vertices_[i].in_vertices.end();
425 for (; it != end; ++it) {
426 if (!visited_[*it]) {
427 visited_[*it] = true;
437 vector<Format const *> const
438 Converters::getReachable(string const & from, bool only_viewable,
441 vector<Format const *> result;
443 if (bfs_init(from, clear_visited) < 0)
446 while (!Q_.empty()) {
447 int const i = Q_.front();
449 Format const & format = formats.get(i);
450 if (format.name() == "lyx")
452 if (!only_viewable || !format.viewer().empty() ||
453 format.isChildFormat())
454 result.push_back(&format);
456 vector<int>::const_iterator cit =
457 vertices_[i].out_vertices.begin();
458 vector<int>::const_iterator end =
459 vertices_[i].out_vertices.end();
460 for (; cit != end; ++cit)
461 if (!visited_[*cit]) {
462 visited_[*cit] = true;
471 bool Converters::isReachable(string const & from, string const & to)
476 int const s = bfs_init(from);
477 int const t = formats.getNumber(to);
481 while (!Q_.empty()) {
482 int const i = Q_.front();
487 vector<int>::const_iterator cit =
488 vertices_[i].out_vertices.begin();
489 vector<int>::const_iterator end =
490 vertices_[i].out_vertices.end();
491 for (; cit != end; ++cit) {
492 if (!visited_[*cit]) {
493 visited_[*cit] = true;
503 Converters::EdgePath const
504 Converters::getPath(string const & from, string const & to)
510 int const s = bfs_init(from);
511 int t = formats.getNumber(to);
515 vector<int> prev_edge(formats.size());
516 vector<int> prev_vertex(formats.size());
519 while (!Q_.empty()) {
520 int const i = Q_.front();
527 vector<int>::const_iterator beg =
528 vertices_[i].out_vertices.begin();
529 vector<int>::const_iterator cit = beg;
530 vector<int>::const_iterator end =
531 vertices_[i].out_vertices.end();
532 for (; cit != end; ++cit)
533 if (!visited_[*cit]) {
537 int const k = cit - beg;
538 prev_edge[j] = vertices_[i].out_edges[k];
546 path.push_back(prev_edge[t]);
549 reverse(path.begin(), path.end());
554 bool Converters::usePdflatex(EdgePath const & path)
556 for (EdgePath::const_iterator cit = path.begin();
557 cit != path.end(); ++cit) {
558 Converter const & conv = converterlist_[*cit];
560 return contains(conv.to, "pdf");
566 bool Converters::convert(Buffer const * buffer,
567 string const & from_file, string const & to_file_base,
568 string const & from_format, string const & to_format,
571 to_file = ChangeExtension(to_file_base,
572 formats.extension(to_format));
574 if (from_format == to_format)
575 return move(from_file, to_file, false);
577 EdgePath edgepath = getPath(from_format, to_format);
578 if (edgepath.empty()) {
579 Alert::alert(_("Cannot convert file"),
580 _("No information for converting from ")
581 + formats.prettyName(from_format) + _(" to ")
582 + formats.prettyName(to_format));
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 command2 = conv.parselog +
661 " < " + QuoteName(infile2 + ".out") +
662 " > " + QuoteName(logfile);
663 one.startscript(Systemcall::Wait, command2);
664 if (!scanLog(buffer, command, logfile))
669 if (conv.to == "program")
670 Alert::alert(_("There were errors during the Build process."),
671 _("You should try to fix them."));
673 Alert::alert(_("Cannot convert file"),
674 "Error while executing",
675 command.substr(0, 50));
681 Converter const & conv = converterlist_[edgepath.back()];
682 if (conv.To->dummy())
686 if (!conv.result_dir.empty()) {
687 to_file = AddName(subst(conv.result_dir, token_base, to_base),
688 subst(conv.result_file,
689 token_base, OnlyFilename(to_base)));
690 if (from_base != to_base) {
691 string from = subst(conv.result_dir,
692 token_base, from_base);
693 string to = subst(conv.result_dir,
694 token_base, to_base);
695 if (!lyx::rename(from, to)) {
696 Alert::alert(_("Error while trying to move directory:"),
703 return move(outfile, to_file, conv.latex);
706 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
707 // moves each /path/file*.ext file to /path2/file2*.ext2'
708 bool Converters::move(string const & from, string const & to, bool copy)
713 bool no_errors = true;
714 string const path = OnlyPath(from);
715 string const base = OnlyFilename(ChangeExtension(from, ""));
716 string const to_base = ChangeExtension(to, "");
717 string const to_extension = GetExtension(to);
719 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
720 for (vector<string>::const_iterator it = files.begin();
721 it != files.end(); ++it)
722 if (prefixIs(*it, base)) {
723 string from2 = path + *it;
724 string to2 = to_base + it->substr(base.length());
725 to2 = ChangeExtension(to2, to_extension);
726 lyxerr[Debug::FILES] << "moving " << from2
727 << " to " << to2 << endl;
729 ? lyx::copy(from2, to2)
730 : lyx::rename(from2, to2);
731 if (!moved && no_errors) {
732 Alert::alert(_("Error while trying to move file:"),
733 from2, _("to ") + to2);
741 bool Converters::convert(Buffer const * buffer,
742 string const & from_file, string const & to_file_base,
743 string const & from_format, string const & to_format)
746 return convert(buffer, from_file, to_file_base, from_format, to_format,
751 void Converters::buildGraph()
753 vertices_ = vector<Vertex>(formats.size());
754 visited_.resize(formats.size());
756 for (ConverterList::iterator it = converterlist_.begin();
757 it != converterlist_.end(); ++it) {
758 int const s = formats.getNumber(it->from);
759 int const t = formats.getNumber(it->to);
760 vertices_[t].in_vertices.push_back(s);
761 vertices_[s].out_vertices.push_back(t);
762 vertices_[s].out_edges.push_back(it - converterlist_.begin());
767 bool Converters::formatIsUsed(string const & format)
769 ConverterList::const_iterator cit = converterlist_.begin();
770 ConverterList::const_iterator end = converterlist_.end();
771 for (; cit != end; ++cit) {
772 if (cit->from == format || cit->to == format)
779 bool Converters::scanLog(Buffer const * buffer, string const & command,
780 string const & filename)
785 BufferView * bv = buffer->getUser();
786 bool need_redraw = false;
788 bv->owner()->prohibitInput();
789 // Remove all error insets
790 need_redraw = bv->removeAutoInsets();
793 LaTeX latex("", filename, "");
795 int result = latex.scanLogFile(terr);
797 if ((result & LaTeX::ERRORS)) {
798 // Insert all errors as errors boxes
799 bv->insertErrors(terr);
806 bv->owner()->allowInput();
809 if ((result & LaTeX::ERRORS)) {
810 int num_errors = latex.getNumErrors();
813 if (num_errors == 1) {
814 s = _("One error detected");
815 t = _("You should try to fix it.");
817 s = tostr(num_errors);
818 s += _(" errors detected.");
819 t = _("You should try to fix them.");
822 split(command, head, ' ');
823 Alert::alert(_("There were errors during running of ") + head,
826 } else if (result & LaTeX::NO_OUTPUT) {
827 string const s = _("The operation resulted in");
828 string const t = _("an empty file.");
829 Alert::alert(_("Resulting file is empty"), s, t);
836 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
841 BufferView * bv = buffer->getUser();
842 string name = buffer->getLatexName();
843 bool need_redraw = false;
846 bv->owner()->prohibitInput();
847 bv->owner()->message(_("Running LaTeX..."));
848 // Remove all error insets
849 need_redraw = bv->removeAutoInsets();
853 // do the LaTex run(s)
855 LaTeX latex(command, name, buffer->filePath());
856 int result = latex.run(terr,
857 bv ? bv->owner()->getLyXFunc() : 0);
861 if ((result & LaTeX::ERRORS)) {
862 // Insert all errors as errors boxes
863 bv->insertErrors(terr);
867 // if we removed error insets before we ran LaTeX or if we inserted
868 // error insets after we ran LaTeX this must be run:
875 // check return value from latex.run().
876 if ((result & LaTeX::NO_LOGFILE)) {
877 Alert::alert(_("LaTeX did not work!"),
878 _("Missing log file:"), name);
879 } else if ((result & LaTeX::ERRORS)) {
880 int num_errors = latex.getNumErrors();
883 if (num_errors == 1) {
884 s = _("One error detected");
885 t = _("You should try to fix it.");
887 s = tostr(num_errors);
888 s += _(" errors detected.");
889 t = _("You should try to fix them.");
891 Alert::alert(_("There were errors during the LaTeX run."),
893 } else if (result & LaTeX::NO_OUTPUT) {
894 string const s = _("The operation resulted in");
895 string const t = _("an empty file.");
896 Alert::alert(_("Resulting file is empty"), s, t);
900 bv->owner()->allowInput();
902 int const ERROR_MASK =
907 return (result & ERROR_MASK) == 0;
912 string const Converters::papersize(Buffer const * buffer)
914 char real_papersize = buffer->params.papersize;
915 if (real_papersize == BufferParams::PAPER_DEFAULT)
916 real_papersize = lyxrc.default_papersize;
918 switch (real_papersize) {
919 case BufferParams::PAPER_A3PAPER:
921 case BufferParams::PAPER_A4PAPER:
923 case BufferParams::PAPER_A5PAPER:
925 case BufferParams::PAPER_B5PAPER:
927 case BufferParams::PAPER_EXECUTIVEPAPER:
929 case BufferParams::PAPER_LEGALPAPER:
931 case BufferParams::PAPER_USLETTER:
938 string const Converters::dvips_options(Buffer const * buffer)
944 if (buffer->params.use_geometry
945 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
946 && !lyxrc.print_paper_dimension_flag.empty()
947 && !buffer->params.paperwidth.empty()
948 && !buffer->params.paperheight.empty()) {
949 // using a custom papersize
950 result = lyxrc.print_paper_dimension_flag;
951 result += ' ' + buffer->params.paperwidth;
952 result += ',' + buffer->params.paperheight;
954 string const paper_option = papersize(buffer);
955 if (paper_option != "letter" ||
956 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
957 // dvips won't accept -t letter -t landscape. In all other
958 // cases, include the paper size explicitly.
959 result = lyxrc.print_paper_flag;
960 result += ' ' + paper_option;
963 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
964 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
965 result += ' ' + lyxrc.print_landscape_flag;
970 string const Converters::dvipdfm_options(Buffer const * buffer)
976 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
977 string const paper_size = papersize(buffer);
978 if (paper_size != "b5" && paper_size != "foolscap")
979 result = "-p "+ paper_size;
981 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
989 vector<Converters::Vertex> Converters::vertices_;
992 /// The global instance
994 Converters converters;
996 // The global copy after reading lyxrc.defaults
997 Formats system_formats;
998 Converters system_converters;