3 * \file EmbeddedFileList.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 namespace Alert = frontend::Alert;
48 EmbeddedFile::EmbeddedFile(string const & file, std::string const & buffer_path)
49 : DocFileName("", false), inzip_name_(""), embedded_(false), inset_list_(),
52 set(file, buffer_path);
56 void EmbeddedFile::set(std::string const & filename, std::string const & buffer_path)
58 DocFileName::set(filename, buffer_path);
62 if (!buffer_path.empty())
63 inzip_name_ = calcInzipName(buffer_path);
67 void EmbeddedFile::setInzipName(std::string const & name)
69 if (name.empty() || name == inzip_name_)
72 // an enabled EmbeededFile should have this problem handled
73 BOOST_ASSERT(!enabled());
74 // file will be synced when it is enabled
79 string EmbeddedFile::embeddedFile() const
81 BOOST_ASSERT(enabled());
82 return temp_path_ + inzip_name_;
86 FileName EmbeddedFile::availableFile() const
88 if (enabled() && embedded())
89 return FileName(embeddedFile());
95 string EmbeddedFile::latexFilename(std::string const & buffer_path) const
97 return (enabled() && embedded()) ? inzip_name_ : relFilename(buffer_path);
101 void EmbeddedFile::addInset(Inset const * inset)
104 inset_list_.push_back(inset);
108 void EmbeddedFile::setEmbed(bool embed)
114 void EmbeddedFile::enable(bool flag, Buffer const * buf, bool updateFile)
116 // This function will be called when
117 // 1. through EmbeddedFiles::enable() when a file is read. Files
118 // should be in place so no updateFromExternalFile or extract()
119 // should be called. (updateFile should be false in this case).
120 // 2. through menu item enable/disable. updateFile should be true.
121 // 3. A single embedded file is added or modified. updateFile
122 // can be true or false.
123 LYXERR(Debug::FILES, (flag ? "Enable" : "Disable")
124 << " " << absFilename()
125 << (updateFile ? " (update file)." : " (no update)."));
128 temp_path_ = buf->temppath();
129 if (!suffixIs(temp_path_, '/'))
132 if (inzip_name_ != calcInzipName(buf->filePath()))
133 syncInzipFile(buf->filePath());
135 updateFromExternalFile();
138 if (embedded() && updateFile)
145 bool EmbeddedFile::extract() const
147 BOOST_ASSERT(enabled());
149 string ext_file = absFilename();
150 string emb_file = embeddedFile();
152 FileName emb(emb_file);
153 FileName ext(ext_file);
159 throw ExceptionMessage(ErrorException, _("Failed to extract file"),
160 bformat(_("Cannot extract file '%1$s'.\n"
161 "Source file %2$s does not exist"),
162 from_utf8(outputFilename()), from_utf8(emb_file)));
165 // if external file already exists ...
167 // no need to copy if the files are the same
168 if (checksum() == FileName(emb_file).checksum())
170 // otherwise, ask if overwrite
171 int ret = Alert::prompt(
172 _("Overwrite external file?"),
173 bformat(_("External file %1$s already exists, do you want to overwrite it"),
174 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
176 // if the user does not want to overwrite, we still consider it
177 // a successful operation.
182 // need to make directory?
183 FileName path = ext.onlyPath();
184 if (!path.createPath()) {
185 throw ExceptionMessage(ErrorException, _("Copy file failure"),
186 bformat(_("Cannot create file path '%1$s'.\n"
187 "Please check whether the path is writeable."),
188 from_utf8(path.absFilename())));
192 if (emb.copyTo(ext)) {
193 LYXERR(Debug::FILES, "Extract file " << emb_file << " to " << ext_file << endl);
197 throw ExceptionMessage(ErrorException, _("Copy file failure"),
198 bformat(_("Cannot copy file %1$s to %2$s.\n"
199 "Please check whether the directory exists and is writeable."),
200 from_utf8(emb_file), from_utf8(ext_file)));
205 bool EmbeddedFile::updateFromExternalFile() const
207 BOOST_ASSERT(enabled());
209 string ext_file = absFilename();
210 string emb_file = embeddedFile();
212 FileName emb(emb_file);
213 FileName ext(ext_file);
219 // no external and internal file
220 throw ExceptionMessage(ErrorException,
221 _("Failed to embed file"),
222 bformat(_("Failed to embed file %1$s.\n"
223 "Please check whether this file exists and is readable."),
224 from_utf8(ext_file)));
227 // if embedded file already exists ...
229 // no need to copy if the files are the same
230 if (checksum() == FileName(emb_file).checksum())
232 // other wise, ask if overwrite
233 int const ret = Alert::prompt(
234 _("Update embedded file?"),
235 bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
236 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
238 // if the user does not want to overwrite, we still consider it
239 // a successful operation.
243 // need to make directory?
244 FileName path = emb.onlyPath();
245 if (!path.isDirectory())
249 throw ExceptionMessage(ErrorException,
250 _("Copy file failure"),
251 bformat(_("Cannot copy file %1$s to %2$s.\n"
252 "Please check whether the directory exists and is writeable."),
253 from_utf8(ext_file), from_utf8(emb_file)));
254 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
259 void EmbeddedFile::updateInsets() const
261 vector<Inset const *>::const_iterator it = inset_list_.begin();
262 vector<Inset const *>::const_iterator it_end = inset_list_.end();
263 for (; it != it_end; ++it)
264 const_cast<Inset *>(*it)->updateEmbeddedFile(*this);
268 bool EmbeddedFile::isReadableFile() const
270 return availableFile().isReadableFile();
274 unsigned long EmbeddedFile::checksum() const
276 return availableFile().checksum();
280 Under the lyx temp directory, content.lyx and its embedded files are usually
283 $temp/$embDirName/file.lyx
284 $temp/$embDirName/figure1.png for ./figure1.png)
285 $temp/$embDirName/sub/figure2.png for ./sub/figure2.png)
287 This works fine for embedded files that are in the current or deeper directory
288 of the document directory, but not for files such as ../figures/figure.png.
289 A unique name $upDirName is chosen to represent .. in such filenames so that
290 'up' directories can be stored 'down' the directory tree:
292 $temp/$embDirName/$upDirName/figures/figure.png for ../figures/figure.png
293 $temp/$embDirName/$upDirName/$upDirName/figure.png for ../../figure.png
295 This name has to be fixed because it is used in lyx bundled .zip file.
297 Using a similar trick, we use $absDirName for absolute path so that
298 an absolute filename can be saved as
300 $temp/$embDirName/$absDirName/a/absolute/path for /a/absolute/path
303 const std::string embDirName = "LyX.Embedded.Files";
304 const std::string upDirName = "LyX.Embed.Dir.Up";
305 const std::string absDirName = "LyX.Embed.Dir.Abs";
306 const std::string driveName = "LyX.Embed.Drive";
307 const std::string spaceName = "LyX.Embed.Space";
309 std::string EmbeddedFile::calcInzipName(std::string const & buffer_path)
311 string inzipName = to_utf8(makeRelPath(from_utf8(absFilename()),
312 from_utf8(buffer_path)));
314 if (FileName(inzipName).isAbsolute())
315 inzipName = absDirName + '/' + inzipName;
317 // replace .. by upDirName
318 if (prefixIs(inzipName, "."))
319 inzipName = subst(inzipName, "..", upDirName);
320 // replace special characters by their value
321 inzipName = subst(inzipName, ":", driveName);
322 inzipName = subst(inzipName, " ", spaceName);
324 // to avoid name conflict between $docu_path/file and $temp_path/file
325 // embedded files are in a subdirectory of $temp_path.
326 inzipName = embDirName + '/' + inzipName;
331 void EmbeddedFile::syncInzipFile(std::string const & buffer_path)
333 BOOST_ASSERT(enabled());
334 string old_emb_file = temp_path_ + '/' + inzip_name_;
335 FileName old_emb(old_emb_file);
337 LYXERR(Debug::FILES, " OLD ZIP " << old_emb_file <<
338 " NEW ZIP " << calcInzipName(buffer_path));
340 //BOOST_ASSERT(old_emb.exists());
342 string new_inzip_name = calcInzipName(buffer_path);
343 string new_emb_file = temp_path_ + '/' + new_inzip_name;
344 FileName new_emb(new_emb_file);
346 // need to make directory?
347 FileName path = new_emb.onlyPath();
348 if (!path.createPath()) {
349 throw ExceptionMessage(ErrorException, _("Sync file failure"),
350 bformat(_("Cannot create file path '%1$s'.\n"
351 "Please check whether the path is writeable."),
352 from_utf8(path.absFilename())));
356 if (old_emb.copyTo(new_emb)) {
357 LYXERR(Debug::FILES, "Sync inzip file from " << inzip_name_
358 << " to " << new_inzip_name);
359 inzip_name_ = new_inzip_name;
362 throw ExceptionMessage(ErrorException, _("Sync file failure"),
363 bformat(_("Cannot copy file %1$s to %2$s.\n"
364 "Please check whether the directory exists and is writeable."),
365 from_utf8(old_emb_file), from_utf8(new_emb_file)));
369 bool operator==(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
371 return lhs.absFilename() == rhs.absFilename()
372 && lhs.saveAbsPath() == rhs.saveAbsPath()
373 && lhs.embedded() == rhs.embedded();
377 bool operator!=(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
379 return !(lhs == rhs);
383 void EmbeddedFileList::enable(bool flag, Buffer & buffer, bool updateFile)
385 // update embedded file list
388 int count_embedded = 0;
389 int count_external = 0;
390 iterator it = begin();
391 iterator it_end = end();
392 // an exception may be thrown
393 for (; it != it_end; ++it) {
394 it->enable(flag, &buffer, updateFile);
400 // if operation is successful (no exception is thrown)
402 buffer.params().embedded = flag;
404 // if the operation is successful, update insets
405 for (it = begin(); it != it_end; ++it)
413 docstring const msg = bformat(_("%1$d external files are ignored.\n"
414 "%2$d embeddable files are embedded.\n"), count_external, count_embedded);
415 Alert::information(_("Packing all files"), msg);
417 docstring const msg = bformat(_("%1$d external files are ignored.\n"
418 "%2$d embedded files are extracted.\n"), count_external, count_embedded);
419 Alert::information(_("Unpacking all files"), msg);
424 void EmbeddedFileList::registerFile(EmbeddedFile const & file,
425 Inset const * inset, Buffer const & buffer)
427 BOOST_ASSERT(!buffer.embedded() || file.enabled());
429 // try to find this file from the list
430 std::vector<EmbeddedFile>::iterator it = begin();
431 std::vector<EmbeddedFile>::iterator it_end = end();
432 for (; it != it_end; ++it)
433 if (it->absFilename() == file.absFilename()) {
434 if (it->embedded() != file.embedded()) {
435 Alert::error(_("Wrong embedding status."),
436 bformat(_("File %1$s is included in more than one insets, "
437 "but with different embedding status. Assuming embedding status."),
438 from_utf8(it->outputFilename())));
440 // update the inset with this embedding status.
441 const_cast<Inset*>(inset)->updateEmbeddedFile(*it);
449 back().addInset(inset);
453 void EmbeddedFileList::update(Buffer const & buffer)
457 for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
458 it->registerEmbeddedFiles(*this);
460 // add extra embedded files
461 vector<string> extra = buffer.params().extraEmbeddedFiles();
462 vector<string>::iterator it = extra.begin();
463 vector<string>::iterator it_end = extra.end();
464 for (; it != it_end; ++it) {
465 EmbeddedFile file = EmbeddedFile(*it, buffer.filePath());
467 file.enable(buffer.embedded(), &buffer, true);
473 bool EmbeddedFileList::writeFile(DocFileName const & filename, Buffer const & buffer)
475 // file in the temporary path has the content
476 string const content = FileName(addName(buffer.temppath(),
477 "content.lyx")).toFilesystemEncoding();
479 vector<pair<string, string> > filenames;
480 // add content.lyx to filenames
481 filenames.push_back(make_pair(content, "content.lyx"));
482 // prepare list of embedded file
485 iterator it = begin();
486 iterator it_end = end();
487 for (; it != it_end; ++it) {
488 if (it->embedded()) {
489 string file = it->embeddedFile();
490 if (!FileName(file).exists())
491 throw ExceptionMessage(ErrorException, _("Failed to write file"),
492 bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
494 filenames.push_back(make_pair(file, it->inzipName()));
495 LYXERR(Debug::FILES, "Writing file " << it->outputFilename()
496 << " as " << it->inzipName() << endl);
499 // write a zip file with all these files. Write to a temp file first, to
500 // avoid messing up the original file in case something goes terribly wrong.
501 DocFileName zipfile(addName(buffer.temppath(),
502 onlyFilename(changeExtension(
503 filename.toFilesystemEncoding(), ".zip"))));
505 ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
507 if (!zipfile.copyTo(filename)) {
508 Alert::error(_("Save failure"),
509 bformat(_("Cannot create file %1$s.\n"
510 "Please check whether the directory exists and is writeable."),
511 from_utf8(filename.absFilename())));
512 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());