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;
67 using support::makedir;
70 EmbeddedFile::EmbeddedFile(string const & file, string const & inzip_name,
71 STATUS status, ParConstIterator const & pit)
72 : DocFileName(file, true), inzip_name_(inzip_name), status_(status),
73 valid_(true), par_it_(pit)
77 string EmbeddedFile::embeddedFile(Buffer const * buf) const
79 return addName(buf->temppath(), inzip_name_);
83 int const EmbeddedFile::parID() const
85 // some embedded file do not have a valid par iterator
86 return par_it_ == ParConstIterator() ? 0 : par_it_->id();
90 void EmbeddedFile::setParIter(ParConstIterator const & pit)
96 string EmbeddedFile::availableFile(Buffer const * buf) const
98 string ext_file = absFilename();
99 string emb_file = embeddedFile(buf);
100 if (status_ == AUTO) {
101 // use external file first
102 if (fs::exists(ext_file))
104 else if (fs::exists(emb_file))
108 } else if (status_ == EMBEDDED) {
109 // use embedded file first
110 if (fs::exists(emb_file))
112 else if (fs::exists(ext_file))
121 bool EmbeddedFile::extract(Buffer const * buf) const
123 string ext_file = absFilename();
124 string emb_file = embeddedFile(buf);
125 bool copyFile = false;
126 // both files exist, are different, and in EMBEDDED status
127 if (fs::exists(ext_file) && fs::exists(emb_file) && status_ == EMBEDDED
128 && sum(*this) != sum(FileName(emb_file))) {
129 int const ret = Alert::prompt(
130 _("Overwrite external file?"),
131 bformat(_("External file %1$s already exists, do you want to overwrite it"),
132 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
135 // copy file in the previous case, and a new case
136 if (copyFile || (!fs::exists(ext_file) && fs::exists(emb_file))) {
138 // need to make directory?
139 string path = onlyPath(ext_file);
140 if (!fs::is_directory(path))
141 makedir(const_cast<char*>(path.c_str()), 0755);
142 fs::copy_file(emb_file, ext_file, false);
144 } catch (fs::filesystem_error const & fe) {
145 Alert::error(_("Copy file failure"),
146 bformat(_("Cannot copy file %1$s to %2$s.\n"
147 "Please check whether the directory exists and is writeable."),
148 from_utf8(emb_file), from_utf8(ext_file)));
149 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
156 bool EmbeddedFiles::enabled() const
158 return buffer_->params().embedded;
162 void EmbeddedFiles::enable(bool flag)
164 if (enabled() != flag) {
165 // if disable embedding, first extract all embedded files
166 if (flag || (!flag && extractAll())) {
167 // file will be changed
168 buffer_->markDirty();
169 buffer_->params().embedded = flag;
175 void EmbeddedFiles::registerFile(string const & filename,
176 EmbeddedFile::STATUS status, ParConstIterator const & pit)
178 string abs_filename = makeAbsPath(filename, buffer_->filePath()).absFilename();
179 // try to find this file from the list
180 EmbeddedFileList::iterator it = file_list_.begin();
181 EmbeddedFileList::iterator it_end = file_list_.end();
182 for (; it != it_end; ++it)
183 if (it->absFilename() == abs_filename)
185 // find this filename
186 if (it != file_list_.end()) {
188 it->setStatus(status);
192 file_list_.push_back(EmbeddedFile(abs_filename,
193 getInzipName(abs_filename), status, pit));
197 void EmbeddedFiles::update()
199 // invalidate all files, obsolete files will then not be validated by the
200 // following document scan. These files will still be kept though, because
201 // they may be added later and their embedding status will be meaningful
202 // again (thinking of cut/paste of an InsetInclude).
203 EmbeddedFileList::iterator it = file_list_.begin();
204 EmbeddedFileList::iterator it_end = file_list_.end();
205 for (; it != it_end; ++it)
206 // Only AUTO files will be updated. If the status of a file is EMBEDDED,
207 // it will be embedded even if it is not referred by a document.
208 if (it->status() == EmbeddedFile::AUTO)
211 ParIterator pit = buffer_->par_iterator_begin();
212 ParIterator pit_end = buffer_->par_iterator_end();
213 for (; pit != pit_end; ++pit) {
214 // For each paragraph, traverse its insets and register embedded files
215 InsetList::const_iterator iit = pit->insetlist.begin();
216 InsetList::const_iterator iit_end = pit->insetlist.end();
217 for (; iit != iit_end; ++iit) {
218 Inset & inset = *iit->inset;
219 inset.registerEmbeddedFiles(*buffer_, *this, pit);
222 LYXERR(Debug::FILES) << "Manifest updated: " << endl
224 << "End Manifest" << endl;
228 bool EmbeddedFiles::write(DocFileName const & filename)
230 // file in the temporary path has the content
231 string const content = FileName(addName(buffer_->temppath(),
232 onlyFilename(filename.toFilesystemEncoding()))).toFilesystemEncoding();
234 // get a file list and write a manifest file
235 vector<pair<string, string> > filenames;
236 string const manifest = FileName(
237 addName(buffer_->temppath(), "manifest.txt")).toFilesystemEncoding();
239 // write a manifest file
240 ofstream os(manifest.c_str());
243 // prepare list of embedded file
244 EmbeddedFileList::iterator it = file_list_.begin();
245 EmbeddedFileList::iterator it_end = file_list_.end();
246 for (; it != it_end; ++it) {
247 if (it->valid() && it->embedded()) {
248 string file = it->availableFile(buffer_);
250 lyxerr << "File " << it->absFilename() << " does not exist. Skip embedding it. " << endl;
252 filenames.push_back(make_pair(file, it->inzipName()));
255 // add filename (.lyx) and manifest to filenames
256 filenames.push_back(make_pair(content, onlyFilename(filename.toFilesystemEncoding())));
257 filenames.push_back(make_pair(manifest, "manifest.txt"));
258 // write a zip file with all these files. Write to a temp file first, to
259 // avoid messing up the original file in case something goes terribly wrong.
260 DocFileName zipfile(addName(buffer_->temppath(),
261 onlyFilename(changeExtension(
262 filename.toFilesystemEncoding(), ".zip"))));
264 zipFiles(zipfile, filenames);
267 fs::copy_file(zipfile.toFilesystemEncoding(), filename.toFilesystemEncoding(), false);
268 } catch (fs::filesystem_error const & fe) {
269 Alert::error(_("Save failure"),
270 bformat(_("Cannot create file %1$s.\n"
271 "Please check whether the directory exists and is writeable."),
272 from_utf8(filename.absFilename())));
273 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
279 bool EmbeddedFiles::extractAll() const
281 EmbeddedFileList::const_iterator it = file_list_.begin();
282 EmbeddedFileList::const_iterator it_end = file_list_.end();
283 // FIXME: the logic here is hard to decide, we should allow cancel for
284 // 'do not overwrite' this file, and cancel for 'cancel extract all files'.
285 // I am not sure how to do this now.
286 for (; it != it_end; ++it)
287 if (it->valid() && it->status() != EmbeddedFile::EXTERNAL)
288 it->extract(buffer_);
293 string const EmbeddedFiles::getInzipName(string const & abs_filename)
295 // register a new one, using relative file path as inzip_name
296 string inzip_name = to_utf8(makeRelPath(from_utf8(abs_filename),
297 from_utf8(buffer_->fileName())));
298 // if inzip_name is an absolute path, use filename only to avoid
299 // leaking of filesystem information in inzip_name
300 // The second case covers cases '../path/file' and '.'
301 if (absolutePath(inzip_name) || prefixIs(inzip_name, "."))
302 inzip_name = onlyFilename(abs_filename);
303 // if this name has been used...
304 // use _1_name, _2_name etc
305 string tmp = inzip_name;
306 EmbeddedFileList::iterator it;
307 EmbeddedFileList::iterator it_end = file_list_.end();
308 bool unique_name = false;
309 while (!unique_name) {
313 inzip_name = convert<string>(i) + "_" + tmp;
314 it = file_list_.begin();
315 for (; it != it_end; ++it)
316 if (it->inzipName() == inzip_name) {
326 istream & operator>> (istream & is, EmbeddedFiles & files)
332 istringstream itmp(tmp);
334 itmp.ignore(string("# LyX manifest version ").size());
338 lyxerr << "This version of LyX can only read LyX manifest version 1" << endl;
343 if (tmp != "<manifest>") {
344 lyxerr << "Invalid manifest file, lacking <manifest>" << endl;
347 // manifest file may be messed up, be carefully
356 getline(is, inzip_name);
358 istringstream itmp(tmp);
363 if (tmp != "</file>") {
364 lyxerr << "Invalid manifest file, lacking </file>" << endl;
368 files.registerFile(fname, static_cast<EmbeddedFile::STATUS>(status));
370 // the last line must be </manifest>
371 if (tmp != "</manifest>") {
372 lyxerr << "Invalid manifest file, lacking </manifest>" << endl;
379 ostream & operator<< (ostream & os, EmbeddedFiles const & files)
381 // store a version so that operator >> can read later versions
382 // using version information.
383 os << "# lyx manifest version 1\n";
384 os << "<manifest>\n";
385 EmbeddedFiles::EmbeddedFileList::const_iterator it = files.begin();
386 EmbeddedFiles::EmbeddedFileList::const_iterator it_end = files.end();
387 for (; it != it_end; ++it) {
390 // use differnt lines to make reading easier.
392 // save the relative path
393 << to_utf8(makeRelPath(from_utf8(it->absFilename()),
394 from_utf8(files.buffer_->filePath()))) << '\n'
395 << it->inzipName() << '\n'
396 << it->status() << '\n'
399 os << "</manifest>\n";