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;
150 bool EmbeddedFiles::enabled() const
152 return buffer_->params().embedded;
156 void EmbeddedFiles::enable(bool flag)
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;
169 void EmbeddedFiles::registerFile(string const & filename,
170 EmbeddedFile::STATUS status, ParConstIterator const & pit)
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)
179 // find this filename
180 if (it != file_list_.end()) {
182 it->setStatus(status);
186 file_list_.push_back(EmbeddedFile(abs_filename,
187 getInzipName(abs_filename), status, pit));
191 void EmbeddedFiles::update()
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)
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);
216 LYXERR(Debug::FILES) << "Manifest updated: " << endl
218 << "End Manifest" << endl;
222 bool EmbeddedFiles::write(DocFileName const & filename)
224 // file in the temporary path has the content
225 string const content = FileName(addName(buffer_->temppath(),
226 onlyFilename(filename.toFilesystemEncoding()))).toFilesystemEncoding();
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();
233 // write a manifest file
234 ofstream os(manifest.c_str());
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_);
244 lyxerr << "File " << it->absFilename() << " does not exist. Skip embedding it. " << endl;
246 filenames.push_back(make_pair(file, it->inzipName()));
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"))));
258 zipFiles(zipfile, filenames);
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;
273 bool EmbeddedFiles::extractAll() const
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_);
287 string const EmbeddedFiles::getInzipName(string const & abs_filename)
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) {
306 inzip_name = convert<string>(i) + "_" + tmp;
307 it = file_list_.begin();
308 for (; it != it_end; ++it)
309 if (it->inzipName() == inzip_name) {
319 istream & operator>> (istream & is, EmbeddedFiles & files)
325 istringstream itmp(tmp);
327 itmp.ignore(string("# LyX manifest version ").size());
331 lyxerr << "This version of LyX can only read LyX manifest version 1" << endl;
336 if (tmp != "<manifest>") {
337 lyxerr << "Invalid manifest file, lacking <manifest>" << endl;
340 // manifest file may be messed up, be carefully
349 getline(is, inzip_name);
351 istringstream itmp(tmp);
356 if (tmp != "</file>") {
357 lyxerr << "Invalid manifest file, lacking </file>" << endl;
361 files.registerFile(fname, static_cast<EmbeddedFile::STATUS>(status));
363 // the last line must be </manifest>
364 if (tmp != "</manifest>") {
365 lyxerr << "Invalid manifest file, lacking </manifest>" << endl;
372 ostream & operator<< (ostream & os, EmbeddedFiles const & files)
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) {
383 // use differnt lines to make reading easier.
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'
392 os << "</manifest>\n";