3 * \file EmbeddedFiles.cpp
4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
15 #include "EmbeddedFiles.h"
17 #include "BufferParams.h"
18 #include "Paragraph.h"
19 #include "ParIterator.h"
24 #include "frontends/alert.h"
26 #include <boost/filesystem/operations.hpp>
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"
47 using std::istringstream;
51 namespace fs = boost::filesystem;
52 namespace Alert = frontend::Alert;
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;
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)
76 string EmbeddedFile::embeddedFile(Buffer const * buf) const
78 return addName(buf->temppath(), inzip_name_);
82 int const EmbeddedFile::parID() const
84 // some embedded file do not have a valid par iterator
85 return par_it_ == ParConstIterator() ? 0 : par_it_->id();
89 void EmbeddedFile::setParIter(ParConstIterator const & pit)
95 string EmbeddedFile::availableFile(Buffer const * buf) const
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))
103 else if (fs::exists(emb_file))
107 } else if (status_ == EMBEDDED) {
108 // use embedded file first
109 if (fs::exists(emb_file))
111 else if (fs::exists(ext_file))
120 bool EmbeddedFile::extract(Buffer const * buf) const
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"));
134 // copy file in the previous case, and a new case
135 if (copyFile || (!fs::exists(ext_file) && fs::exists(emb_file))) {
137 fs::copy_file(emb_file, ext_file, false);
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;
151 bool EmbeddedFiles::enabled() const
153 return buffer_->params().embedded;
157 void EmbeddedFiles::enable(bool flag)
159 if (enabled() != flag) {
160 // if disable embedding, first extract all embedded files
161 if (flag || (!flag && extractAll())) {
162 // file will be changed
163 buffer_->markDirty();
164 buffer_->params().embedded = flag;
170 void EmbeddedFiles::registerFile(string const & filename,
171 EmbeddedFile::STATUS status, ParConstIterator const & pit)
173 string abs_filename = makeAbsPath(filename, buffer_->filePath()).absFilename();
174 // try to find this file from the list
175 EmbeddedFileList::iterator it = file_list_.begin();
176 EmbeddedFileList::iterator it_end = file_list_.end();
177 for (; it != it_end; ++it)
178 if (it->absFilename() == abs_filename)
180 // find this filename
181 if (it != file_list_.end()) {
183 it->setStatus(status);
187 file_list_.push_back(EmbeddedFile(abs_filename,
188 getInzipName(abs_filename), status, pit));
192 void EmbeddedFiles::update()
194 // invalidate all files, obsolete files will then not be validated by the
195 // following document scan. These files will still be kept though, because
196 // they may be added later and their embedding status will be meaningful
197 // again (thinking of cut/paste of an InsetInclude).
198 EmbeddedFileList::iterator it = file_list_.begin();
199 EmbeddedFileList::iterator it_end = file_list_.end();
200 for (; it != it_end; ++it)
201 // Only AUTO files will be updated. If the status of a file is EMBEDDED,
202 // it will be embedded even if it is not referred by a document.
203 if (it->status() == EmbeddedFile::AUTO)
206 ParIterator pit = buffer_->par_iterator_begin();
207 ParIterator pit_end = buffer_->par_iterator_end();
208 for (; pit != pit_end; ++pit) {
209 // For each paragraph, traverse its insets and register embedded files
210 InsetList::const_iterator iit = pit->insetlist.begin();
211 InsetList::const_iterator iit_end = pit->insetlist.end();
212 for (; iit != iit_end; ++iit) {
213 Inset & inset = *iit->inset;
214 inset.registerEmbeddedFiles(*buffer_, *this, pit);
217 LYXERR(Debug::FILES) << "Manifest updated: " << endl
219 << "End Manifest" << endl;
223 bool EmbeddedFiles::write(DocFileName const & filename)
225 // file in the temporary path has the content
226 string const content = FileName(addName(buffer_->temppath(),
227 onlyFilename(filename.toFilesystemEncoding()))).toFilesystemEncoding();
229 // get a file list and write a manifest file
230 vector<pair<string, string> > filenames;
231 string const manifest = FileName(
232 addName(buffer_->temppath(), "manifest.txt")).toFilesystemEncoding();
234 // write a manifest file
235 ofstream os(manifest.c_str());
238 // prepare list of embedded file
239 EmbeddedFileList::iterator it = file_list_.begin();
240 EmbeddedFileList::iterator it_end = file_list_.end();
241 for (; it != it_end; ++it) {
242 if (it->valid() && it->embedded()) {
243 string file = it->availableFile(buffer_);
245 lyxerr << "File " << it->absFilename() << " does not exist. Skip embedding it. " << endl;
247 filenames.push_back(make_pair(file, it->inzipName()));
250 // add filename (.lyx) and manifest to filenames
251 filenames.push_back(make_pair(content, onlyFilename(filename.toFilesystemEncoding())));
252 filenames.push_back(make_pair(manifest, "manifest.txt"));
253 // write a zip file with all these files. Write to a temp file first, to
254 // avoid messing up the original file in case something goes terribly wrong.
255 DocFileName zipfile(addName(buffer_->temppath(),
256 onlyFilename(changeExtension(
257 filename.toFilesystemEncoding(), ".zip"))));
259 zipFiles(zipfile, filenames);
262 fs::copy_file(zipfile.toFilesystemEncoding(), filename.toFilesystemEncoding(), false);
263 } catch (fs::filesystem_error const & fe) {
264 Alert::error(_("Save failure"),
265 bformat(_("Cannot create file %1$s.\n"
266 "Please check whether the directory exists and is writeable."),
267 from_utf8(filename.absFilename())));
268 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
274 bool EmbeddedFiles::extractAll() const
276 EmbeddedFileList::const_iterator it = file_list_.begin();
277 EmbeddedFileList::const_iterator it_end = file_list_.end();
278 // FIXME: the logic here is hard to decide, we should allow cancel for
279 // 'do not overwrite' this file, and cancel for 'cancel extract all files'.
280 // I am not sure how to do this now.
281 for (; it != it_end; ++it)
282 if (it->valid() && it->status() != EmbeddedFile::EXTERNAL)
283 it->extract(buffer_);
288 string const EmbeddedFiles::getInzipName(string const & abs_filename)
290 // register a new one, using relative file path as inzip_name
291 string inzip_name = to_utf8(makeRelPath(from_utf8(abs_filename),
292 from_utf8(buffer_->fileName())));
293 // if inzip_name is an absolute path, use filename only to avoid
294 // leaking of filesystem information in inzip_name
295 if (absolutePath(inzip_name) || prefixIs(inzip_name, ".."))
296 inzip_name = onlyFilename(inzip_name);
297 // if this name has been used...
298 // use _1_name, _2_name etc
299 string tmp = inzip_name;
300 EmbeddedFileList::iterator it;
301 EmbeddedFileList::iterator it_end = file_list_.end();
302 bool unique_name = false;
303 while (!unique_name) {
307 inzip_name = convert<string>(i) + "_" + tmp;
308 it = file_list_.begin();
309 for (; it != it_end; ++it)
310 if (it->inzipName() == inzip_name) {
320 istream & operator>> (istream & is, EmbeddedFiles & files)
326 istringstream itmp(tmp);
328 itmp.ignore(string("# LyX manifest version ").size());
332 lyxerr << "This version of LyX can only read LyX manifest version 1" << endl;
337 if (tmp != "<manifest>") {
338 lyxerr << "Invalid manifest file, lacking <manifest>" << endl;
341 // manifest file may be messed up, be carefully
350 getline(is, inzip_name);
352 istringstream itmp(tmp);
357 if (tmp != "</file>") {
358 lyxerr << "Invalid manifest file, lacking </file>" << endl;
362 files.registerFile(fname, static_cast<EmbeddedFile::STATUS>(status));
364 // the last line must be </manifest>
365 if (tmp != "</manifest>") {
366 lyxerr << "Invalid manifest file, lacking </manifest>" << endl;
373 ostream & operator<< (ostream & os, EmbeddedFiles const & files)
375 // store a version so that operator >> can read later versions
376 // using version information.
377 os << "# lyx manifest version 1\n";
378 os << "<manifest>\n";
379 EmbeddedFiles::EmbeddedFileList::const_iterator it = files.begin();
380 EmbeddedFiles::EmbeddedFileList::const_iterator it_end = files.end();
381 for (; it != it_end; ++it) {
384 // use differnt lines to make reading easier.
386 // save the relative path
387 << to_utf8(makeRelPath(from_utf8(it->absFilename()),
388 from_utf8(files.buffer_->filePath()))) << '\n'
389 << it->inzipName() << '\n'
390 << it->status() << '\n'
393 os << "</manifest>\n";