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"
21 #include "support/syscall.h"
22 #include "support/path.h"
23 #include "support/filetools.h"
25 #include "bufferview_funcs.h"
28 #include "lyx_gui_misc.h"
29 #include "lyx_cb.h" // ShowMessage()
30 #include "support/lyxfunctional.h"
32 #include "BufferView.h"
45 string const token_from("$$i");
46 string const token_base("$$b");
47 string const token_to("$$o");
49 //////////////////////////////////////////////////////////////////////////////
52 string const add_options(string const & command, string const & options)
55 string const tail = split(command, head, ' ');
56 return head + ' ' + options + ' ' + tail;
61 //////////////////////////////////////////////////////////////////////////////
63 bool Format::dummy() const
65 return extension().empty();
69 bool Format::isChildFormat() const
73 return isdigit(name_[name_.length() - 1]);
77 string const Format::parentFormat() const
79 return name_.substr(0, name_.length() - 1);
82 //////////////////////////////////////////////////////////////////////////////
84 // This method should return a reference, and throw an exception
85 // if the format named name cannot be found (Lgb)
86 Format const * Formats::getFormat(string const & name) const
88 FormatList::const_iterator cit =
89 find_if(formatlist.begin(), formatlist.end(),
90 lyx::compare_memfun(&Format::name, name));
91 if (cit != formatlist.end())
98 int Formats::getNumber(string const & name) const
100 FormatList::const_iterator cit =
101 find_if(formatlist.begin(), formatlist.end(),
102 lyx::compare_memfun(&Format::name, name));
103 if (cit != formatlist.end())
104 return cit - formatlist.begin();
110 void Formats::add(string const & name)
112 if (!getFormat(name))
113 add(name, name, name, string());
117 void Formats::add(string const & name, string const & extension,
118 string const & prettyname, string const & shortcut)
120 FormatList::iterator it =
121 find_if(formatlist.begin(), formatlist.end(),
122 lyx::compare_memfun(&Format::name, name));
123 if (it == formatlist.end())
124 formatlist.push_back(Format(name, extension, prettyname,
127 string viewer = it->viewer();
128 *it = Format(name, extension, prettyname, shortcut, viewer);
133 void Formats::erase(string const & name)
135 FormatList::iterator it =
136 find_if(formatlist.begin(), formatlist.end(),
137 lyx::compare_memfun(&Format::name, name));
138 if (it != formatlist.end())
139 formatlist.erase(it);
145 std::sort(formatlist.begin(), formatlist.end());
149 void Formats::setViewer(string const & name, string const & command)
152 FormatList::iterator it =
153 find_if(formatlist.begin(), formatlist.end(),
154 lyx::compare_memfun(&Format::name, name));
155 if (it != formatlist.end())
156 it->setViewer(command);
160 bool Formats::view(Buffer const * buffer, string const & filename,
161 string const & format_name) const
163 if (filename.empty())
166 Format const * format = getFormat(format_name);
167 if (format && format->viewer().empty() &&
168 format->isChildFormat())
169 format = getFormat(format->parentFormat());
170 if (!format || format->viewer().empty()) {
171 WriteAlert(_("Cannot view file"),
172 _("No information for viewing ")
173 + prettyName(format_name));
177 string command = format->viewer();
179 if (format_name == "dvi" &&
180 !lyxrc.view_dvi_paper_option.empty()) {
181 command += " " + lyxrc.view_dvi_paper_option;
182 string paper_size = converters.papersize(buffer);
183 if (paper_size == "letter")
185 command += " " + paper_size;
186 if (buffer->params.orientation
187 == BufferParams::ORIENTATION_LANDSCAPE)
191 command += " " + QuoteName(OnlyFilename((filename)));
193 lyxerr[Debug::FILES] << "Executing command: " << command << endl;
194 ShowMessage(buffer, _("Executing command:"), command);
196 Path p(OnlyPath(filename));
198 int const res = one.startscript(Systemcalls::SystemDontWait, command);
201 WriteAlert(_("Cannot view file"),
202 _("Error while executing"),
203 command.substr(0, 50));
210 string const Formats::prettyName(string const & name) const
212 Format const * format = getFormat(name);
214 return format->prettyname();
220 string const Formats::extension(string const & name) const
222 Format const * format = getFormat(name);
224 return format->extension();
229 //////////////////////////////////////////////////////////////////////////////
231 void Converter::readFlags()
233 string flag_list(flags);
234 while (!flag_list.empty()) {
235 string flag_name, flag_value;
236 flag_list = split(flag_list, flag_value, ',');
237 flag_value = split(flag_value, flag_name, '=');
238 if (flag_name == "latex")
240 else if (flag_name == "originaldir")
242 else if (flag_name == "needaux")
244 else if (flag_name == "resultdir")
245 result_dir = (flag_value.empty())
246 ? token_base : flag_value;
247 else if (flag_name == "resultfile")
248 result_file = flag_value;
249 else if (flag_name == "parselog")
250 parselog = flag_value;
252 if (!result_dir.empty() && result_file.empty())
253 result_file = "index." + formats.extension(to);
254 //if (!contains(command, token_from))
259 bool operator<(Converter const & a, Converter const & b)
261 int const i = compare_no_case(a.From->prettyname(),
262 b.From->prettyname());
264 return compare_no_case(a.To->prettyname(), b.To->prettyname())
270 //////////////////////////////////////////////////////////////////////////////
272 class compare_Converter {
274 compare_Converter(string const & f, string const & t)
276 bool operator()(Converter const & c) {
277 return c.from == from && c.to == to;
285 Converter const * Converters::getConverter(string const & from,
288 ConverterList::const_iterator cit =
289 find_if(converterlist_.begin(), converterlist_.end(),
290 compare_Converter(from, to));
291 if (cit != converterlist_.end())
298 int Converters::getNumber(string const & from, string const & to)
300 ConverterList::const_iterator cit =
301 find_if(converterlist_.begin(), converterlist_.end(),
302 compare_Converter(from, to));
303 if (cit != converterlist_.end())
304 return cit - converterlist_.begin();
310 void Converters::add(string const & from, string const & to,
311 string const & command, string const & flags)
315 ConverterList::iterator it = find_if(converterlist_.begin(),
316 converterlist_.end(),
317 compare_Converter(from, to));
319 Converter converter(from, to, command, flags);
320 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
322 converter.command = command;
323 converter.flags = flags;
325 converter.readFlags();
327 if (converter.latex && (latex_command_.empty() || to == "dvi"))
328 latex_command_ = subst(command, token_from, "");
329 // If we have both latex & pdflatex, we set latex_command to latex.
330 // The latex_command is used to update the .aux file when running
331 // a converter that uses it.
333 if (it == converterlist_.end()) {
334 converterlist_.push_back(converter);
336 converter.From = it->From;
337 converter.To = it->To;
343 void Converters::erase(string const & from, string const & to)
345 ConverterList::iterator it = find_if(converterlist_.begin(),
346 converterlist_.end(),
347 compare_Converter(from, to));
348 if (it != converterlist_.end())
349 converterlist_.erase(it);
353 // This method updates the pointers From and To in all the converters.
354 // The code is not very efficient, but it doesn't matter as the number
355 // of formats and converters is small.
356 // Furthermore, this method is called only on startup, or after
357 // adding/deleting a format in FormPreferences (the latter calls can be
358 // eliminated if the formats in the Formats class are stored using a map or
359 // a list (instead of a vector), but this will cause other problems).
360 void Converters::update(Formats const & formats)
362 ConverterList::iterator it = converterlist_.begin();
363 ConverterList::iterator end = converterlist_.end();
364 for (; it != end; ++it) {
365 it->From = formats.getFormat(it->from);
366 it->To = formats.getFormat(it->to);
371 // This method updates the pointers From and To in the last converter.
372 // It is called when adding a new converter in FormPreferences
373 void Converters::updateLast(Formats const & formats)
375 if (converterlist_.begin() != converterlist_.end()) {
376 ConverterList::iterator it = converterlist_.end() - 1;
377 it->From = formats.getFormat(it->from);
378 it->To = formats.getFormat(it->to);
383 void Converters::sort()
385 std::sort(converterlist_.begin(), converterlist_.end());
389 int Converters::bfs_init(string const & start, bool clear_visited)
391 int const s = formats.getNumber(start);
397 fill(visited_.begin(), visited_.end(), false);
398 if (visited_[s] == false) {
406 vector<Format const *> const
407 Converters::getReachableTo(string const & target, bool clear_visited)
409 vector<Format const *> result;
410 int const s = bfs_init(target, clear_visited);
414 while (!Q_.empty()) {
415 int const i = Q_.front();
417 if (i != s || target != "lyx") {
418 result.push_back(&formats.get(i));
421 vector<int>::iterator it = vertices_[i].in_vertices.begin();
422 vector<int>::iterator end = vertices_[i].in_vertices.end();
423 for (; it != end; ++it) {
424 if (!visited_[*it]) {
425 visited_[*it] = true;
435 vector<Format const *> const
436 Converters::getReachable(string const & from, bool only_viewable,
439 vector<Format const *> result;
441 if (bfs_init(from, clear_visited) < 0)
444 while (!Q_.empty()) {
445 int const i = Q_.front();
447 Format const & format = formats.get(i);
448 if (format.name() == "lyx")
450 if (!only_viewable || !format.viewer().empty() ||
451 format.isChildFormat())
452 result.push_back(&format);
454 vector<int>::const_iterator cit =
455 vertices_[i].out_vertices.begin();
456 vector<int>::const_iterator end =
457 vertices_[i].out_vertices.end();
458 for (; cit != end; ++cit)
459 if (!visited_[*cit]) {
460 visited_[*cit] = true;
469 bool Converters::isReachable(string const & from, string const & to)
474 int const s = bfs_init(from);
475 int const t = formats.getNumber(to);
479 while (!Q_.empty()) {
480 int const i = Q_.front();
485 vector<int>::const_iterator cit =
486 vertices_[i].out_vertices.begin();
487 vector<int>::const_iterator end =
488 vertices_[i].out_vertices.end();
489 for (; cit != end; ++cit) {
490 if (!visited_[*cit]) {
491 visited_[*cit] = true;
501 Converters::EdgePath const
502 Converters::getPath(string const & from, string const & to)
508 int const s = bfs_init(from);
509 int t = formats.getNumber(to);
513 vector<int> prev_edge(formats.size());
514 vector<int> prev_vertex(formats.size());
517 while (!Q_.empty()) {
518 int const i = Q_.front();
525 vector<int>::const_iterator beg =
526 vertices_[i].out_vertices.begin();
527 vector<int>::const_iterator cit = beg;
528 vector<int>::const_iterator end =
529 vertices_[i].out_vertices.end();
530 for (; cit != end; ++cit)
531 if (!visited_[*cit]) {
535 int const k = cit - beg;
536 prev_edge[j] = vertices_[i].out_edges[k];
544 path.push_back(prev_edge[t]);
547 reverse(path.begin(), path.end());
552 bool Converters::usePdflatex(EdgePath const & path)
554 for (EdgePath::const_iterator cit = path.begin();
555 cit != path.end(); ++cit) {
556 Converter const & conv = converterlist_[*cit];
558 return contains(conv.to, "pdf");
564 bool Converters::convert(Buffer const * buffer,
565 string const & from_file, string const & to_file_base,
566 string const & from_format, string const & to_format,
569 to_file = ChangeExtension(to_file_base,
570 formats.extension(to_format));
572 if (from_format == to_format)
573 return move(from_file, to_file, false);
575 EdgePath edgepath = getPath(from_format, to_format);
576 if (edgepath.empty()) {
577 WriteAlert(_("Cannot convert file"),
578 _("No information for converting from ")
579 + formats.prettyName(from_format) + _(" to ")
580 + formats.prettyName(to_format));
584 string path = OnlyPath(from_file);
587 bool run_latex = false;
588 string from_base = ChangeExtension(from_file, "");
589 string to_base = ChangeExtension(to_file, "");
591 string outfile = from_file;
592 for (EdgePath::const_iterator cit = edgepath.begin();
593 cit != edgepath.end(); ++cit) {
594 Converter const & conv = converterlist_[*cit];
595 bool dummy = conv.To->dummy() && conv.to != "program";
597 lyxerr[Debug::FILES] << "Converting from "
598 << conv.from << " to " << conv.to << endl;
600 outfile = conv.result_dir.empty()
601 ? ChangeExtension(from_file, conv.To->extension())
602 : AddName(subst(conv.result_dir,
603 token_base, from_base),
604 subst(conv.result_file,
605 token_base, OnlyFilename(from_base)));
609 string command = subst(conv.command, token_from, "");
610 lyxerr[Debug::FILES] << "Running " << command << endl;
611 if (!runLaTeX(buffer, command))
614 if (conv.need_aux && !run_latex
615 && !latex_command_.empty()) {
617 << "Running " << latex_command_
618 << " to update aux file"<< endl;
619 runLaTeX(buffer, latex_command_);
622 string infile2 = (conv.original_dir)
623 ? infile : MakeRelPath(infile, path);
624 string outfile2 = (conv.original_dir)
625 ? outfile : MakeRelPath(outfile, path);
627 string command = conv.command;
628 command = subst(command, token_from, QuoteName(infile2));
629 command = subst(command, token_base, QuoteName(from_base));
630 command = subst(command, token_to, QuoteName(outfile2));
632 if (!conv.parselog.empty())
633 command += " 2> " + QuoteName(infile2 + ".out");
635 if (conv.from == "dvi" && conv.to == "ps")
636 command = add_options(command,
637 dvips_options(buffer));
638 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
639 command = add_options(command,
640 dvipdfm_options(buffer));
642 lyxerr[Debug::FILES] << "Calling " << command << endl;
644 ShowMessage(buffer, _("Executing command:"), command);
646 Systemcalls::Starttype type = (dummy)
647 ? Systemcalls::SystemDontWait : Systemcalls::System;
650 if (conv.original_dir && buffer) {
651 Path p(buffer->filepath);
652 res = one.startscript(type, command);
654 res = one.startscript(type, command);
656 if (!conv.parselog.empty()) {
657 string const logfile = infile2 + ".log";
658 string const command2 = conv.parselog +
659 " < " + QuoteName(infile2 + ".out") +
660 " > " + QuoteName(logfile);
661 one.startscript(Systemcalls::System, command2);
662 if (!scanLog(buffer, command, logfile))
667 if (conv.to == "program")
668 WriteAlert(_("There were errors during the Build process."),
669 _("You should try to fix them."));
671 WriteAlert(_("Cannot convert file"),
672 "Error while executing",
673 command.substr(0, 50));
679 Converter const & conv = converterlist_[edgepath.back()];
680 if (conv.To->dummy())
684 if (!conv.result_dir.empty()) {
685 to_file = AddName(subst(conv.result_dir, token_base, to_base),
686 subst(conv.result_file,
687 token_base, OnlyFilename(to_base)));
688 if (from_base != to_base) {
689 string from = subst(conv.result_dir,
690 token_base, from_base);
691 string to = subst(conv.result_dir,
692 token_base, to_base);
693 if (!lyx::rename(from, to)) {
694 WriteAlert(_("Error while trying to move directory:"),
701 return move(outfile, to_file, conv.latex);
704 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
705 // moves each /path/file*.ext file to /path2/file2*.ext2'
706 bool Converters::move(string const & from, string const & to, bool copy)
711 bool no_errors = true;
712 string const path = OnlyPath(from);
713 string const base = OnlyFilename(ChangeExtension(from, ""));
714 string const to_base = ChangeExtension(to, "");
715 string const to_extension = GetExtension(to);
717 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
718 for (vector<string>::const_iterator it = files.begin();
719 it != files.end(); ++it)
720 if (prefixIs(*it, base)) {
721 string from2 = path + *it;
722 string to2 = to_base + it->substr(base.length());
723 to2 = ChangeExtension(to2, to_extension);
724 lyxerr[Debug::FILES] << "moving " << from2
725 << " to " << to2 << endl;
727 ? lyx::copy(from2, to2)
728 : lyx::rename(from2, to2);
729 if (!moved && no_errors) {
730 WriteAlert(_("Error while trying to move file:"),
731 from2, _("to ") + to2);
739 bool Converters::convert(Buffer const * buffer,
740 string const & from_file, string const & to_file_base,
741 string const & from_format, string const & to_format)
744 return convert(buffer, from_file, to_file_base, from_format, to_format,
749 void Converters::buildGraph()
751 vertices_ = vector<Vertex>(formats.size());
752 visited_.resize(formats.size());
754 for (ConverterList::iterator it = converterlist_.begin();
755 it != converterlist_.end(); ++it) {
756 int const s = formats.getNumber(it->from);
757 int const t = formats.getNumber(it->to);
758 vertices_[t].in_vertices.push_back(s);
759 vertices_[s].out_vertices.push_back(t);
760 vertices_[s].out_edges.push_back(it - converterlist_.begin());
765 bool Converters::formatIsUsed(string const & format)
767 ConverterList::const_iterator cit = converterlist_.begin();
768 ConverterList::const_iterator end = converterlist_.end();
769 for (; cit != end; ++cit) {
770 if (cit->from == format || cit->to == format)
777 bool Converters::scanLog(Buffer const * buffer, string const & command,
778 string const & filename)
783 BufferView * bv = buffer->getUser();
784 bool need_redraw = false;
786 bv->owner()->prohibitInput();
787 // Remove all error insets
788 need_redraw = bv->removeAutoInsets();
791 LaTeX latex("", filename, "");
793 int result = latex.scanLogFile(terr);
795 if ((result & LaTeX::ERRORS)) {
796 // Insert all errors as errors boxes
797 bv->insertErrors(terr);
804 bv->owner()->allowInput();
807 if ((result & LaTeX::ERRORS)) {
808 int num_errors = latex.getNumErrors();
811 if (num_errors == 1) {
812 s = _("One error detected");
813 t = _("You should try to fix it.");
815 s = tostr(num_errors);
816 s += _(" errors detected.");
817 t = _("You should try to fix them.");
820 split(command, head, ' ');
821 WriteAlert(_("There were errors during running of ") + head,
824 } else if (result & LaTeX::NO_OUTPUT) {
825 string const s = _("The operation resulted in");
826 string const t = _("an empty file.");
827 WriteAlert(_("Resulting file is empty"), s, t);
834 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
839 BufferView * bv = buffer->getUser();
840 string name = buffer->getLatexName();
841 bool need_redraw = false;
844 bv->owner()->prohibitInput();
845 bv->owner()->message(_("Running LaTeX..."));
846 // Remove all error insets
847 need_redraw = bv->removeAutoInsets();
851 // do the LaTex run(s)
853 LaTeX latex(command, name, buffer->filepath);
854 int result = latex.run(terr,
855 bv ? bv->owner()->getLyXFunc() : 0);
859 if ((result & LaTeX::ERRORS)) {
860 // Insert all errors as errors boxes
861 bv->insertErrors(terr);
865 // if we removed error insets before we ran LaTeX or if we inserted
866 // error insets after we ran LaTeX this must be run:
873 // check return value from latex.run().
874 if ((result & LaTeX::NO_LOGFILE)) {
875 WriteAlert(_("LaTeX did not work!"),
876 _("Missing log file:"), name);
877 } else if ((result & LaTeX::ERRORS)) {
878 int num_errors = latex.getNumErrors();
881 if (num_errors == 1) {
882 s = _("One error detected");
883 t = _("You should try to fix it.");
885 s = tostr(num_errors);
886 s += _(" errors detected.");
887 t = _("You should try to fix them.");
889 WriteAlert(_("There were errors during the LaTeX run."),
891 } else if (result & LaTeX::NO_OUTPUT) {
892 string const s = _("The operation resulted in");
893 string const t = _("an empty file.");
894 WriteAlert(_("Resulting file is empty"), s, t);
898 bv->owner()->allowInput();
900 int const ERROR_MASK =
905 return (result & ERROR_MASK) == 0;
910 string const Converters::papersize(Buffer const * buffer)
912 char real_papersize = buffer->params.papersize;
913 if (real_papersize == BufferParams::PAPER_DEFAULT)
914 real_papersize = lyxrc.default_papersize;
916 switch (real_papersize) {
917 case BufferParams::PAPER_A3PAPER:
919 case BufferParams::PAPER_A4PAPER:
921 case BufferParams::PAPER_A5PAPER:
923 case BufferParams::PAPER_B5PAPER:
925 case BufferParams::PAPER_EXECUTIVEPAPER:
927 case BufferParams::PAPER_LEGALPAPER:
929 case BufferParams::PAPER_USLETTER:
936 string const Converters::dvips_options(Buffer const * buffer)
942 if (buffer->params.use_geometry
943 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
944 && !lyxrc.print_paper_dimension_flag.empty()
945 && !buffer->params.paperwidth.empty()
946 && !buffer->params.paperheight.empty()) {
947 // using a custom papersize
948 result = lyxrc.print_paper_dimension_flag;
949 result += ' ' + buffer->params.paperwidth;
950 result += ',' + buffer->params.paperheight;
952 string const paper_option = papersize(buffer);
953 if (paper_option != "letter" ||
954 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
955 // dvips won't accept -t letter -t landscape. In all other
956 // cases, include the paper size explicitly.
957 result = lyxrc.print_paper_flag;
958 result += ' ' + paper_option;
961 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
962 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
963 result += ' ' + lyxrc.print_landscape_flag;
968 string const Converters::dvipdfm_options(Buffer const * buffer)
974 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
975 string const paper_size = papersize(buffer);
976 if (paper_size != "b5" && paper_size != "foolscap")
977 result = "-p "+ paper_size;
979 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
987 vector<Converters::Vertex> Converters::vertices_;
990 /// The global instance
992 Converters converters;
994 // The global copy after reading lyxrc.defaults
995 Formats system_formats;
996 Converters system_converters;