1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 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 "minibuffer.h"
29 #include "lyx_gui_misc.h"
30 #include "lyx_cb.h" // ShowMessage()
31 #include "support/lyxfunctional.h"
41 static string const token_from("$$i");
42 static string const token_base("$$b");
43 static string const token_to("$$o");
45 //////////////////////////////////////////////////////////////////////////////
48 string const add_options(string const & command, string const & options)
51 string const tail = split(command, head, ' ');
52 return head + ' ' + options + ' ' + tail;
55 //////////////////////////////////////////////////////////////////////////////
57 bool Format::dummy() const
59 return extension().empty();
63 bool Format::IsChildFormat() const
67 return isdigit(name_[name_.length() - 1]);
71 string const Format::ParentFormat() const
73 return name_.substr(0, name_.length() - 1);
76 //////////////////////////////////////////////////////////////////////////////
78 // This method should return a reference, and throw an exception
79 // if the format named name cannot be found (Lgb)
80 Format const * Formats::GetFormat(string const & name) const
82 FormatList::const_iterator cit =
83 find_if(formatlist.begin(), formatlist.end(),
84 compare_memfun(&Format::name, name));
85 if (cit != formatlist.end())
92 int Formats::GetNumber(string const & name) const
94 FormatList::const_iterator cit =
95 find_if(formatlist.begin(), formatlist.end(),
96 compare_memfun(&Format::name, name));
97 if (cit != formatlist.end())
98 return cit - formatlist.begin();
104 void Formats::Add(string const & name)
106 if (!GetFormat(name))
107 Add(name, name, name, string());
111 void Formats::Add(string const & name, string const & extension,
112 string const & prettyname, string const & shortcut)
114 FormatList::iterator it =
115 find_if(formatlist.begin(), formatlist.end(),
116 compare_memfun(&Format::name, name));
117 if (it == formatlist.end())
118 formatlist.push_back(Format(name, extension, prettyname,
121 string viewer = it->viewer();
122 *it = Format(name, extension, prettyname, shortcut, viewer);
127 void Formats::Delete(string const & name)
129 FormatList::iterator it =
130 find_if(formatlist.begin(), formatlist.end(),
131 compare_memfun(&Format::name, name));
132 if (it != formatlist.end())
133 formatlist.erase(it);
139 sort(formatlist.begin(), formatlist.end());
143 void Formats::SetViewer(string const & name, string const & command)
146 FormatList::iterator it =
147 find_if(formatlist.begin(), formatlist.end(),
148 compare_memfun(&Format::name, name));
149 if (it != formatlist.end())
150 it->setViewer(command);
154 bool Formats::View(Buffer const * buffer, string const & filename,
155 string const & format_name) const
157 if (filename.empty())
160 Format const * format = GetFormat(format_name);
161 if (format && format->viewer().empty() &&
162 format->IsChildFormat())
163 format = GetFormat(format->ParentFormat());
164 if (!format || format->viewer().empty()) {
165 WriteAlert(_("Can not view file"),
166 _("No information for viewing ")
167 + PrettyName(format_name));
171 string command = format->viewer();
173 if (format_name == "dvi" &&
174 !lyxrc.view_dvi_paper_option.empty()) {
175 command += " " + lyxrc.view_dvi_paper_option;
176 command += " " + converters.dvi_papersize(buffer);
177 if (buffer->params.orientation
178 == BufferParams::ORIENTATION_LANDSCAPE)
182 string command2 = command + " " + OnlyFilename(filename);
183 lyxerr << "Executing command: " << command2 << endl;
184 ShowMessage(buffer, _("Executing command:"), command2);
186 command += " " + QuoteName(filename);
188 int res = one.startscript(Systemcalls::SystemDontWait, command);
191 WriteAlert(_("Can not view file"),
192 _("Error while executing"),
193 command2.substr(0, 50));
200 string const Formats::PrettyName(string const & name) const
202 Format const * format = GetFormat(name);
204 return format->prettyname();
210 string const Formats::Extension(string const & name) const
212 Format const * format = GetFormat(name);
214 return format->extension();
219 //////////////////////////////////////////////////////////////////////////////
221 void Converter::ReadFlags()
223 string flag_list(flags);
224 while (!flag_list.empty()) {
225 string flag_name, flag_value;
226 flag_list = split(flag_list, flag_value, ',');
227 flag_value = split(flag_value, flag_name, '=');
228 if (flag_name == "latex")
230 else if (flag_name == "originaldir")
232 else if (flag_name == "needaux")
234 else if (flag_name == "resultdir")
235 result_dir = (flag_value.empty())
236 ? token_base : flag_value;
237 else if (flag_name == "resultfile")
238 result_file = flag_value;
239 else if (flag_name == "parselog")
240 parselog = flag_value;
242 if (!result_dir.empty() && result_file.empty())
243 result_file = "index." + formats.Extension(to);
244 //if (!contains(command, token_from))
249 bool operator<(Converter const & a, Converter const & b)
251 int i = compare_no_case(a.From->prettyname(), b.From->prettyname());
253 return compare_no_case(a.To->prettyname(), b.To->prettyname())
259 //////////////////////////////////////////////////////////////////////////////
261 class compare_Converter {
263 compare_Converter(string const & f, string const & t)
265 bool operator()(Converter const & c) {
266 return c.from == from && c.to == to;
274 Converter const * Converters::GetConverter(string const & from,
277 ConverterList::const_iterator cit =
278 find_if(converterlist.begin(), converterlist.end(),
279 compare_Converter(from, to));
280 if (cit != converterlist.end())
287 int Converters::GetNumber(string const & from, string const & to)
289 ConverterList::const_iterator cit =
290 find_if(converterlist.begin(), converterlist.end(),
291 compare_Converter(from, to));
292 if (cit != converterlist.end())
293 return cit - converterlist.begin();
299 void Converters::Add(string const & from, string const & to,
300 string const & command, string const & flags)
304 ConverterList::iterator it = find_if(converterlist.begin(),
306 compare_Converter(from, to));
308 Converter converter(from, to, command, flags);
309 if (it != converterlist.end() && !flags.empty() && flags[0] == '*') {
311 converter.command = command;
312 converter.flags = flags;
314 converter.ReadFlags();
316 if (converter.latex && (latex_command.empty() || to == "dvi"))
317 latex_command = command;
318 // If we have both latex & pdflatex, we set latex_command to latex.
319 // The latex_command is used to update the .aux file when running
320 // a converter that uses it.
322 if (it == converterlist.end())
323 converterlist.push_back(converter);
325 converter.From = it->From;
326 converter.To = it->To;
332 void Converters::Delete(string const & from, string const & to)
334 ConverterList::iterator it = find_if(converterlist.begin(),
336 compare_Converter(from, to));
337 if (it != converterlist.end())
338 converterlist.erase(it);
342 // This method updates the pointers From and To in all the converters.
343 // The code is not very efficient, but it doesn't matter as the number
344 // of formats and converters is small.
345 // Furthermore, this method is called only on startup, or after
346 // adding/deleting a format in FormPreferences (the latter calls can be
347 // eliminated if the formats in the Formats class are stored using a map or
348 // a list (instead of a vector), but this will cause other problems).
349 void Converters::Update(Formats const & formats)
351 for (ConverterList::iterator it = converterlist.begin();
352 it != converterlist.end(); ++it) {
353 it->From = formats.GetFormat(it->from);
354 it->To = formats.GetFormat(it->to);
359 // This method updates the pointers From and To in the last converter.
360 // It is called when adding a new converter in FormPreferences
361 void Converters::UpdateLast(Formats const & formats)
363 if (converterlist.begin() != converterlist.end()) {
364 ConverterList::iterator it = converterlist.end()-1;
365 it->From = formats.GetFormat(it->from);
366 it->To = formats.GetFormat(it->to);
371 void Converters::Sort()
373 sort(converterlist.begin(), converterlist.end());
377 int Converters::BFS_init(string const & start, bool clear_visited)
379 int s = formats.GetNumber(start);
385 fill(visited.begin(), visited.end(), false);
386 if (visited[s] == false) {
394 vector<Format const *> const
395 Converters::GetReachableTo(string const & target, bool clear_visited)
397 vector<Format const *> result;
398 int s = BFS_init(target, clear_visited);
405 if (i != s || target != "lyx")
406 result.push_back(&formats.Get(i));
407 for (vector<int>::iterator it = vertices[i].in_vertices.begin();
408 it != vertices[i].in_vertices.end(); ++it)
419 vector<Format const *> const
420 Converters::GetReachable(string const & from, bool only_viewable,
423 vector<Format const *> result;
425 if (BFS_init(from, clear_visited) < 0)
431 Format const & format = formats.Get(i);
432 if (format.name() == "lyx")
434 if (!only_viewable || !format.viewer().empty() ||
435 format.IsChildFormat())
436 result.push_back(&format);
437 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
438 it != vertices[i].out_vertices.end(); ++it)
449 bool Converters::IsReachable(string const & from, string const & to)
454 int s = BFS_init(from);
455 int t = formats.GetNumber(to);
464 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
465 it != vertices[i].out_vertices.end(); ++it)
476 Converters::EdgePath const
477 Converters::GetPath(string const & from, string const & to)
483 int s = BFS_init(from);
484 int t = formats.GetNumber(to);
488 vector<int> prev_edge(formats.size());
489 vector<int> prev_vertex(formats.size());
499 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
500 it != vertices[i].out_vertices.end(); ++it)
505 int k = it - vertices[i].out_vertices.begin();
506 prev_edge[j] = vertices[i].out_edges[k];
514 path.push_back(prev_edge[t]);
517 reverse(path.begin(), path.end());
522 bool Converters::UsePdflatex(EdgePath const & path)
524 for (EdgePath::const_iterator cit = path.begin();
525 cit != path.end(); ++cit) {
526 Converter const & conv = converterlist[*cit];
528 return contains(conv.to, "pdf");
534 bool Converters::Convert(Buffer const * buffer,
535 string const & from_file, string const & to_file_base,
536 string const & from_format, string const & to_format,
539 to_file = ChangeExtension(to_file_base,
540 formats.Extension(to_format));
542 if (from_format == to_format)
543 if (from_file != to_file)
544 return lyx::rename(from_file, to_file);
548 EdgePath edgepath = GetPath(from_format, to_format);
549 if (edgepath.empty()) {
550 WriteAlert(_("Can not convert file"),
551 _("No information for converting from ")
552 + formats.PrettyName(from_format) + _(" to ")
553 + formats.PrettyName(to_format));
557 string path = OnlyPath(from_file);
560 bool run_latex = false;
561 string from_base = ChangeExtension(from_file, "");
562 string to_base = ChangeExtension(to_file, "");
564 string outfile = from_file;
565 for (EdgePath::const_iterator cit = edgepath.begin();
566 cit != edgepath.end(); ++cit) {
567 Converter const & conv = converterlist[*cit];
568 bool dummy = conv.To->dummy() && conv.to != "program";
570 lyxerr << "Converting from "
571 << conv.from << " to " << conv.to << endl;
573 outfile = conv.result_dir.empty()
574 ? ChangeExtension(from_file, conv.To->extension())
575 : AddName(subst(conv.result_dir,
576 token_base, from_base),
577 subst(conv.result_file,
578 token_base, OnlyFilename(from_base)));
582 string command = subst(conv.command, token_from, "");
583 lyxerr << "Running " << command << endl;
584 if (!runLaTeX(buffer, command))
587 if (conv.need_aux && !run_latex
588 && !latex_command.empty()) {
589 lyxerr << "Running " << latex_command
590 << " to update aux file"<< endl;
591 runLaTeX(buffer, latex_command);
594 string infile2 = (conv.original_dir)
595 ? infile : MakeRelPath(infile, path);
596 string outfile2 = (conv.original_dir)
597 ? outfile : MakeRelPath(outfile, path);
599 string command = conv.command;
600 command = subst(command, token_from, QuoteName(infile2));
601 command = subst(command, token_base, QuoteName(from_base));
602 command = subst(command, token_to, QuoteName(outfile2));
604 if (!conv.parselog.empty())
605 command += " 2> " + QuoteName(infile2 + ".out");
607 if (conv.from == "dvi" && conv.to == "ps")
608 command = add_options(command,
609 dvips_options(buffer));
611 lyxerr << "Calling " << command << endl;
613 ShowMessage(buffer, _("Executing command:"), command);
615 Systemcalls::Starttype type = (dummy)
616 ? Systemcalls::SystemDontWait : Systemcalls::System;
619 if (conv.original_dir && buffer) {
620 Path p(buffer->filepath);
621 res = one.startscript(type, command);
623 res = one.startscript(type, command);
625 if (!conv.parselog.empty()) {
626 string const logfile = infile2 + ".log";
627 string const command2 = conv.parselog +
628 " < " + QuoteName(infile2 + ".out") +
629 " > " + QuoteName(logfile);
630 one.startscript(Systemcalls::System, command2);
631 if (!scanLog(buffer, command, logfile))
636 if (conv.to == "program")
637 WriteAlert(_("There were errors during the Build process."),
638 _("You should try to fix them."));
640 WriteAlert(_("Can not convert file"),
641 "Error while executing",
642 command.substr(0, 50));
648 Converter const & conv = converterlist[edgepath.back()];
649 if (conv.To->dummy())
653 if (!conv.result_dir.empty()) {
654 to_file = AddName(subst(conv.result_dir, token_base, to_base),
655 subst(conv.result_file,
656 token_base, OnlyFilename(to_base)));
657 if (from_base != to_base) {
658 string from = subst(conv.result_dir,
659 token_base, from_base);
660 string to = subst(conv.result_dir,
661 token_base, to_base);
662 if (!lyx::rename(from, to)) {
663 WriteAlert(_("Error while trying to move directory:"),
668 } else if (outfile != to_file) {
669 bool moved = (conv.latex)
670 ? lyx::copy(outfile, to_file)
671 : lyx::rename(outfile, to_file);
673 WriteAlert(_("Error while trying to move file:"),
674 outfile, _("to ") + to_file);
683 bool Converters::Convert(Buffer const * buffer,
684 string const & from_file, string const & to_file_base,
685 string const & from_format, string const & to_format)
688 return Convert(buffer, from_file, to_file_base, from_format, to_format,
693 void Converters::BuildGraph()
695 vertices = vector<Vertex>(formats.size());
696 visited.resize(formats.size());
698 for (ConverterList::iterator it = converterlist.begin();
699 it != converterlist.end(); ++it) {
700 int s = formats.GetNumber(it->from);
701 int t = formats.GetNumber(it->to);
702 vertices[t].in_vertices.push_back(s);
703 vertices[s].out_vertices.push_back(t);
704 vertices[s].out_edges.push_back(it - converterlist.begin());
709 bool Converters::FormatIsUsed(string const & format)
711 for (ConverterList::const_iterator cit = converterlist.begin();
712 cit != converterlist.end(); ++cit)
713 if (cit->from == format || cit->to == format)
719 bool Converters::scanLog(Buffer const * buffer, string const & command,
720 string const & filename)
725 BufferView * bv = buffer->getUser();
726 bool need_redraw = false;
729 // Remove all error insets
730 need_redraw = bv->removeAutoInsets();
733 LaTeX latex("", filename, "");
735 int result = latex.scanLogFile(terr);
737 if ((result & LaTeX::ERRORS)) {
738 // Insert all errors as errors boxes
739 bv->insertErrors(terr);
744 bv->fitCursor(bv->text);
749 if ((result & LaTeX::ERRORS)) {
750 int num_errors = latex.getNumErrors();
753 if (num_errors == 1) {
754 s = _("One error detected");
755 t = _("You should try to fix it.");
757 s = tostr(num_errors);
758 s += _(" errors detected.");
759 t = _("You should try to fix them.");
762 split(command, head, ' ');
763 WriteAlert(_("There were errors during running of ") + head,
766 } else if (result & LaTeX::NO_OUTPUT) {
767 string const s = _("The operation resulted in");
768 string const t = _("an empty file.");
769 WriteAlert(_("Resulting file is empty"), s, t);
776 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
781 BufferView * bv = buffer->getUser();
782 string name = buffer->getLatexName();
783 bool need_redraw = false;
787 bv->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
788 // Remove all error insets
789 need_redraw = bv->removeAutoInsets();
793 // do the LaTex run(s)
795 LaTeX latex(command, name, buffer->filepath);
796 int result = latex.run(terr,
797 bv ? bv->owner()->getMiniBuffer() : 0);
801 if ((result & LaTeX::ERRORS)) {
802 // Insert all errors as errors boxes
803 bv->insertErrors(terr);
807 // if we removed error insets before we ran LaTeX or if we inserted
808 // error insets after we ran LaTeX this must be run:
811 bv->fitCursor(bv->text);
815 // check return value from latex.run().
816 if ((result & LaTeX::NO_LOGFILE)) {
817 WriteAlert(_("LaTeX did not work!"),
818 _("Missing log file:"), name);
819 } else if ((result & LaTeX::ERRORS)) {
820 int num_errors = latex.getNumErrors();
823 if (num_errors == 1) {
824 s = _("One error detected");
825 t = _("You should try to fix it.");
827 s = tostr(num_errors);
828 s += _(" errors detected.");
829 t = _("You should try to fix them.");
831 WriteAlert(_("There were errors during the LaTeX run."),
833 } else if (result & LaTeX::NO_OUTPUT) {
834 string const s = _("The operation resulted in");
835 string const t = _("an empty file.");
836 WriteAlert(_("Resulting file is empty"), s, t);
842 int const ERROR_MASK =
847 return (result & ERROR_MASK) == 0;
852 string const Converters::dvi_papersize(Buffer const * buffer)
854 char real_papersize = buffer->params.papersize;
855 if (real_papersize == BufferParams::PAPER_DEFAULT)
856 real_papersize = lyxrc.default_papersize;
858 switch (real_papersize) {
859 case BufferParams::PAPER_A3PAPER:
861 case BufferParams::PAPER_A4PAPER:
863 case BufferParams::PAPER_A5PAPER:
865 case BufferParams::PAPER_B5PAPER:
867 case BufferParams::PAPER_EXECUTIVEPAPER:
869 case BufferParams::PAPER_LEGALPAPER:
871 case BufferParams::PAPER_USLETTER:
878 string const Converters::dvips_options(Buffer const * buffer)
884 if (buffer->params.use_geometry
885 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
886 && !lyxrc.print_paper_dimension_flag.empty()
887 && !buffer->params.paperwidth.empty()
888 && !buffer->params.paperheight.empty()) {
889 // using a custom papersize
890 result = lyxrc.print_paper_dimension_flag;
891 result += ' ' + buffer->params.paperwidth;
892 result += ',' + buffer->params.paperheight;
894 string paper_option = dvi_papersize(buffer);
895 if (paper_option == "us")
896 paper_option = "letter";
897 if (paper_option != "letter" ||
898 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
899 // dvips won't accept -t letter -t landscape. In all other
900 // cases, include the paper size explicitly.
901 result = lyxrc.print_paper_flag;
902 result += ' ' + paper_option;
905 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
906 result += ' ' + lyxrc.print_landscape_flag;
910 vector<Converters::Vertex> Converters::vertices;
913 /// The global instance
915 Converters converters;
917 // The global copy after reading lyxrc.defaults
918 Formats system_formats;
919 Converters system_converters;