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