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"
44 string const token_from("$$i");
45 string const token_base("$$b");
46 string const token_to("$$o");
48 //////////////////////////////////////////////////////////////////////////////
51 string const add_options(string const & command, string const & options)
54 string const tail = split(command, head, ' ');
55 return head + ' ' + options + ' ' + tail;
60 //////////////////////////////////////////////////////////////////////////////
62 bool Format::dummy() const
64 return extension().empty();
68 bool Format::IsChildFormat() const
72 return isdigit(name_[name_.length() - 1]);
76 string const Format::ParentFormat() const
78 return name_.substr(0, name_.length() - 1);
81 //////////////////////////////////////////////////////////////////////////////
83 // This method should return a reference, and throw an exception
84 // if the format named name cannot be found (Lgb)
85 Format const * Formats::GetFormat(string const & name) const
87 FormatList::const_iterator cit =
88 find_if(formatlist.begin(), formatlist.end(),
89 lyx::compare_memfun(&Format::name, name));
90 if (cit != formatlist.end())
97 int Formats::GetNumber(string const & name) const
99 FormatList::const_iterator cit =
100 find_if(formatlist.begin(), formatlist.end(),
101 lyx::compare_memfun(&Format::name, name));
102 if (cit != formatlist.end())
103 return cit - formatlist.begin();
109 void Formats::Add(string const & name)
111 if (!GetFormat(name))
112 Add(name, name, name, string());
116 void Formats::Add(string const & name, string const & extension,
117 string const & prettyname, string const & shortcut)
119 FormatList::iterator it =
120 find_if(formatlist.begin(), formatlist.end(),
121 lyx::compare_memfun(&Format::name, name));
122 if (it == formatlist.end())
123 formatlist.push_back(Format(name, extension, prettyname,
126 string viewer = it->viewer();
127 *it = Format(name, extension, prettyname, shortcut, viewer);
132 void Formats::Delete(string const & name)
134 FormatList::iterator it =
135 find_if(formatlist.begin(), formatlist.end(),
136 lyx::compare_memfun(&Format::name, name));
137 if (it != formatlist.end())
138 formatlist.erase(it);
144 sort(formatlist.begin(), formatlist.end());
148 void Formats::SetViewer(string const & name, string const & command)
151 FormatList::iterator it =
152 find_if(formatlist.begin(), formatlist.end(),
153 lyx::compare_memfun(&Format::name, name));
154 if (it != formatlist.end())
155 it->setViewer(command);
159 bool Formats::View(Buffer const * buffer, string const & filename,
160 string const & format_name) const
162 if (filename.empty())
165 Format const * format = GetFormat(format_name);
166 if (format && format->viewer().empty() &&
167 format->IsChildFormat())
168 format = GetFormat(format->ParentFormat());
169 if (!format || format->viewer().empty()) {
170 WriteAlert(_("Can not view file"),
171 _("No information for viewing ")
172 + PrettyName(format_name));
176 string command = format->viewer();
178 if (format_name == "dvi" &&
179 !lyxrc.view_dvi_paper_option.empty()) {
180 command += " " + lyxrc.view_dvi_paper_option;
181 string paper_size = converters.papersize(buffer);
182 if (paper_size == "letter")
184 command += " " + paper_size;
185 if (buffer->params.orientation
186 == BufferParams::ORIENTATION_LANDSCAPE)
190 command += " " + QuoteName(OnlyFilename((filename)));
192 lyxerr[Debug::FILES] << "Executing command: " << command << endl;
193 ShowMessage(buffer, _("Executing command:"), command);
195 Path p(OnlyPath(filename));
197 int const res = one.startscript(Systemcalls::SystemDontWait, command);
200 WriteAlert(_("Can not view file"),
201 _("Error while executing"),
202 command.substr(0, 50));
209 string const Formats::PrettyName(string const & name) const
211 Format const * format = GetFormat(name);
213 return format->prettyname();
219 string const Formats::Extension(string const & name) const
221 Format const * format = GetFormat(name);
223 return format->extension();
228 //////////////////////////////////////////////////////////////////////////////
230 void Converter::ReadFlags()
232 string flag_list(flags);
233 while (!flag_list.empty()) {
234 string flag_name, flag_value;
235 flag_list = split(flag_list, flag_value, ',');
236 flag_value = split(flag_value, flag_name, '=');
237 if (flag_name == "latex")
239 else if (flag_name == "originaldir")
241 else if (flag_name == "needaux")
243 else if (flag_name == "resultdir")
244 result_dir = (flag_value.empty())
245 ? token_base : flag_value;
246 else if (flag_name == "resultfile")
247 result_file = flag_value;
248 else if (flag_name == "parselog")
249 parselog = flag_value;
251 if (!result_dir.empty() && result_file.empty())
252 result_file = "index." + formats.Extension(to);
253 //if (!contains(command, token_from))
258 bool operator<(Converter const & a, Converter const & b)
260 int const i = compare_no_case(a.From->prettyname(),
261 b.From->prettyname());
263 return compare_no_case(a.To->prettyname(), b.To->prettyname())
269 //////////////////////////////////////////////////////////////////////////////
271 class compare_Converter {
273 compare_Converter(string const & f, string const & t)
275 bool operator()(Converter const & c) {
276 return c.from == from && c.to == to;
284 Converter const * Converters::GetConverter(string const & from,
287 ConverterList::const_iterator cit =
288 find_if(converterlist.begin(), converterlist.end(),
289 compare_Converter(from, to));
290 if (cit != converterlist.end())
297 int Converters::GetNumber(string const & from, string const & to)
299 ConverterList::const_iterator cit =
300 find_if(converterlist.begin(), converterlist.end(),
301 compare_Converter(from, to));
302 if (cit != converterlist.end())
303 return cit - converterlist.begin();
309 void Converters::Add(string const & from, string const & to,
310 string const & command, string const & flags)
314 ConverterList::iterator it = find_if(converterlist.begin(),
316 compare_Converter(from, to));
318 Converter converter(from, to, command, flags);
319 if (it != converterlist.end() && !flags.empty() && flags[0] == '*') {
321 converter.command = command;
322 converter.flags = flags;
324 converter.ReadFlags();
326 if (converter.latex && (latex_command.empty() || to == "dvi"))
327 latex_command = subst(command, token_from, "");
328 // If we have both latex & pdflatex, we set latex_command to latex.
329 // The latex_command is used to update the .aux file when running
330 // a converter that uses it.
332 if (it == converterlist.end())
333 converterlist.push_back(converter);
335 converter.From = it->From;
336 converter.To = it->To;
342 void Converters::Delete(string const & from, string const & to)
344 ConverterList::iterator it = find_if(converterlist.begin(),
346 compare_Converter(from, to));
347 if (it != converterlist.end())
348 converterlist.erase(it);
352 // This method updates the pointers From and To in all the converters.
353 // The code is not very efficient, but it doesn't matter as the number
354 // of formats and converters is small.
355 // Furthermore, this method is called only on startup, or after
356 // adding/deleting a format in FormPreferences (the latter calls can be
357 // eliminated if the formats in the Formats class are stored using a map or
358 // a list (instead of a vector), but this will cause other problems).
359 void Converters::Update(Formats const & formats)
361 for (ConverterList::iterator it = converterlist.begin();
362 it != converterlist.end(); ++it) {
363 it->From = formats.GetFormat(it->from);
364 it->To = formats.GetFormat(it->to);
369 // This method updates the pointers From and To in the last converter.
370 // It is called when adding a new converter in FormPreferences
371 void Converters::UpdateLast(Formats const & formats)
373 if (converterlist.begin() != converterlist.end()) {
374 ConverterList::iterator it = converterlist.end()-1;
375 it->From = formats.GetFormat(it->from);
376 it->To = formats.GetFormat(it->to);
381 void Converters::Sort()
383 sort(converterlist.begin(), converterlist.end());
387 int Converters::BFS_init(string const & start, bool clear_visited)
389 int const s = formats.GetNumber(start);
395 fill(visited.begin(), visited.end(), false);
396 if (visited[s] == false) {
404 vector<Format const *> const
405 Converters::GetReachableTo(string const & target, bool clear_visited)
407 vector<Format const *> result;
408 int const s = BFS_init(target, clear_visited);
413 int const i = Q.front();
415 if (i != s || target != "lyx")
416 result.push_back(&formats.Get(i));
417 for (vector<int>::iterator it = vertices[i].in_vertices.begin();
418 it != vertices[i].in_vertices.end(); ++it)
429 vector<Format const *> const
430 Converters::GetReachable(string const & from, bool only_viewable,
433 vector<Format const *> result;
435 if (BFS_init(from, clear_visited) < 0)
439 int const i = Q.front();
441 Format const & format = formats.Get(i);
442 if (format.name() == "lyx")
444 if (!only_viewable || !format.viewer().empty() ||
445 format.IsChildFormat())
446 result.push_back(&format);
447 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
448 it != vertices[i].out_vertices.end(); ++it)
459 bool Converters::IsReachable(string const & from, string const & to)
464 int const s = BFS_init(from);
465 int const t = formats.GetNumber(to);
470 int const i = Q.front();
474 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
475 it != vertices[i].out_vertices.end(); ++it)
486 Converters::EdgePath const
487 Converters::GetPath(string const & from, string const & to)
493 int const s = BFS_init(from);
494 int t = formats.GetNumber(to);
498 vector<int> prev_edge(formats.size());
499 vector<int> prev_vertex(formats.size());
503 int const i = Q.front();
509 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
510 it != vertices[i].out_vertices.end(); ++it)
515 int const k = it - vertices[i].out_vertices.begin();
516 prev_edge[j] = vertices[i].out_edges[k];
524 path.push_back(prev_edge[t]);
527 reverse(path.begin(), path.end());
532 bool Converters::UsePdflatex(EdgePath const & path)
534 for (EdgePath::const_iterator cit = path.begin();
535 cit != path.end(); ++cit) {
536 Converter const & conv = converterlist[*cit];
538 return contains(conv.to, "pdf");
544 bool Converters::Convert(Buffer const * buffer,
545 string const & from_file, string const & to_file_base,
546 string const & from_format, string const & to_format,
549 to_file = ChangeExtension(to_file_base,
550 formats.Extension(to_format));
552 if (from_format == to_format)
553 return Move(from_file, to_file, false);
555 EdgePath edgepath = GetPath(from_format, to_format);
556 if (edgepath.empty()) {
557 WriteAlert(_("Can not convert file"),
558 _("No information for converting from ")
559 + formats.PrettyName(from_format) + _(" to ")
560 + formats.PrettyName(to_format));
564 string path = OnlyPath(from_file);
567 bool run_latex = false;
568 string from_base = ChangeExtension(from_file, "");
569 string to_base = ChangeExtension(to_file, "");
571 string outfile = from_file;
572 for (EdgePath::const_iterator cit = edgepath.begin();
573 cit != edgepath.end(); ++cit) {
574 Converter const & conv = converterlist[*cit];
575 bool dummy = conv.To->dummy() && conv.to != "program";
577 lyxerr[Debug::FILES] << "Converting from "
578 << conv.from << " to " << conv.to << endl;
580 outfile = conv.result_dir.empty()
581 ? ChangeExtension(from_file, conv.To->extension())
582 : AddName(subst(conv.result_dir,
583 token_base, from_base),
584 subst(conv.result_file,
585 token_base, OnlyFilename(from_base)));
589 string command = subst(conv.command, token_from, "");
590 lyxerr[Debug::FILES] << "Running " << command << endl;
591 if (!runLaTeX(buffer, command))
594 if (conv.need_aux && !run_latex
595 && !latex_command.empty()) {
597 << "Running " << latex_command
598 << " to update aux file"<< endl;
599 runLaTeX(buffer, latex_command);
602 string infile2 = (conv.original_dir)
603 ? infile : MakeRelPath(infile, path);
604 string outfile2 = (conv.original_dir)
605 ? outfile : MakeRelPath(outfile, path);
607 string command = conv.command;
608 command = subst(command, token_from, QuoteName(infile2));
609 command = subst(command, token_base, QuoteName(from_base));
610 command = subst(command, token_to, QuoteName(outfile2));
612 if (!conv.parselog.empty())
613 command += " 2> " + QuoteName(infile2 + ".out");
615 if (conv.from == "dvi" && conv.to == "ps")
616 command = add_options(command,
617 dvips_options(buffer));
618 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
619 command = add_options(command,
620 dvipdfm_options(buffer));
622 lyxerr[Debug::FILES] << "Calling " << command << endl;
624 ShowMessage(buffer, _("Executing command:"), command);
626 Systemcalls::Starttype type = (dummy)
627 ? Systemcalls::SystemDontWait : Systemcalls::System;
630 if (conv.original_dir && buffer) {
631 Path p(buffer->filepath);
632 res = one.startscript(type, command);
634 res = one.startscript(type, command);
636 if (!conv.parselog.empty()) {
637 string const logfile = infile2 + ".log";
638 string const command2 = conv.parselog +
639 " < " + QuoteName(infile2 + ".out") +
640 " > " + QuoteName(logfile);
641 one.startscript(Systemcalls::System, command2);
642 if (!scanLog(buffer, command, logfile))
647 if (conv.to == "program")
648 WriteAlert(_("There were errors during the Build process."),
649 _("You should try to fix them."));
651 WriteAlert(_("Can not convert file"),
652 "Error while executing",
653 command.substr(0, 50));
659 Converter const & conv = converterlist[edgepath.back()];
660 if (conv.To->dummy())
664 if (!conv.result_dir.empty()) {
665 to_file = AddName(subst(conv.result_dir, token_base, to_base),
666 subst(conv.result_file,
667 token_base, OnlyFilename(to_base)));
668 if (from_base != to_base) {
669 string from = subst(conv.result_dir,
670 token_base, from_base);
671 string to = subst(conv.result_dir,
672 token_base, to_base);
673 if (!lyx::rename(from, to)) {
674 WriteAlert(_("Error while trying to move directory:"),
681 return Move(outfile, to_file, conv.latex);
684 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
685 // moves each /path/file*.ext file to /path2/file2*.ext2'
686 bool Converters::Move(string const & from, string const & to, bool copy)
691 bool no_errors = true;
692 string const path = OnlyPath(from);
693 string const base = OnlyFilename(ChangeExtension(from, ""));
694 string const to_base = ChangeExtension(to, "");
695 string const to_extension = GetExtension(to);
697 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
698 for (vector<string>::const_iterator it = files.begin();
699 it != files.end(); ++it)
700 if (prefixIs(*it, base)) {
701 string from2 = path + *it;
702 string to2 = to_base + it->substr(base.length());
703 to2 = ChangeExtension(to2, to_extension);
704 lyxerr[Debug::FILES] << "moving " << from2
705 << " to " << to2 << endl;
707 ? lyx::copy(from2, to2)
708 : lyx::rename(from2, to2);
709 if (!moved && no_errors) {
710 WriteAlert(_("Error while trying to move file:"),
711 from2, _("to ") + to2);
718 bool Converters::Convert(Buffer const * buffer,
719 string const & from_file, string const & to_file_base,
720 string const & from_format, string const & to_format)
723 return Convert(buffer, from_file, to_file_base, from_format, to_format,
729 void Converters::BuildGraph()
731 vertices = vector<Vertex>(formats.size());
732 visited.resize(formats.size());
734 for (ConverterList::iterator it = converterlist.begin();
735 it != converterlist.end(); ++it) {
736 int const s = formats.GetNumber(it->from);
737 int const t = formats.GetNumber(it->to);
738 vertices[t].in_vertices.push_back(s);
739 vertices[s].out_vertices.push_back(t);
740 vertices[s].out_edges.push_back(it - converterlist.begin());
745 bool Converters::FormatIsUsed(string const & format)
747 for (ConverterList::const_iterator cit = converterlist.begin();
748 cit != converterlist.end(); ++cit)
749 if (cit->from == format || cit->to == format)
755 bool Converters::scanLog(Buffer const * buffer, string const & command,
756 string const & filename)
761 BufferView * bv = buffer->getUser();
762 bool need_redraw = false;
764 bv->owner()->prohibitInput();
765 // Remove all error insets
766 need_redraw = bv->removeAutoInsets();
769 LaTeX latex("", filename, "");
771 int result = latex.scanLogFile(terr);
773 if ((result & LaTeX::ERRORS)) {
774 // Insert all errors as errors boxes
775 bv->insertErrors(terr);
780 bv->fitCursor(bv->text);
782 bv->owner()->allowInput();
785 if ((result & LaTeX::ERRORS)) {
786 int num_errors = latex.getNumErrors();
789 if (num_errors == 1) {
790 s = _("One error detected");
791 t = _("You should try to fix it.");
793 s = tostr(num_errors);
794 s += _(" errors detected.");
795 t = _("You should try to fix them.");
798 split(command, head, ' ');
799 WriteAlert(_("There were errors during running of ") + head,
802 } else if (result & LaTeX::NO_OUTPUT) {
803 string const s = _("The operation resulted in");
804 string const t = _("an empty file.");
805 WriteAlert(_("Resulting file is empty"), s, t);
812 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
817 BufferView * bv = buffer->getUser();
818 string name = buffer->getLatexName();
819 bool need_redraw = false;
822 bv->owner()->prohibitInput();
823 bv->owner()->message(_("Running LaTeX..."));
824 // Remove all error insets
825 need_redraw = bv->removeAutoInsets();
829 // do the LaTex run(s)
831 LaTeX latex(command, name, buffer->filepath);
832 int result = latex.run(terr,
833 bv ? bv->owner()->getLyXFunc() : 0);
837 if ((result & LaTeX::ERRORS)) {
838 // Insert all errors as errors boxes
839 bv->insertErrors(terr);
843 // if we removed error insets before we ran LaTeX or if we inserted
844 // error insets after we ran LaTeX this must be run:
847 bv->fitCursor(bv->text);
851 // check return value from latex.run().
852 if ((result & LaTeX::NO_LOGFILE)) {
853 WriteAlert(_("LaTeX did not work!"),
854 _("Missing log file:"), name);
855 } else if ((result & LaTeX::ERRORS)) {
856 int num_errors = latex.getNumErrors();
859 if (num_errors == 1) {
860 s = _("One error detected");
861 t = _("You should try to fix it.");
863 s = tostr(num_errors);
864 s += _(" errors detected.");
865 t = _("You should try to fix them.");
867 WriteAlert(_("There were errors during the LaTeX run."),
869 } else if (result & LaTeX::NO_OUTPUT) {
870 string const s = _("The operation resulted in");
871 string const t = _("an empty file.");
872 WriteAlert(_("Resulting file is empty"), s, t);
876 bv->owner()->allowInput();
878 int const ERROR_MASK =
883 return (result & ERROR_MASK) == 0;
888 string const Converters::papersize(Buffer const * buffer)
890 char real_papersize = buffer->params.papersize;
891 if (real_papersize == BufferParams::PAPER_DEFAULT)
892 real_papersize = lyxrc.default_papersize;
894 switch (real_papersize) {
895 case BufferParams::PAPER_A3PAPER:
897 case BufferParams::PAPER_A4PAPER:
899 case BufferParams::PAPER_A5PAPER:
901 case BufferParams::PAPER_B5PAPER:
903 case BufferParams::PAPER_EXECUTIVEPAPER:
905 case BufferParams::PAPER_LEGALPAPER:
907 case BufferParams::PAPER_USLETTER:
914 string const Converters::dvips_options(Buffer const * buffer)
920 if (buffer->params.use_geometry
921 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
922 && !lyxrc.print_paper_dimension_flag.empty()
923 && !buffer->params.paperwidth.empty()
924 && !buffer->params.paperheight.empty()) {
925 // using a custom papersize
926 result = lyxrc.print_paper_dimension_flag;
927 result += ' ' + buffer->params.paperwidth;
928 result += ',' + buffer->params.paperheight;
930 string paper_option = papersize(buffer);
931 if (paper_option != "letter" ||
932 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
933 // dvips won't accept -t letter -t landscape. In all other
934 // cases, include the paper size explicitly.
935 result = lyxrc.print_paper_flag;
936 result += ' ' + paper_option;
939 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
940 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
941 result += ' ' + lyxrc.print_landscape_flag;
946 string const Converters::dvipdfm_options(Buffer const * buffer)
952 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
953 string paper_size = papersize(buffer);
954 if (paper_size != "b5" && paper_size != "foolscap")
955 result = "-p "+ paper_size;
957 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
965 vector<Converters::Vertex> Converters::vertices;
968 /// The global instance
970 Converters converters;
972 // The global copy after reading lyxrc.defaults
973 Formats system_formats;
974 Converters system_converters;