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::prefixIs;
66 using support::makedir;
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 // need to make directory?
138 string path = onlyPath(ext_file);
139 if (!fs::is_directory(path))
140 makedir(const_cast<char*>(path.c_str()), 0755);
141 fs::copy_file(emb_file, ext_file, false);
143 } catch (fs::filesystem_error const & fe) {
144 Alert::error(_("Copy file failure"),
145 bformat(_("Cannot copy file %1$s to %2$s.\n"
146 "Please check whether the directory exists and is writeable."),
147 from_utf8(emb_file), from_utf8(ext_file)));
148 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
155 bool EmbeddedFiles::enabled() const
157 return buffer_->params().embedded;
161 void EmbeddedFiles::enable(bool flag)
163 if (enabled() != flag) {
164 // if disable embedding, first extract all embedded files
165 if (flag || (!flag && extractAll())) {
166 // file will be changed
167 buffer_->markDirty();
168 buffer_->params().embedded = flag;
174 void EmbeddedFiles::registerFile(string const & filename,
175 EmbeddedFile::STATUS status, ParConstIterator const & pit)
177 string abs_filename = makeAbsPath(filename, buffer_->filePath()).absFilename();
178 // try to find this file from the list
179 EmbeddedFileList::iterator it = file_list_.begin();
180 EmbeddedFileList::iterator it_end = file_list_.end();
181 for (; it != it_end; ++it)
182 if (it->absFilename() == abs_filename || it->embeddedFile(buffer_) == abs_filename)
184 // find this filename
185 if (it != file_list_.end()) {
187 it->setStatus(status);
191 file_list_.push_back(EmbeddedFile(abs_filename,
192 getInzipName(abs_filename), status, pit));
196 void EmbeddedFiles::update()
198 // invalidate all files, obsolete files will then not be validated by the
199 // following document scan. These files will still be kept though, because
200 // they may be added later and their embedding status will be meaningful
201 // again (thinking of cut/paste of an InsetInclude).
202 EmbeddedFileList::iterator it = file_list_.begin();
203 EmbeddedFileList::iterator it_end = file_list_.end();
204 for (; it != it_end; ++it)
205 // Only AUTO files will be updated. If the status of a file is EMBEDDED,
206 // it will be embedded even if it is not referred by a document.
207 if (it->status() == EmbeddedFile::AUTO)
210 ParIterator pit = buffer_->par_iterator_begin();
211 ParIterator pit_end = buffer_->par_iterator_end();
212 for (; pit != pit_end; ++pit) {
213 // For each paragraph, traverse its insets and register embedded files
214 InsetList::const_iterator iit = pit->insetlist.begin();
215 InsetList::const_iterator iit_end = pit->insetlist.end();
216 for (; iit != iit_end; ++iit) {
217 Inset & inset = *iit->inset;
218 inset.registerEmbeddedFiles(*buffer_, *this, pit);
221 LYXERR(Debug::FILES) << "Manifest updated: " << endl
223 << "End Manifest" << endl;
227 bool EmbeddedFiles::write(DocFileName const & filename)
229 // file in the temporary path has the content
230 string const content = FileName(addName(buffer_->temppath(),
231 onlyFilename(filename.toFilesystemEncoding()))).toFilesystemEncoding();
233 // get a file list and write a manifest file
234 vector<pair<string, string> > filenames;
235 string const manifest = FileName(
236 addName(buffer_->temppath(), "manifest.txt")).toFilesystemEncoding();
238 // write a manifest file
239 ofstream os(manifest.c_str());
242 // prepare list of embedded file
243 EmbeddedFileList::iterator it = file_list_.begin();
244 EmbeddedFileList::iterator it_end = file_list_.end();
245 for (; it != it_end; ++it) {
246 if (it->valid() && it->embedded()) {
247 string file = it->availableFile(buffer_);
249 lyxerr << "File " << it->absFilename() << " does not exist. Skip embedding it. " << endl;
251 filenames.push_back(make_pair(file, it->inzipName()));
254 // add filename (.lyx) and manifest to filenames
255 filenames.push_back(make_pair(content, onlyFilename(filename.toFilesystemEncoding())));
256 filenames.push_back(make_pair(manifest, "manifest.txt"));
257 // write a zip file with all these files. Write to a temp file first, to
258 // avoid messing up the original file in case something goes terribly wrong.
259 DocFileName zipfile(addName(buffer_->temppath(),
260 onlyFilename(changeExtension(
261 filename.toFilesystemEncoding(), ".zip"))));
263 ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
266 fs::copy_file(zipfile.toFilesystemEncoding(), filename.toFilesystemEncoding(), false);
267 } catch (fs::filesystem_error const & fe) {
268 Alert::error(_("Save failure"),
269 bformat(_("Cannot create file %1$s.\n"
270 "Please check whether the directory exists and is writeable."),
271 from_utf8(filename.absFilename())));
272 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
278 EmbeddedFiles::EmbeddedFileList::const_iterator EmbeddedFiles::find(std::string filename) const
280 EmbeddedFileList::const_iterator it = file_list_.begin();
281 EmbeddedFileList::const_iterator it_end = file_list_.end();
282 for (; it != it_end; ++it)
283 if (it->absFilename() == filename || it->embeddedFile(buffer_) == filename)
285 return file_list_.end();
289 bool EmbeddedFiles::extractAll() const
291 EmbeddedFileList::const_iterator it = file_list_.begin();
292 EmbeddedFileList::const_iterator it_end = file_list_.end();
293 // FIXME: the logic here is hard to decide, we should allow cancel for
294 // 'do not overwrite' this file, and cancel for 'cancel extract all files'.
295 // I am not sure how to do this now.
296 for (; it != it_end; ++it)
297 if (it->valid() && it->status() != EmbeddedFile::EXTERNAL)
298 it->extract(buffer_);
303 string const EmbeddedFiles::getInzipName(string const & abs_filename)
305 // register a new one, using relative file path as inzip_name
306 string inzip_name = to_utf8(makeRelPath(from_utf8(abs_filename),
307 from_utf8(buffer_->fileName())));
308 // if inzip_name is an absolute path, use filename only to avoid
309 // leaking of filesystem information in inzip_name
310 // The second case covers cases '../path/file' and '.'
311 if (absolutePath(inzip_name) || prefixIs(inzip_name, "."))
312 inzip_name = onlyFilename(abs_filename);
313 // if this name has been used...
314 // use _1_name, _2_name etc
315 string tmp = inzip_name;
316 EmbeddedFileList::iterator it;
317 EmbeddedFileList::iterator it_end = file_list_.end();
318 bool unique_name = false;
320 while (!unique_name) {
323 inzip_name = convert<string>(i) + "_" + tmp;
324 it = file_list_.begin();
325 for (; it != it_end; ++it)
326 if (it->inzipName() == inzip_name) {
336 istream & operator>> (istream & is, EmbeddedFiles & files)
342 istringstream itmp(tmp);
344 itmp.ignore(string("# LyX manifest version ").size());
348 lyxerr << "This version of LyX can only read LyX manifest version 1" << endl;
353 if (tmp != "<manifest>") {
354 lyxerr << "Invalid manifest file, lacking <manifest>" << endl;
357 // manifest file may be messed up, be carefully
366 getline(is, inzip_name);
368 istringstream itmp(tmp);
373 if (tmp != "</file>") {
374 lyxerr << "Invalid manifest file, lacking </file>" << endl;
378 files.registerFile(fname, static_cast<EmbeddedFile::STATUS>(status));
380 // the last line must be </manifest>
381 if (tmp != "</manifest>") {
382 lyxerr << "Invalid manifest file, lacking </manifest>" << endl;
389 ostream & operator<< (ostream & os, EmbeddedFiles const & files)
391 // store a version so that operator >> can read later versions
392 // using version information.
393 os << "# lyx manifest version 1\n";
394 os << "<manifest>\n";
395 EmbeddedFiles::EmbeddedFileList::const_iterator it = files.begin();
396 EmbeddedFiles::EmbeddedFileList::const_iterator it_end = files.end();
397 for (; it != it_end; ++it) {
400 // use differnt lines to make reading easier.
402 // save the relative path
403 << to_utf8(makeRelPath(from_utf8(it->absFilename()),
404 from_utf8(files.buffer_->filePath()))) << '\n'
405 << it->inzipName() << '\n'
406 << it->status() << '\n'
409 os << "</manifest>\n";