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