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"
18 #include "BufferParams.h"
19 #include "ErrorList.h"
21 #include "InsetIterator.h"
24 #include "Paragraph.h"
27 #include "frontends/alert.h"
29 #include "support/debug.h"
30 #include "support/filetools.h"
31 #include "support/gettext.h"
32 #include "support/convert.h"
33 #include "support/lstrings.h"
34 #include "support/ExceptionMessage.h"
35 #include "support/FileZipListDir.h"
42 using namespace lyx::support;
46 /** Dir name used for ".." in the bundled file.
48 Under the lyx temp directory, content.lyx and its embedded files are usually
51 $temp/$embDirName/file.lyx
52 $temp/$embDirName/figure1.png for ./figure1.png)
53 $temp/$embDirName/sub/figure2.png for ./sub/figure2.png)
55 This works fine for embedded files that are in the current or deeper directory
56 of the document directory, but not for files such as ../figures/figure.png.
57 A unique name $upDirName is chosen to represent .. in such filenames so that
58 'up' directories can be stored 'down' the directory tree:
60 $temp/$embDirName/$upDirName/figures/figure.png for ../figures/figure.png
61 $temp/$embDirName/$upDirName/$upDirName/figure.png for ../../figure.png
63 This name has to be fixed because it is used in lyx bundled .zip file.
65 Using a similar trick, we use $absDirName for absolute path so that
66 an absolute filename can be saved as
68 $temp/$embDirName/$absDirName/a/absolute/path for /a/absolute/path
71 const std::string embDirName = "LyX.Embedded.Files";
72 const std::string upDirName = "LyX.Embed.Dir.Up";
73 const std::string absDirName = "LyX.Embed.Dir.Abs";
75 namespace Alert = frontend::Alert;
77 EmbeddedFile::EmbeddedFile(string const & file, std::string const & buffer_path)
78 : DocFileName("", false), inzip_name_(""), embedded_(false), inset_list_(),
81 set(file, buffer_path);
85 void EmbeddedFile::set(std::string const & filename, std::string const & buffer_path)
87 DocFileName::set(filename, buffer_path);
91 inzip_name_ = to_utf8(makeRelPath(from_utf8(absFilename()),
92 from_utf8(buffer_path)));
94 if (FileName(inzip_name_).isAbsolute())
95 inzip_name_ = absDirName + '/' + inzip_name_;
97 // replace .. by upDirName
98 if (prefixIs(inzip_name_, "."))
99 inzip_name_ = subst(inzip_name_, "..", upDirName);
101 // to avoid name conflict between $docu_path/file and $temp_path/file
102 // embedded files are in a subdirectory of $temp_path.
103 inzip_name_ = embDirName + '/' + inzip_name_;
107 string EmbeddedFile::embeddedFile() const
109 BOOST_ASSERT(enabled());
110 return temp_path_ + inzip_name_;
114 FileName EmbeddedFile::availableFile() const
116 if (enabled() && embedded())
117 return FileName(embeddedFile());
123 string EmbeddedFile::latexFilename(std::string const & buffer_path) const
125 return (enabled() && embedded()) ? inzip_name_ : relFilename(buffer_path);
129 void EmbeddedFile::addInset(Inset const * inset)
132 inset_list_.push_back(inset);
136 void EmbeddedFile::setEmbed(bool embed)
142 void EmbeddedFile::enable(bool flag, Buffer const * buf)
144 if (enabled() == flag)
148 temp_path_ = buf->temppath();
149 if (!suffixIs(temp_path_, '/'))
152 updateFromExternalFile();
160 bool EmbeddedFile::extract() const
162 BOOST_ASSERT(enabled());
164 string ext_file = absFilename();
165 string emb_file = embeddedFile();
167 FileName emb(emb_file);
168 FileName ext(ext_file);
174 throw ExceptionMessage(ErrorException, _("Failed to extract file"),
175 bformat(_("Cannot extract file '%1$s'.\n"
176 "Source file %2$s does not exist"),
177 from_utf8(outputFilename()), from_utf8(emb_file)));
180 // if external file already exists ...
182 // no need to copy if the files are the same
183 if (checksum() == FileName(emb_file).checksum())
185 // otherwise, ask if overwrite
186 int ret = Alert::prompt(
187 _("Overwrite external file?"),
188 bformat(_("External file %1$s already exists, do you want to overwrite it"),
189 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
191 // if the user does not want to overwrite, we still consider it
192 // a successful operation.
197 // need to make directory?
198 FileName path = ext.onlyPath();
199 if (!path.createPath()) {
200 throw ExceptionMessage(ErrorException, _("Copy file failure"),
201 bformat(_("Cannot create file path '%1$s'.\n"
202 "Please check whether the path is writeable."),
203 from_utf8(path.absFilename())));
207 if (emb.copyTo(ext)) {
208 LYXERR(Debug::FILES, "Extract file " << emb_file << " to " << ext_file << endl);
212 throw ExceptionMessage(ErrorException, _("Copy file failure"),
213 bformat(_("Cannot copy file %1$s to %2$s.\n"
214 "Please check whether the directory exists and is writeable."),
215 from_utf8(emb_file), from_utf8(ext_file)));
220 bool EmbeddedFile::updateFromExternalFile() const
222 BOOST_ASSERT(enabled());
224 string ext_file = absFilename();
225 string emb_file = embeddedFile();
227 FileName emb(emb_file);
228 FileName ext(ext_file);
234 // no external and internal file
235 throw ExceptionMessage(ErrorException,
236 _("Failed to embed file"),
237 bformat(_("Failed to embed file %1$s.\n"
238 "Please check whether this file exists and is readable."),
239 from_utf8(ext_file)));
242 // if embedded file already exists ...
244 // no need to copy if the files are the same
245 if (checksum() == FileName(emb_file).checksum())
247 // other wise, ask if overwrite
248 int const ret = Alert::prompt(
249 _("Update embedded file?"),
250 bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
251 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
253 // if the user does not want to overwrite, we still consider it
254 // a successful operation.
258 // need to make directory?
259 FileName path = emb.onlyPath();
260 if (!path.isDirectory())
264 throw ExceptionMessage(ErrorException,
265 _("Copy file failure"),
266 bformat(_("Cannot copy file %1$s to %2$s.\n"
267 "Please check whether the directory exists and is writeable."),
268 from_utf8(ext_file), from_utf8(emb_file)));
269 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
274 void EmbeddedFile::updateInsets(Buffer const * buf) const
276 vector<Inset const *>::const_iterator it = inset_list_.begin();
277 vector<Inset const *>::const_iterator it_end = inset_list_.end();
278 for (; it != it_end; ++it)
279 const_cast<Inset *>(*it)->updateEmbeddedFile(*buf, *this);
283 bool EmbeddedFile::isReadableFile() const
285 return availableFile().isReadableFile();
289 unsigned long EmbeddedFile::checksum() const
291 return availableFile().checksum();
295 bool operator==(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
297 return lhs.absFilename() == rhs.absFilename()
298 && lhs.saveAbsPath() == rhs.saveAbsPath()
299 && lhs.embedded() == rhs.embedded();
303 bool operator!=(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
305 return !(lhs == rhs);
309 void EmbeddedFiles::enable(bool flag, Buffer & buffer)
311 if (buffer.embedded() == flag)
314 // update embedded file list
317 int count_embedded = 0;
318 int count_external = 0;
319 std::vector<EmbeddedFile>::iterator it = begin();
320 std::vector<EmbeddedFile>::iterator it_end = end();
321 // an exception may be thrown
322 for (; it != it_end; ++it) {
323 it->enable(flag, &buffer);
329 // if operation is successful (no exception is thrown)
331 buffer.params().embedded = flag;
333 // if the operation is successful, update insets
334 for (it = begin(); it != it_end; ++it)
335 it->updateInsets(&buffer);
339 docstring const msg = bformat(_("%1$d external files are ignored.\n"
340 "%2$d embeddable files are embedded.\n"), count_external, count_embedded);
341 Alert::information(_("Packing all files"), msg);
343 docstring const msg = bformat(_("%1$d external files are ignored.\n"
344 "%2$d embedded files are extracted.\n"), count_external, count_embedded);
345 Alert::information(_("Unpacking all files"), msg);
350 void EmbeddedFiles::registerFile(EmbeddedFile const & file,
351 Inset const * inset, Buffer const & buffer)
353 BOOST_ASSERT(!buffer.embedded() || file.availableFile().exists());
354 BOOST_ASSERT(!buffer.embedded() || file.enabled());
356 // try to find this file from the list
357 std::vector<EmbeddedFile>::iterator it = begin();
358 std::vector<EmbeddedFile>::iterator it_end = end();
359 for (; it != it_end; ++it)
360 if (it->absFilename() == file.absFilename()) {
361 if (it->embedded() != file.embedded()) {
362 Alert::error(_("Wrong embedding status."),
363 bformat(_("File %1$s is included in more than one insets, "
364 "but with different embedding status. Assuming embedding status."),
365 from_utf8(it->outputFilename())));
367 // update the inset with this embedding status.
368 const_cast<Inset*>(inset)->updateEmbeddedFile(buffer, *it);
375 back().addInset(inset);
379 void EmbeddedFiles::update(Buffer const & buffer)
383 for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
384 it->registerEmbeddedFiles(buffer, *this);
388 bool EmbeddedFiles::writeFile(DocFileName const & filename, Buffer const & buffer)
390 // file in the temporary path has the content
391 string const content = FileName(addName(buffer.temppath(),
392 "content.lyx")).toFilesystemEncoding();
394 vector<pair<string, string> > filenames;
395 // add content.lyx to filenames
396 filenames.push_back(make_pair(content, "content.lyx"));
397 // prepare list of embedded file
399 std::vector<EmbeddedFile>::iterator it = begin();
400 std::vector<EmbeddedFile>::iterator it_end = end();
401 for (; it != it_end; ++it) {
402 if (it->embedded()) {
403 string file = it->embeddedFile();
404 if (!FileName(file).exists())
405 throw ExceptionMessage(ErrorException, _("Failed to write file"),
406 bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
408 filenames.push_back(make_pair(file, it->inzipName()));
409 LYXERR(Debug::FILES, "Writing file " << it->outputFilename()
410 << " as " << it->inzipName() << endl);
413 // write a zip file with all these files. Write to a temp file first, to
414 // avoid messing up the original file in case something goes terribly wrong.
415 DocFileName zipfile(addName(buffer.temppath(),
416 onlyFilename(changeExtension(
417 filename.toFilesystemEncoding(), ".zip"))));
419 ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
421 if (!zipfile.copyTo(filename)) {
422 Alert::error(_("Save failure"),
423 bformat(_("Cannot create file %1$s.\n"
424 "Please check whether the directory exists and is writeable."),
425 from_utf8(filename.absFilename())));
426 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());