]> git.lyx.org Git - lyx.git/blob - src/exporter.C
Fix strange bibtex problem by converting some more functions to use FileName
[lyx.git] / src / exporter.C
1 /**
2  * \file exporter.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author Alfredo Braunstein
8  * \author Lars Gullik Bjønnes
9  * \author Jean Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "exporter.h"
20
21 #include "buffer.h"
22 #include "buffer_funcs.h"
23 #include "bufferparams.h"
24 #include "converter.h"
25 #include "format.h"
26 #include "gettext.h"
27 #include "lyxrc.h"
28 #include "mover.h"
29 #include "output_plaintext.h"
30 #include "outputparams.h"
31 #include "frontends/Alert.h"
32
33 #include "support/filetools.h"
34 #include "support/lyxlib.h"
35 #include "support/package.h"
36
37 #include <boost/filesystem/operations.hpp>
38
39
40 namespace lyx {
41
42 using support::addName;
43 using support::bformat;
44 using support::changeExtension;
45 using support::contains;
46 using support::FileName;
47 using support::makeAbsPath;
48 using support::makeDisplayPath;
49 using support::onlyFilename;
50 using support::onlyPath;
51 using support::package;
52 using support::prefixIs;
53
54 using std::find;
55 using std::string;
56 using std::vector;
57
58 namespace Alert = frontend::Alert;
59 namespace fs = boost::filesystem;
60
61 namespace {
62
63 vector<string> const Backends(Buffer const & buffer)
64 {
65         vector<string> v;
66         if (buffer.params().getLyXTextClass().isTeXClassAvailable()) {
67                 v.push_back(bufferFormat(buffer));
68                 // FIXME: Don't hardcode format names here, but use a flag
69                 if (v.back() == "latex")
70                         v.push_back("pdflatex");
71         }
72         v.push_back("text");
73         v.push_back("lyx");
74         return v;
75 }
76
77
78 /// ask the user what to do if a file already exists
79 int checkOverwrite(FileName const & filename)
80 {
81         if (fs::exists(filename.toFilesystemEncoding())) {
82                 docstring text = bformat(_("The file %1$s already exists.\n\n"
83                                                      "Do you want to over-write that file?"),
84                                       makeDisplayPath(filename.absFilename()));
85                 return Alert::prompt(_("Over-write file?"),
86                                      text, 0, 2,
87                                      _("&Over-write"), _("Over-write &all"),
88                                      _("&Cancel export"));
89         }
90         return 0;
91 }
92
93
94 enum CopyStatus {
95         SUCCESS,
96         FORCE,
97         CANCEL
98 };
99
100
101 /** copy file \p sourceFile to \p destFile. If \p force is false, the user
102  *  will be asked before existing files are overwritten.
103  *  \return
104  *  - SUCCESS if this file got copied
105  *  - FORCE   if subsequent calls should not ask for confirmation before
106  *            overwriting files anymore.
107  *  - CANCEL  if the export should be cancelled
108  */
109 CopyStatus copyFile(string const & format,
110                     FileName const & sourceFile, FileName const & destFile,
111                     string const & latexFile, bool force)
112 {
113         CopyStatus ret = force ? FORCE : SUCCESS;
114
115         // Only copy files that are in our tmp dir, all other files would
116         // overwrite themselves. This check could be changed to
117         // boost::filesystem::equivalent(sourceFile, destFile) if export to
118         // other directories than the document directory is desired.
119         if (!prefixIs(onlyPath(sourceFile.absFilename()), package().temp_dir()))
120                 return ret;
121
122         if (!force) {
123                 switch(checkOverwrite(destFile)) {
124                 case 0:
125                         ret = SUCCESS;
126                         break;
127                 case 1:
128                         ret = FORCE;
129                         break;
130                 default:
131                         return CANCEL;
132                 }
133         }
134
135         Mover const & mover = movers(format);
136         if (!mover.copy(sourceFile, destFile, latexFile))
137                 Alert::error(_("Couldn't copy file"),
138                              bformat(_("Copying %1$s to %2$s failed."),
139                                      makeDisplayPath(sourceFile.absFilename()),
140                                      makeDisplayPath(destFile.absFilename())));
141
142         return ret;
143 }
144
145 } //namespace anon
146
147
148 bool Exporter::Export(Buffer * buffer, string const & format,
149                       bool put_in_tempdir, string & result_file)
150 {
151         string backend_format;
152         OutputParams runparams;
153         runparams.flavor = OutputParams::LATEX;
154         runparams.linelen = lyxrc.ascii_linelen;
155         vector<string> backends = Backends(*buffer);
156         // FIXME: Without this test export to lyx13 would be through
157         // latex -> lyx -> lyx13, because the first backend below with a
158         // working conversion path is used. We should replace this test and
159         // the explicit loop below with a method
160         // getShortestPath(vector<string> const & from, string const & to)
161         // which returns the shortest path from one of the formats in 'from'
162         // to 'to'.
163         if (format == "lyx13x" && !converters.getPath("lyx", format).empty())
164                 backend_format = "lyx";
165         else if (find(backends.begin(), backends.end(), format) == backends.end()) {
166                 for (vector<string>::const_iterator it = backends.begin();
167                      it != backends.end(); ++it) {
168                         Graph::EdgePath p = converters.getPath(*it, format);
169                         if (!p.empty()) {
170                                 runparams.flavor = converters.getFlavor(p);
171                                 backend_format = *it;
172                                 break;
173                         }
174                 }
175                 if (backend_format.empty()) {
176                         Alert::error(_("Couldn't export file"),
177                                 bformat(_("No information for exporting the format %1$s."),
178                                    formats.prettyName(format)));
179                         return false;
180                 }
181         } else {
182                 backend_format = format;
183                 // FIXME: Don't hardcode format names here, but use a flag
184                 if (backend_format == "pdflatex")
185                         runparams.flavor = OutputParams::PDFLATEX;
186         }
187
188         string filename = buffer->getLatexName(false);
189         filename = addName(buffer->temppath(), filename);
190         filename = changeExtension(filename,
191                                    formats.extension(backend_format));
192
193         // Ascii backend
194         if (backend_format == "text")
195                 writeFileAscii(*buffer, FileName(filename), runparams);
196         // no backend
197         else if (backend_format == "lyx")
198                 buffer->writeFile(FileName(filename));
199         // Docbook backend
200         else if (buffer->isDocBook()) {
201                 runparams.nice = !put_in_tempdir;
202                 buffer->makeDocBookFile(FileName(filename), runparams);
203         }
204         // LaTeX backend
205         else if (backend_format == format) {
206                 runparams.nice = true;
207                 if (!buffer->makeLaTeXFile(FileName(filename), string(), runparams))
208                         return false;
209         } else if (!lyxrc.tex_allows_spaces
210                    && contains(buffer->filePath(), ' ')) {
211                 Alert::error(_("File name error"),
212                            _("The directory path to the document cannot contain spaces."));
213                 return false;
214         } else {
215                 runparams.nice = false;
216                 if (!buffer->makeLaTeXFile(FileName(filename), buffer->filePath(), runparams))
217                         return false;
218         }
219
220         string const error_type = (format == "program")? "Build" : bufferFormat(*buffer);
221         string const ext = formats.extension(format);
222         FileName const tmp_result_file(changeExtension(filename, ext));
223         bool const success = converters.convert(buffer, FileName(filename),
224                 tmp_result_file, FileName(buffer->fileName()), backend_format, format,
225                 buffer->errorList(error_type));
226         // Emit the signal to show the error list.
227         buffer->errors(error_type);
228         if (!success)
229                 return false;
230
231         if (put_in_tempdir)
232                 result_file = tmp_result_file.absFilename();
233         else {
234                 result_file = changeExtension(buffer->fileName(), ext);
235                 // We need to copy referenced files (e. g. included graphics
236                 // if format == "dvi") to the result dir.
237                 vector<ExportedFile> const files =
238                         runparams.exportdata->externalFiles(format);
239                 string const dest = onlyPath(result_file);
240                 CopyStatus status = SUCCESS;
241                 for (vector<ExportedFile>::const_iterator it = files.begin();
242                                 it != files.end() && status != CANCEL; ++it) {
243                         string const fmt =
244                                 formats.getFormatFromFile(it->sourceName);
245                         status = copyFile(fmt, it->sourceName,
246                                           makeAbsPath(it->exportName, dest),
247                                           it->exportName, status == FORCE);
248                 }
249                 if (status == CANCEL) {
250                         buffer->message(_("Document export cancelled."));
251                 } else if (fs::exists(tmp_result_file.toFilesystemEncoding())) {
252                         // Finally copy the main file
253                         status = copyFile(format, tmp_result_file,
254                                           FileName(result_file), result_file,
255                                           status == FORCE);
256                         buffer->message(bformat(_("Document exported as %1$s "
257                                                                "to file `%2$s'"),
258                                                 formats.prettyName(format),
259                                                 makeDisplayPath(result_file)));
260                 } else {
261                         // This must be a dummy converter like fax (bug 1888)
262                         buffer->message(bformat(_("Document exported as %1$s"),
263                                                 formats.prettyName(format)));
264                 }
265         }
266
267         return true;
268 }
269
270
271 bool Exporter::Export(Buffer * buffer, string const & format,
272                       bool put_in_tempdir)
273 {
274         string result_file;
275         return Export(buffer, format, put_in_tempdir, result_file);
276 }
277
278
279 bool Exporter::preview(Buffer * buffer, string const & format)
280 {
281         string result_file;
282         if (!Export(buffer, format, true, result_file))
283                 return false;
284         return formats.view(*buffer, FileName(result_file), format);
285 }
286
287
288 bool Exporter::isExportable(Buffer const & buffer, string const & format)
289 {
290         vector<string> backends = Backends(buffer);
291         for (vector<string>::const_iterator it = backends.begin();
292              it != backends.end(); ++it)
293                 if (converters.isReachable(*it, format))
294                         return true;
295         return false;
296 }
297
298
299 vector<Format const *> const
300 Exporter::getExportableFormats(Buffer const & buffer, bool only_viewable)
301 {
302         vector<string> backends = Backends(buffer);
303         vector<Format const *> result =
304                 converters.getReachable(backends[0], only_viewable, true);
305         for (vector<string>::const_iterator it = backends.begin() + 1;
306              it != backends.end(); ++it) {
307                 vector<Format const *>  r =
308                         converters.getReachable(*it, only_viewable, false);
309                 result.insert(result.end(), r.begin(), r.end());
310         }
311         return result;
312 }
313
314
315 ExportedFile::ExportedFile(FileName const & s, string const & e) :
316         sourceName(s), exportName(e) {}
317
318
319 bool operator==(ExportedFile const & f1, ExportedFile const & f2)
320 {
321         return f1.sourceName == f2.sourceName &&
322                f1.exportName == f2.exportName;
323
324 }
325
326
327 void ExportData::addExternalFile(string const & format,
328                                  FileName const & sourceName,
329                                  string const & exportName)
330 {
331         // Make sure that we have every file only once, otherwise copyFile()
332         // would ask several times if it should overwrite a file.
333         vector<ExportedFile> & files = externalfiles[format];
334         ExportedFile file(sourceName, exportName);
335         if (find(files.begin(), files.end(), file) == files.end())
336                 files.push_back(file);
337 }
338
339
340 void ExportData::addExternalFile(string const & format,
341                                  FileName const & sourceName)
342 {
343         addExternalFile(format, sourceName, onlyFilename(sourceName.absFilename()));
344 }
345
346
347 vector<ExportedFile> const
348 ExportData::externalFiles(string const & format) const
349 {
350         FileMap::const_iterator cit = externalfiles.find(format);
351         if (cit != externalfiles.end())
352                 return cit->second;
353         return vector<ExportedFile>();
354 }
355
356
357 } // namespace lyx