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