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