]> git.lyx.org Git - lyx.git/blob - src/EmbeddedFiles.cpp
Embedding dialog: add extract and extractAll functions
[lyx.git] / src / EmbeddedFiles.cpp
1 // -*- C++ -*-
2 /**
3  * \file EmbeddedFiles.cpp
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Bo Peng
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "EmbeddedFiles.h"
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "Paragraph.h"
19 #include "ParIterator.h"
20 #include "debug.h"
21 #include "gettext.h"
22 #include "Format.h"
23
24 #include "frontends/alert.h"
25
26 #include <boost/filesystem/operations.hpp>
27
28 #include "support/filetools.h"
29 #include "support/fs_extras.h"
30 #include "support/convert.h"
31 #include "support/lyxlib.h"
32 #include "support/lstrings.h"
33
34 #include <sstream>
35 #include <fstream>
36 #include <utility>
37
38 using std::ofstream;
39 using std::endl;
40 using std::vector;
41 using std::string;
42 using std::pair;
43 using std::make_pair;
44 using std::istream;
45 using std::ostream;
46 using std::getline;
47 using std::istringstream;
48
49 namespace lyx {
50
51 namespace fs = boost::filesystem;
52 namespace Alert = frontend::Alert;
53
54 using support::FileName;
55 using support::DocFileName;
56 using support::makeAbsPath;
57 using support::addName;
58 using support::onlyPath;
59 using support::absolutePath;
60 using support::onlyFilename;
61 using support::makeRelPath;
62 using support::changeExtension;
63 using support::bformat;
64 using support::zipFiles;
65 using support::prefixIs;
66 using support::sum;
67
68
69 EmbeddedFile::EmbeddedFile(string const & file, string const & inzip_name,
70         STATUS status, ParConstIterator const & pit)
71         : DocFileName(file, true), inzip_name_(inzip_name), status_(status),
72                 valid_(true), par_it_(pit)
73 {}
74
75
76 string EmbeddedFile::embeddedFile(Buffer const * buf) const
77 {
78         return addName(buf->temppath(), inzip_name_);
79 }
80
81
82 int const EmbeddedFile::parID() const
83 {
84         // some embedded file do not have a valid par iterator
85         return par_it_ == ParConstIterator() ? 0 : par_it_->id();
86 }
87
88
89 void EmbeddedFile::setParIter(ParConstIterator const & pit)
90 {
91         par_it_ = pit;
92 }
93
94
95 string EmbeddedFile::availableFile(Buffer const * buf) const
96 {
97         string ext_file = absFilename();
98         string emb_file = embeddedFile(buf);
99         if (status_ == AUTO) {
100                 // use external file first
101                 if (fs::exists(ext_file))
102                         return ext_file;
103                 else if (fs::exists(emb_file))
104                         return emb_file;
105                 else
106                         return string();
107         } else if (status_ == EMBEDDED) {
108                 // use embedded file first
109                 if (fs::exists(emb_file))
110                         return emb_file;
111                 else if (fs::exists(ext_file))
112                         return ext_file;
113                 else
114                         return string();
115         } else
116                 return string();
117 }
118
119
120 bool EmbeddedFile::extract(Buffer const * buf) const
121 {
122         string ext_file = absFilename();
123         string emb_file = embeddedFile(buf);
124         bool copyFile = false;
125         // both files exist, are different, and in EMBEDDED status
126         if (fs::exists(ext_file) && fs::exists(emb_file) && status_ == EMBEDDED
127                 && sum(*this) != sum(FileName(emb_file))) {
128                 int const ret = Alert::prompt(
129                         _("Overwrite external file?"),
130                         bformat(_("External file %1$s already exists, do you want to overwrite it"),
131                                 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
132                 copyFile = ret == 0;
133         }
134         // copy file in the previous case, and a new case
135         if (copyFile || (!fs::exists(ext_file) && fs::exists(emb_file))) {
136                 try {
137                         fs::copy_file(emb_file, ext_file, false);
138                         return true;
139                 } catch (fs::filesystem_error const & fe) {
140                         Alert::error(_("Copy file failure"),
141                                  bformat(_("Cannot copy file %1$s to %2$s.\n"
142                                            "Please check whether the directory exists and is writeable."),
143                                                 from_utf8(emb_file), from_utf8(ext_file)));
144                         LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
145                 }
146         }
147 }
148
149  
150 bool EmbeddedFiles::enabled() const
151 {
152         return buffer_->params().embedded;
153 }
154
155
156 void EmbeddedFiles::enable(bool flag)
157 {
158         if (enabled() != flag) {
159                 // if disable embedding, first extract all embedded files
160                 if (flag || (!flag && extractAll())) {
161                         // file will be changed
162                         buffer_->markDirty();
163                         buffer_->params().embedded = flag;
164                 }
165         }
166 }
167
168
169 void EmbeddedFiles::registerFile(string const & filename,
170         EmbeddedFile::STATUS status, ParConstIterator const & pit)
171 {
172         string abs_filename = makeAbsPath(filename, buffer_->filePath()).absFilename();
173         // try to find this file from the list
174         EmbeddedFileList::iterator it = file_list_.begin();
175         EmbeddedFileList::iterator it_end = file_list_.end();
176         for (; it != it_end; ++it)
177                 if (it->absFilename() == abs_filename)
178                         break;
179         // find this filename
180         if (it != file_list_.end()) {
181                 it->setParIter(pit);
182                 it->setStatus(status);
183                 it->validate();
184                 return;
185         }
186         file_list_.push_back(EmbeddedFile(abs_filename, 
187                 getInzipName(abs_filename), status, pit));
188 }
189
190
191 void EmbeddedFiles::update()
192 {
193         // invalidate all files, obsolete files will then not be validated by the
194         // following document scan. These files will still be kept though, because
195         // they may be added later and their embedding status will be meaningful
196         // again (thinking of cut/paste of an InsetInclude).
197         EmbeddedFileList::iterator it = file_list_.begin();
198         EmbeddedFileList::iterator it_end = file_list_.end();
199         for (; it != it_end; ++it)
200                 // Only AUTO files will be updated. If the status of a file is EMBEDDED, 
201                 // it will be embedded even if it is not referred by a document.
202                 if (it->status() == EmbeddedFile::AUTO)
203                         it->invalidate();
204
205         ParIterator pit = buffer_->par_iterator_begin();
206         ParIterator pit_end = buffer_->par_iterator_end();
207         for (; pit != pit_end; ++pit) {
208                 // For each paragraph, traverse its insets and register embedded files
209                 InsetList::const_iterator iit = pit->insetlist.begin();
210                 InsetList::const_iterator iit_end = pit->insetlist.end();
211                 for (; iit != iit_end; ++iit) {
212                         Inset & inset = *iit->inset;
213                         inset.registerEmbeddedFiles(*buffer_, *this, pit);
214                 }
215         }
216         LYXERR(Debug::FILES) << "Manifest updated: " << endl
217                 << *this
218                 << "End Manifest" << endl;
219 }
220
221
222 bool EmbeddedFiles::write(DocFileName const & filename)
223 {
224         // file in the temporary path has the content
225         string const content = FileName(addName(buffer_->temppath(),
226                 onlyFilename(filename.toFilesystemEncoding()))).toFilesystemEncoding();
227
228         // get a file list and write a manifest file
229         vector<pair<string, string> > filenames;
230         string const manifest = FileName(
231                 addName(buffer_->temppath(), "manifest.txt")).toFilesystemEncoding();
232
233         // write a manifest file
234         ofstream os(manifest.c_str());
235         os << *this;
236         os.close();
237         // prepare list of embedded file
238         EmbeddedFileList::iterator it = file_list_.begin();
239         EmbeddedFileList::iterator it_end = file_list_.end();
240         for (; it != it_end; ++it) {
241                 if (it->valid() && it->embedded()) {
242                         string file = it->availableFile(buffer_);
243                         if (file.empty())
244                                 lyxerr << "File " << it->absFilename() << " does not exist. Skip embedding it. " << endl;
245                         else
246                                 filenames.push_back(make_pair(file, it->inzipName()));
247                 }
248         }
249         // add filename (.lyx) and manifest to filenames
250         filenames.push_back(make_pair(content, onlyFilename(filename.toFilesystemEncoding())));
251         filenames.push_back(make_pair(manifest, "manifest.txt"));
252         // write a zip file with all these files. Write to a temp file first, to
253         // avoid messing up the original file in case something goes terribly wrong.
254         DocFileName zipfile(addName(buffer_->temppath(),
255                 onlyFilename(changeExtension(
256                         filename.toFilesystemEncoding(), ".zip"))));
257
258         zipFiles(zipfile, filenames);
259         // copy file back
260         try {
261                 fs::copy_file(zipfile.toFilesystemEncoding(), filename.toFilesystemEncoding(), false);
262         } catch (fs::filesystem_error const & fe) {
263                 Alert::error(_("Save failure"),
264                                  bformat(_("Cannot create file %1$s.\n"
265                                            "Please check whether the directory exists and is writeable."),
266                                          from_utf8(filename.absFilename())));
267                 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
268         }
269         return true;
270 }
271
272
273 bool EmbeddedFiles::extractAll() const
274 {
275         EmbeddedFileList::const_iterator it = file_list_.begin();
276         EmbeddedFileList::const_iterator it_end = file_list_.end();
277         // FIXME: the logic here is hard to decide, we should allow cancel for
278         // 'do not overwrite' this file, and cancel for 'cancel extract all files'.
279         // I am not sure how to do this now.
280         for (; it != it_end; ++it)
281                 if (it->valid() && it->status() != EmbeddedFile::EXTERNAL)
282                         it->extract(buffer_);
283         return true;
284 }
285
286
287 string const EmbeddedFiles::getInzipName(string const & abs_filename)
288 {
289         // register a new one, using relative file path as inzip_name
290         string inzip_name = to_utf8(makeRelPath(from_utf8(abs_filename),
291                 from_utf8(buffer_->fileName())));
292         // if inzip_name is an absolute path, use filename only to avoid
293         // leaking of filesystem information in inzip_name
294         if (absolutePath(inzip_name) || prefixIs(inzip_name, ".."))
295                 inzip_name = onlyFilename(inzip_name);
296         // if this name has been used...
297         // use _1_name, _2_name etc
298         string tmp = inzip_name;
299         EmbeddedFileList::iterator it;
300         EmbeddedFileList::iterator it_end = file_list_.end();
301         bool unique_name = false;
302         while (!unique_name) {
303                 unique_name = true;
304                 size_t i = 0;
305                 if (i > 0)
306                         inzip_name = convert<string>(i) + "_" + tmp;
307                 it = file_list_.begin();
308                 for (; it != it_end; ++it)
309                         if (it->inzipName() == inzip_name) {
310                                 unique_name = false;
311                                 ++i;
312                                 break;
313                         }
314         }
315         return inzip_name;
316 }
317
318
319 istream & operator>> (istream & is, EmbeddedFiles & files)
320 {
321         files.clear();
322         string tmp;
323         getline(is, tmp);
324         // get version
325         istringstream itmp(tmp);
326         int version;
327         itmp.ignore(string("# LyX manifest version ").size());
328         itmp >> version;
329
330         if (version != 1) {
331                 lyxerr << "This version of LyX can only read LyX manifest version 1" << endl;
332                 return is;
333         }
334
335         getline(is, tmp);
336         if (tmp != "<manifest>") {
337                 lyxerr << "Invalid manifest file, lacking <manifest>" << endl;
338                 return is;
339         }
340         // manifest file may be messed up, be carefully
341         while (is.good()) {
342                 getline(is, tmp);
343                 if (tmp != "<file>")
344                         break;
345
346                 string fname;
347                 getline(is, fname);
348                 string inzip_name;
349                 getline(is, inzip_name);
350                 getline(is, tmp);
351                 istringstream itmp(tmp);
352                 int status;
353                 itmp >> status;
354
355                 getline(is, tmp);
356                 if (tmp != "</file>") {
357                         lyxerr << "Invalid manifest file, lacking </file>" << endl;
358                         break;
359                 }
360
361                 files.registerFile(fname, static_cast<EmbeddedFile::STATUS>(status));
362         };
363         // the last line must be </manifest>
364         if (tmp != "</manifest>") {
365                 lyxerr << "Invalid manifest file, lacking </manifest>" << endl;
366                 return is;
367         }
368         return is;
369 }
370
371
372 ostream & operator<< (ostream & os, EmbeddedFiles const & files)
373 {
374         // store a version so that operator >> can read later versions
375         // using version information.
376         os << "# lyx manifest version 1\n";
377         os << "<manifest>\n";
378         EmbeddedFiles::EmbeddedFileList::const_iterator it = files.begin();
379         EmbeddedFiles::EmbeddedFileList::const_iterator it_end = files.end();
380         for (; it != it_end; ++it) {
381                 if (!it->valid())
382                         continue;
383                 // use differnt lines to make reading easier.
384                 os << "<file>\n"
385                         // save the relative path
386                         << to_utf8(makeRelPath(from_utf8(it->absFilename()),
387                                 from_utf8(files.buffer_->filePath()))) << '\n'
388                         << it->inzipName() << '\n'
389                         << it->status() << '\n'
390                         << "</file>\n";
391         }
392         os << "</manifest>\n";
393         return os;
394 }
395
396 }