]> git.lyx.org Git - features.git/blob - src/Exporter.cpp
mainly cosmetics
[features.git] / src / Exporter.cpp
1 /**
2  * \file Exporter.cpp
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 std::find;
40 using std::string;
41 using std::vector;
42
43
44 namespace lyx {
45
46 using support::addName;
47 using support::bformat;
48 using support::changeExtension;
49 using support::contains;
50 using support::FileName;
51 using support::makeAbsPath;
52 using support::makeDisplayPath;
53 using support::onlyFilename;
54 using support::onlyPath;
55 using support::package;
56 using support::prefixIs;
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().getTextClass().isTeXClassAvailable()) {
67                 v.push_back(buffer.bufferFormat());
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 (filename.exists()) {
82                 docstring text = bformat(_("The file %1$s already exists.\n\n"
83                                                      "Do you want to overwrite that file?"),
84                                       makeDisplayPath(filename.absFilename()));
85                 return Alert::prompt(_("Overwrite file?"),
86                                      text, 0, 2,
87                                      _("&Overwrite"), _("Overwrite &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().absFilename()))
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 = getMover(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(&buffer->params().encoding());
153         runparams.flavor = OutputParams::LATEX;
154         runparams.linelen = lyxrc.plaintext_linelen;
155         vector<string> backends = Backends(*buffer);
156         if (find(backends.begin(), backends.end(), format) == backends.end()) {
157                 // Get shortest path to format
158                 Graph::EdgePath path;
159                 for (vector<string>::const_iterator it = backends.begin();
160                      it != backends.end(); ++it) {
161                         Graph::EdgePath p = theConverters().getPath(*it, format);
162                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
163                                 backend_format = *it;
164                                 path = p;
165                         }
166                 }
167                 if (!path.empty())
168                         runparams.flavor = theConverters().getFlavor(path);
169                 else {
170                         Alert::error(_("Couldn't export file"),
171                                 bformat(_("No information for exporting the format %1$s."),
172                                    formats.prettyName(format)));
173                         return false;
174                 }
175         } else {
176                 backend_format = format;
177                 // FIXME: Don't hardcode format names here, but use a flag
178                 if (backend_format == "pdflatex")
179                         runparams.flavor = OutputParams::PDFLATEX;
180         }
181
182         string filename = buffer->latexName(false);
183         filename = addName(buffer->temppath(), filename);
184         filename = changeExtension(filename,
185                                    formats.extension(backend_format));
186
187         // Plain text backend
188         if (backend_format == "text")
189                 writePlaintextFile(*buffer, FileName(filename), runparams);
190         // no backend
191         else if (backend_format == "lyx")
192                 buffer->writeFile(FileName(filename));
193         // Docbook backend
194         else if (buffer->isDocBook()) {
195                 runparams.nice = !put_in_tempdir;
196                 buffer->makeDocBookFile(FileName(filename), runparams);
197         }
198         // LaTeX backend
199         else if (backend_format == format) {
200                 runparams.nice = true;
201                 if (!buffer->makeLaTeXFile(FileName(filename), string(), runparams))
202                         return false;
203         } else if (!lyxrc.tex_allows_spaces
204                    && contains(buffer->filePath(), ' ')) {
205                 Alert::error(_("File name error"),
206                            _("The directory path to the document cannot contain spaces."));
207                 return false;
208         } else {
209                 runparams.nice = false;
210                 if (!buffer->makeLaTeXFile(FileName(filename), buffer->filePath(), runparams))
211                         return false;
212         }
213
214         string const error_type = (format == "program")
215                 ? "Build" : buffer->bufferFormat();
216         string const ext = formats.extension(format);
217         FileName const tmp_result_file(changeExtension(filename, ext));
218         bool const success = theConverters().convert(buffer, FileName(filename),
219                 tmp_result_file, FileName(buffer->absFileName()), backend_format, format,
220                 buffer->errorList(error_type));
221         // Emit the signal to show the error list.
222         if (format != backend_format)
223                 buffer->errors(error_type);
224         if (!success)
225                 return false;
226
227         if (put_in_tempdir)
228                 result_file = tmp_result_file.absFilename();
229         else {
230                 result_file = changeExtension(buffer->absFileName(), ext);
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 (tmp_result_file.exists()) {
248                         // Finally copy the main file
249                         status = copyFile(format, tmp_result_file,
250                                           FileName(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, FileName(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 (theConverters().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                 theConverters().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                         theConverters().getReachable(*it, only_viewable, false);
305                 result.insert(result.end(), r.begin(), r.end());
306         }
307         return result;
308 }
309
310
311 ExportedFile::ExportedFile(FileName 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                                  FileName const & sourceName,
325                                  string const & exportName)
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                                  FileName const & sourceName)
338 {
339         addExternalFile(format, sourceName, onlyFilename(sourceName.absFilename()));
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 }
351
352
353 } // namespace lyx