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 inzip_name_ = calcInzipName(buffer_path);
66 void EmbeddedFile::setInzipName(std::string const & name)
68 if (name.empty() || name == inzip_name_)
71 // an enabled EmbeededFile should have this problem handled
72 BOOST_ASSERT(!enabled());
73 // file will be synced when it is enabled
78 string EmbeddedFile::embeddedFile() const
80 BOOST_ASSERT(enabled());
81 return temp_path_ + inzip_name_;
85 FileName EmbeddedFile::availableFile() const
87 if (enabled() && embedded())
88 return FileName(embeddedFile());
94 string EmbeddedFile::latexFilename(std::string const & buffer_path) const
96 return (enabled() && embedded()) ? inzip_name_ : relFilename(buffer_path);
100 void EmbeddedFile::addInset(Inset const * inset)
103 inset_list_.push_back(inset);
107 void EmbeddedFile::setEmbed(bool embed)
113 void EmbeddedFile::enable(bool flag, Buffer const * buf)
116 temp_path_ = buf->temppath();
117 if (!suffixIs(temp_path_, '/'))
120 if (inzip_name_ != calcInzipName(buf->filePath()))
121 syncInzipFile(buf->filePath());
122 updateFromExternalFile();
132 bool EmbeddedFile::extract() const
134 BOOST_ASSERT(enabled());
136 string ext_file = absFilename();
137 string emb_file = embeddedFile();
139 FileName emb(emb_file);
140 FileName ext(ext_file);
146 throw ExceptionMessage(ErrorException, _("Failed to extract file"),
147 bformat(_("Cannot extract file '%1$s'.\n"
148 "Source file %2$s does not exist"),
149 from_utf8(outputFilename()), from_utf8(emb_file)));
152 // if external file already exists ...
154 // no need to copy if the files are the same
155 if (checksum() == FileName(emb_file).checksum())
157 // otherwise, ask if overwrite
158 int ret = Alert::prompt(
159 _("Overwrite external file?"),
160 bformat(_("External file %1$s already exists, do you want to overwrite it"),
161 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
163 // if the user does not want to overwrite, we still consider it
164 // a successful operation.
169 // need to make directory?
170 FileName path = ext.onlyPath();
171 if (!path.createPath()) {
172 throw ExceptionMessage(ErrorException, _("Copy file failure"),
173 bformat(_("Cannot create file path '%1$s'.\n"
174 "Please check whether the path is writeable."),
175 from_utf8(path.absFilename())));
179 if (emb.copyTo(ext)) {
180 LYXERR(Debug::FILES, "Extract file " << emb_file << " to " << ext_file << endl);
184 throw ExceptionMessage(ErrorException, _("Copy file failure"),
185 bformat(_("Cannot copy file %1$s to %2$s.\n"
186 "Please check whether the directory exists and is writeable."),
187 from_utf8(emb_file), from_utf8(ext_file)));
192 bool EmbeddedFile::updateFromExternalFile() const
194 BOOST_ASSERT(enabled());
196 string ext_file = absFilename();
197 string emb_file = embeddedFile();
199 FileName emb(emb_file);
200 FileName ext(ext_file);
206 // no external and internal file
207 throw ExceptionMessage(ErrorException,
208 _("Failed to embed file"),
209 bformat(_("Failed to embed file %1$s.\n"
210 "Please check whether this file exists and is readable."),
211 from_utf8(ext_file)));
214 // if embedded file already exists ...
216 // no need to copy if the files are the same
217 if (checksum() == FileName(emb_file).checksum())
219 // other wise, ask if overwrite
220 int const ret = Alert::prompt(
221 _("Update embedded file?"),
222 bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
223 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
225 // if the user does not want to overwrite, we still consider it
226 // a successful operation.
230 // need to make directory?
231 FileName path = emb.onlyPath();
232 if (!path.isDirectory())
236 throw ExceptionMessage(ErrorException,
237 _("Copy file failure"),
238 bformat(_("Cannot copy file %1$s to %2$s.\n"
239 "Please check whether the directory exists and is writeable."),
240 from_utf8(ext_file), from_utf8(emb_file)));
241 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
246 void EmbeddedFile::updateInsets(Buffer const * buf) const
248 vector<Inset const *>::const_iterator it = inset_list_.begin();
249 vector<Inset const *>::const_iterator it_end = inset_list_.end();
250 for (; it != it_end; ++it)
251 const_cast<Inset *>(*it)->updateEmbeddedFile(*buf, *this);
255 bool EmbeddedFile::isReadableFile() const
257 return availableFile().isReadableFile();
261 unsigned long EmbeddedFile::checksum() const
263 return availableFile().checksum();
267 Under the lyx temp directory, content.lyx and its embedded files are usually
270 $temp/$embDirName/file.lyx
271 $temp/$embDirName/figure1.png for ./figure1.png)
272 $temp/$embDirName/sub/figure2.png for ./sub/figure2.png)
274 This works fine for embedded files that are in the current or deeper directory
275 of the document directory, but not for files such as ../figures/figure.png.
276 A unique name $upDirName is chosen to represent .. in such filenames so that
277 'up' directories can be stored 'down' the directory tree:
279 $temp/$embDirName/$upDirName/figures/figure.png for ../figures/figure.png
280 $temp/$embDirName/$upDirName/$upDirName/figure.png for ../../figure.png
282 This name has to be fixed because it is used in lyx bundled .zip file.
284 Using a similar trick, we use $absDirName for absolute path so that
285 an absolute filename can be saved as
287 $temp/$embDirName/$absDirName/a/absolute/path for /a/absolute/path
290 const std::string embDirName = "LyX.Embedded.Files";
291 const std::string upDirName = "LyX.Embed.Dir.Up";
292 const std::string absDirName = "LyX.Embed.Dir.Abs";
293 const std::string driveName = "LyX.Embed.Drive";
294 const std::string spaceName = "LyX.Embed.Space";
296 std::string EmbeddedFile::calcInzipName(std::string const & buffer_path)
298 string inzipName = to_utf8(makeRelPath(from_utf8(absFilename()),
299 from_utf8(buffer_path)));
301 if (FileName(inzipName).isAbsolute())
302 inzipName = absDirName + '/' + inzipName;
304 // replace .. by upDirName
305 if (prefixIs(inzipName, "."))
306 inzipName = subst(inzipName, "..", upDirName);
307 // replace special characters by their value
308 inzipName = subst(inzipName, ":", driveName);
309 inzipName = subst(inzipName, " ", spaceName);
311 // to avoid name conflict between $docu_path/file and $temp_path/file
312 // embedded files are in a subdirectory of $temp_path.
313 inzipName = embDirName + '/' + inzipName;
318 void EmbeddedFile::syncInzipFile(std::string const & buffer_path)
320 BOOST_ASSERT(enabled());
321 string old_emb_file = temp_path_ + '/' + inzip_name_;
322 FileName old_emb(old_emb_file);
324 LYXERR(Debug::FILES, " OLD ZIP " << old_emb_file <<
325 " NEW ZIP " << calcInzipName(buffer_path));
327 //BOOST_ASSERT(old_emb.exists());
329 string new_inzip_name = calcInzipName(buffer_path);
330 string new_emb_file = temp_path_ + '/' + new_inzip_name;
331 FileName new_emb(new_emb_file);
333 // need to make directory?
334 FileName path = new_emb.onlyPath();
335 if (!path.createPath()) {
336 throw ExceptionMessage(ErrorException, _("Sync file failure"),
337 bformat(_("Cannot create file path '%1$s'.\n"
338 "Please check whether the path is writeable."),
339 from_utf8(path.absFilename())));
343 if (old_emb.copyTo(new_emb)) {
344 LYXERR(Debug::FILES, "Sync inzip file from " << inzip_name_
345 << " to " << new_inzip_name);
346 inzip_name_ = new_inzip_name;
349 throw ExceptionMessage(ErrorException, _("Sync file failure"),
350 bformat(_("Cannot copy file %1$s to %2$s.\n"
351 "Please check whether the directory exists and is writeable."),
352 from_utf8(old_emb_file), from_utf8(new_emb_file)));
356 bool operator==(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
358 return lhs.absFilename() == rhs.absFilename()
359 && lhs.saveAbsPath() == rhs.saveAbsPath()
360 && lhs.embedded() == rhs.embedded();
364 bool operator!=(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
366 return !(lhs == rhs);
370 void EmbeddedFileList::enable(bool flag, Buffer & buffer)
372 if (buffer.embedded() == flag)
375 // update embedded file list
378 int count_embedded = 0;
379 int count_external = 0;
380 std::vector<EmbeddedFile>::iterator it = begin();
381 std::vector<EmbeddedFile>::iterator it_end = end();
382 // an exception may be thrown
383 for (; it != it_end; ++it) {
384 it->enable(flag, &buffer);
390 // if operation is successful (no exception is thrown)
392 buffer.params().embedded = flag;
394 // if the operation is successful, update insets
395 for (it = begin(); it != it_end; ++it)
396 it->updateInsets(&buffer);
400 docstring const msg = bformat(_("%1$d external files are ignored.\n"
401 "%2$d embeddable files are embedded.\n"), count_external, count_embedded);
402 Alert::information(_("Packing all files"), msg);
404 docstring const msg = bformat(_("%1$d external files are ignored.\n"
405 "%2$d embedded files are extracted.\n"), count_external, count_embedded);
406 Alert::information(_("Unpacking all files"), msg);
411 void EmbeddedFileList::registerFile(EmbeddedFile const & file,
412 Inset const * inset, Buffer const & buffer)
414 BOOST_ASSERT(!buffer.embedded() || file.availableFile().exists());
415 BOOST_ASSERT(!buffer.embedded() || file.enabled());
417 // try to find this file from the list
418 std::vector<EmbeddedFile>::iterator it = begin();
419 std::vector<EmbeddedFile>::iterator it_end = end();
420 for (; it != it_end; ++it)
421 if (it->absFilename() == file.absFilename()) {
422 if (it->embedded() != file.embedded()) {
423 Alert::error(_("Wrong embedding status."),
424 bformat(_("File %1$s is included in more than one insets, "
425 "but with different embedding status. Assuming embedding status."),
426 from_utf8(it->outputFilename())));
428 // update the inset with this embedding status.
429 const_cast<Inset*>(inset)->updateEmbeddedFile(buffer, *it);
436 back().addInset(inset);
440 void EmbeddedFileList::update(Buffer const & buffer)
444 for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
445 it->registerEmbeddedFiles(buffer, *this);
449 bool EmbeddedFileList::writeFile(DocFileName const & filename, Buffer const & buffer)
451 // file in the temporary path has the content
452 string const content = FileName(addName(buffer.temppath(),
453 "content.lyx")).toFilesystemEncoding();
455 vector<pair<string, string> > filenames;
456 // add content.lyx to filenames
457 filenames.push_back(make_pair(content, "content.lyx"));
458 // prepare list of embedded file
460 std::vector<EmbeddedFile>::iterator it = begin();
461 std::vector<EmbeddedFile>::iterator it_end = end();
462 for (; it != it_end; ++it) {
463 if (it->embedded()) {
464 string file = it->embeddedFile();
465 if (!FileName(file).exists())
466 throw ExceptionMessage(ErrorException, _("Failed to write file"),
467 bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
469 filenames.push_back(make_pair(file, it->inzipName()));
470 LYXERR(Debug::FILES, "Writing file " << it->outputFilename()
471 << " as " << it->inzipName() << endl);
474 // write a zip file with all these files. Write to a temp file first, to
475 // avoid messing up the original file in case something goes terribly wrong.
476 DocFileName zipfile(addName(buffer.temppath(),
477 onlyFilename(changeExtension(
478 filename.toFilesystemEncoding(), ".zip"))));
480 ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
482 if (!zipfile.copyTo(filename)) {
483 Alert::error(_("Save failure"),
484 bformat(_("Cannot create file %1$s.\n"
485 "Please check whether the directory exists and is writeable."),
486 from_utf8(filename.absFilename())));
487 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());