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 "lyx_gui_misc.h"
29 #include "lyx_cb.h" // ShowMessage()
30 #include "support/lyxfunctional.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 << "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 << "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 << "Running " << command << endl;
591 if (!runLaTeX(buffer, command))
594 if (conv.need_aux && !run_latex
595 && !latex_command.empty()) {
596 lyxerr << "Running " << latex_command
597 << " to update aux file"<< endl;
598 runLaTeX(buffer, latex_command);
601 string infile2 = (conv.original_dir)
602 ? infile : MakeRelPath(infile, path);
603 string outfile2 = (conv.original_dir)
604 ? outfile : MakeRelPath(outfile, path);
606 string command = conv.command;
607 command = subst(command, token_from, QuoteName(infile2));
608 command = subst(command, token_base, QuoteName(from_base));
609 command = subst(command, token_to, QuoteName(outfile2));
611 if (!conv.parselog.empty())
612 command += " 2> " + QuoteName(infile2 + ".out");
614 if (conv.from == "dvi" && conv.to == "ps")
615 command = add_options(command,
616 dvips_options(buffer));
617 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
618 command = add_options(command,
619 dvipdfm_options(buffer));
621 lyxerr << "Calling " << command << endl;
623 ShowMessage(buffer, _("Executing command:"), command);
625 Systemcalls::Starttype type = (dummy)
626 ? Systemcalls::SystemDontWait : Systemcalls::System;
629 if (conv.original_dir && buffer) {
630 Path p(buffer->filepath);
631 res = one.startscript(type, command);
633 res = one.startscript(type, command);
635 if (!conv.parselog.empty()) {
636 string const logfile = infile2 + ".log";
637 string const command2 = conv.parselog +
638 " < " + QuoteName(infile2 + ".out") +
639 " > " + QuoteName(logfile);
640 one.startscript(Systemcalls::System, command2);
641 if (!scanLog(buffer, command, logfile))
646 if (conv.to == "program")
647 WriteAlert(_("There were errors during the Build process."),
648 _("You should try to fix them."));
650 WriteAlert(_("Can not convert file"),
651 "Error while executing",
652 command.substr(0, 50));
658 Converter const & conv = converterlist[edgepath.back()];
659 if (conv.To->dummy())
663 if (!conv.result_dir.empty()) {
664 to_file = AddName(subst(conv.result_dir, token_base, to_base),
665 subst(conv.result_file,
666 token_base, OnlyFilename(to_base)));
667 if (from_base != to_base) {
668 string from = subst(conv.result_dir,
669 token_base, from_base);
670 string to = subst(conv.result_dir,
671 token_base, to_base);
672 if (!lyx::rename(from, to)) {
673 WriteAlert(_("Error while trying to move directory:"),
680 return Move(outfile, to_file, conv.latex);
683 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
684 // moves each /path/file*.ext file to /path2/file2*.ext2'
685 bool Converters::Move(string const & from, string const & to, bool copy)
690 bool no_errors = true;
691 string const path = OnlyPath(from);
692 string const base = OnlyFilename(ChangeExtension(from, ""));
693 string const to_base = ChangeExtension(to, "");
694 string const to_extension = GetExtension(to);
696 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
697 for (vector<string>::const_iterator it = files.begin();
698 it != files.end(); ++it)
699 if (prefixIs(*it, base)) {
700 string from2 = path + *it;
701 string to2 = to_base + (*it).substr(base.length());
702 to2 = ChangeExtension(to2, to_extension);
703 lyxerr << "moving " << from2 << " to " << to2 << endl;
705 ? lyx::copy(from2, to2)
706 : lyx::rename(from2, to2);
707 if (!moved && no_errors) {
708 WriteAlert(_("Error while trying to move file:"),
709 from2, _("to ") + to2);
716 bool Converters::Convert(Buffer const * buffer,
717 string const & from_file, string const & to_file_base,
718 string const & from_format, string const & to_format)
721 return Convert(buffer, from_file, to_file_base, from_format, to_format,
727 void Converters::BuildGraph()
729 vertices = vector<Vertex>(formats.size());
730 visited.resize(formats.size());
732 for (ConverterList::iterator it = converterlist.begin();
733 it != converterlist.end(); ++it) {
734 int const s = formats.GetNumber(it->from);
735 int const t = formats.GetNumber(it->to);
736 vertices[t].in_vertices.push_back(s);
737 vertices[s].out_vertices.push_back(t);
738 vertices[s].out_edges.push_back(it - converterlist.begin());
743 bool Converters::FormatIsUsed(string const & format)
745 for (ConverterList::const_iterator cit = converterlist.begin();
746 cit != converterlist.end(); ++cit)
747 if (cit->from == format || cit->to == format)
753 bool Converters::scanLog(Buffer const * buffer, string const & command,
754 string const & filename)
759 BufferView * bv = buffer->getUser();
760 bool need_redraw = false;
763 // Remove all error insets
764 need_redraw = bv->removeAutoInsets();
767 LaTeX latex("", filename, "");
769 int result = latex.scanLogFile(terr);
771 if ((result & LaTeX::ERRORS)) {
772 // Insert all errors as errors boxes
773 bv->insertErrors(terr);
778 bv->fitCursor(bv->text);
783 if ((result & LaTeX::ERRORS)) {
784 int num_errors = latex.getNumErrors();
787 if (num_errors == 1) {
788 s = _("One error detected");
789 t = _("You should try to fix it.");
791 s = tostr(num_errors);
792 s += _(" errors detected.");
793 t = _("You should try to fix them.");
796 split(command, head, ' ');
797 WriteAlert(_("There were errors during running of ") + head,
800 } else if (result & LaTeX::NO_OUTPUT) {
801 string const s = _("The operation resulted in");
802 string const t = _("an empty file.");
803 WriteAlert(_("Resulting file is empty"), s, t);
810 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
815 BufferView * bv = buffer->getUser();
816 string name = buffer->getLatexName();
817 bool need_redraw = false;
821 bv->owner()->getLyXFunc()->Dispatch(LFUN_MESSAGE,
822 _("Running LaTeX..."));
823 // Remove all error insets
824 need_redraw = bv->removeAutoInsets();
828 // do the LaTex run(s)
830 LaTeX latex(command, name, buffer->filepath);
831 int result = latex.run(terr,
832 bv ? bv->owner()->getLyXFunc() : 0);
836 if ((result & LaTeX::ERRORS)) {
837 // Insert all errors as errors boxes
838 bv->insertErrors(terr);
842 // if we removed error insets before we ran LaTeX or if we inserted
843 // error insets after we ran LaTeX this must be run:
846 bv->fitCursor(bv->text);
850 // check return value from latex.run().
851 if ((result & LaTeX::NO_LOGFILE)) {
852 WriteAlert(_("LaTeX did not work!"),
853 _("Missing log file:"), name);
854 } else if ((result & LaTeX::ERRORS)) {
855 int num_errors = latex.getNumErrors();
858 if (num_errors == 1) {
859 s = _("One error detected");
860 t = _("You should try to fix it.");
862 s = tostr(num_errors);
863 s += _(" errors detected.");
864 t = _("You should try to fix them.");
866 WriteAlert(_("There were errors during the LaTeX run."),
868 } else if (result & LaTeX::NO_OUTPUT) {
869 string const s = _("The operation resulted in");
870 string const t = _("an empty file.");
871 WriteAlert(_("Resulting file is empty"), s, t);
877 int const ERROR_MASK =
882 return (result & ERROR_MASK) == 0;
887 string const Converters::papersize(Buffer const * buffer)
889 char real_papersize = buffer->params.papersize;
890 if (real_papersize == BufferParams::PAPER_DEFAULT)
891 real_papersize = lyxrc.default_papersize;
893 switch (real_papersize) {
894 case BufferParams::PAPER_A3PAPER:
896 case BufferParams::PAPER_A4PAPER:
898 case BufferParams::PAPER_A5PAPER:
900 case BufferParams::PAPER_B5PAPER:
902 case BufferParams::PAPER_EXECUTIVEPAPER:
904 case BufferParams::PAPER_LEGALPAPER:
906 case BufferParams::PAPER_USLETTER:
913 string const Converters::dvips_options(Buffer const * buffer)
919 if (buffer->params.use_geometry
920 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
921 && !lyxrc.print_paper_dimension_flag.empty()
922 && !buffer->params.paperwidth.empty()
923 && !buffer->params.paperheight.empty()) {
924 // using a custom papersize
925 result = lyxrc.print_paper_dimension_flag;
926 result += ' ' + buffer->params.paperwidth;
927 result += ',' + buffer->params.paperheight;
929 string paper_option = papersize(buffer);
930 if (paper_option != "letter" ||
931 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
932 // dvips won't accept -t letter -t landscape. In all other
933 // cases, include the paper size explicitly.
934 result = lyxrc.print_paper_flag;
935 result += ' ' + paper_option;
938 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
939 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
940 result += ' ' + lyxrc.print_landscape_flag;
945 string const Converters::dvipdfm_options(Buffer const * buffer)
951 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
952 string paper_size = papersize(buffer);
953 if (paper_size != "b5" && paper_size != "foolscap")
954 result = "-p "+ paper_size;
956 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
964 vector<Converters::Vertex> Converters::vertices;
967 /// The global instance
969 Converters converters;
971 // The global copy after reading lyxrc.defaults
972 Formats system_formats;
973 Converters system_converters;