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)
115 if (enabled() == flag)
119 temp_path_ = buf->temppath();
120 if (!suffixIs(temp_path_, '/'))
123 if (inzip_name_ != calcInzipName(buf->filePath()))
124 syncInzipFile(buf->filePath());
125 updateFromExternalFile();
134 bool EmbeddedFile::extract() const
136 BOOST_ASSERT(enabled());
138 string ext_file = absFilename();
139 string emb_file = embeddedFile();
141 FileName emb(emb_file);
142 FileName ext(ext_file);
148 throw ExceptionMessage(ErrorException, _("Failed to extract file"),
149 bformat(_("Cannot extract file '%1$s'.\n"
150 "Source file %2$s does not exist"),
151 from_utf8(outputFilename()), from_utf8(emb_file)));
154 // if external file already exists ...
156 // no need to copy if the files are the same
157 if (checksum() == FileName(emb_file).checksum())
159 // otherwise, ask if overwrite
160 int ret = Alert::prompt(
161 _("Overwrite external file?"),
162 bformat(_("External file %1$s already exists, do you want to overwrite it"),
163 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
165 // if the user does not want to overwrite, we still consider it
166 // a successful operation.
171 // need to make directory?
172 FileName path = ext.onlyPath();
173 if (!path.createPath()) {
174 throw ExceptionMessage(ErrorException, _("Copy file failure"),
175 bformat(_("Cannot create file path '%1$s'.\n"
176 "Please check whether the path is writeable."),
177 from_utf8(path.absFilename())));
181 if (emb.copyTo(ext)) {
182 LYXERR(Debug::FILES, "Extract file " << emb_file << " to " << ext_file << endl);
186 throw ExceptionMessage(ErrorException, _("Copy file failure"),
187 bformat(_("Cannot copy file %1$s to %2$s.\n"
188 "Please check whether the directory exists and is writeable."),
189 from_utf8(emb_file), from_utf8(ext_file)));
194 bool EmbeddedFile::updateFromExternalFile() const
196 BOOST_ASSERT(enabled());
198 string ext_file = absFilename();
199 string emb_file = embeddedFile();
201 FileName emb(emb_file);
202 FileName ext(ext_file);
208 // no external and internal file
209 throw ExceptionMessage(ErrorException,
210 _("Failed to embed file"),
211 bformat(_("Failed to embed file %1$s.\n"
212 "Please check whether this file exists and is readable."),
213 from_utf8(ext_file)));
216 // if embedded file already exists ...
218 // no need to copy if the files are the same
219 if (checksum() == FileName(emb_file).checksum())
221 // other wise, ask if overwrite
222 int const ret = Alert::prompt(
223 _("Update embedded file?"),
224 bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
225 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
227 // if the user does not want to overwrite, we still consider it
228 // a successful operation.
232 // need to make directory?
233 FileName path = emb.onlyPath();
234 if (!path.isDirectory())
238 throw ExceptionMessage(ErrorException,
239 _("Copy file failure"),
240 bformat(_("Cannot copy file %1$s to %2$s.\n"
241 "Please check whether the directory exists and is writeable."),
242 from_utf8(ext_file), from_utf8(emb_file)));
243 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
248 void EmbeddedFile::updateInsets(Buffer const * buf) const
250 vector<Inset const *>::const_iterator it = inset_list_.begin();
251 vector<Inset const *>::const_iterator it_end = inset_list_.end();
252 for (; it != it_end; ++it)
253 const_cast<Inset *>(*it)->updateEmbeddedFile(*buf, *this);
257 bool EmbeddedFile::isReadableFile() const
259 return availableFile().isReadableFile();
263 unsigned long EmbeddedFile::checksum() const
265 return availableFile().checksum();
269 Under the lyx temp directory, content.lyx and its embedded files are usually
272 $temp/$embDirName/file.lyx
273 $temp/$embDirName/figure1.png for ./figure1.png)
274 $temp/$embDirName/sub/figure2.png for ./sub/figure2.png)
276 This works fine for embedded files that are in the current or deeper directory
277 of the document directory, but not for files such as ../figures/figure.png.
278 A unique name $upDirName is chosen to represent .. in such filenames so that
279 'up' directories can be stored 'down' the directory tree:
281 $temp/$embDirName/$upDirName/figures/figure.png for ../figures/figure.png
282 $temp/$embDirName/$upDirName/$upDirName/figure.png for ../../figure.png
284 This name has to be fixed because it is used in lyx bundled .zip file.
286 Using a similar trick, we use $absDirName for absolute path so that
287 an absolute filename can be saved as
289 $temp/$embDirName/$absDirName/a/absolute/path for /a/absolute/path
292 const std::string embDirName = "LyX.Embedded.Files";
293 const std::string upDirName = "LyX.Embed.Dir.Up";
294 const std::string absDirName = "LyX.Embed.Dir.Abs";
295 const std::string driveName = "LyX.Embed.Drive";
296 const std::string spaceName = "LyX.Embed.Space";
298 std::string EmbeddedFile::calcInzipName(std::string const & buffer_path)
300 string inzipName = to_utf8(makeRelPath(from_utf8(absFilename()),
301 from_utf8(buffer_path)));
303 if (FileName(inzipName).isAbsolute())
304 inzipName = absDirName + '/' + inzipName;
306 // replace .. by upDirName
307 if (prefixIs(inzipName, "."))
308 inzipName = subst(inzipName, "..", upDirName);
309 // replace special characters by their value
310 inzipName = subst(inzipName, ":", driveName);
311 inzipName = subst(inzipName, " ", spaceName);
313 // to avoid name conflict between $docu_path/file and $temp_path/file
314 // embedded files are in a subdirectory of $temp_path.
315 inzipName = embDirName + '/' + inzipName;
320 void EmbeddedFile::syncInzipFile(std::string const & buffer_path)
322 BOOST_ASSERT(enabled());
323 string old_emb_file = temp_path_ + '/' + inzip_name_;
324 FileName old_emb(old_emb_file);
326 LYXERR(Debug::FILES, " OLD ZIP " << old_emb_file <<
327 " NEW ZIP " << calcInzipName(buffer_path));
329 //BOOST_ASSERT(old_emb.exists());
331 string new_inzip_name = calcInzipName(buffer_path);
332 string new_emb_file = temp_path_ + '/' + new_inzip_name;
333 FileName new_emb(new_emb_file);
335 // need to make directory?
336 FileName path = new_emb.onlyPath();
337 if (!path.createPath()) {
338 throw ExceptionMessage(ErrorException, _("Sync file failure"),
339 bformat(_("Cannot create file path '%1$s'.\n"
340 "Please check whether the path is writeable."),
341 from_utf8(path.absFilename())));
345 if (old_emb.copyTo(new_emb)) {
346 LYXERR(Debug::FILES, "Sync inzip file from " << inzip_name_
347 << " to " << new_inzip_name);
348 inzip_name_ = new_inzip_name;
351 throw ExceptionMessage(ErrorException, _("Sync file failure"),
352 bformat(_("Cannot copy file %1$s to %2$s.\n"
353 "Please check whether the directory exists and is writeable."),
354 from_utf8(old_emb_file), from_utf8(new_emb_file)));
358 bool operator==(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
360 return lhs.absFilename() == rhs.absFilename()
361 && lhs.saveAbsPath() == rhs.saveAbsPath()
362 && lhs.embedded() == rhs.embedded();
366 bool operator!=(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
368 return !(lhs == rhs);
372 void EmbeddedFileList::enable(bool flag, Buffer & buffer)
374 if (buffer.embedded() == flag)
377 // update embedded file list
380 int count_embedded = 0;
381 int count_external = 0;
382 std::vector<EmbeddedFile>::iterator it = begin();
383 std::vector<EmbeddedFile>::iterator it_end = end();
384 // an exception may be thrown
385 for (; it != it_end; ++it) {
386 it->enable(flag, &buffer);
392 // if operation is successful (no exception is thrown)
394 buffer.params().embedded = flag;
396 // if the operation is successful, update insets
397 for (it = begin(); it != it_end; ++it)
398 it->updateInsets(&buffer);
402 docstring const msg = bformat(_("%1$d external files are ignored.\n"
403 "%2$d embeddable files are embedded.\n"), count_external, count_embedded);
404 Alert::information(_("Packing all files"), msg);
406 docstring const msg = bformat(_("%1$d external files are ignored.\n"
407 "%2$d embedded files are extracted.\n"), count_external, count_embedded);
408 Alert::information(_("Unpacking all files"), msg);
413 void EmbeddedFileList::registerFile(EmbeddedFile const & file,
414 Inset const * inset, Buffer const & buffer)
416 BOOST_ASSERT(!buffer.embedded() || file.availableFile().exists());
417 BOOST_ASSERT(!buffer.embedded() || file.enabled());
419 // try to find this file from the list
420 std::vector<EmbeddedFile>::iterator it = begin();
421 std::vector<EmbeddedFile>::iterator it_end = end();
422 for (; it != it_end; ++it)
423 if (it->absFilename() == file.absFilename()) {
424 if (it->embedded() != file.embedded()) {
425 Alert::error(_("Wrong embedding status."),
426 bformat(_("File %1$s is included in more than one insets, "
427 "but with different embedding status. Assuming embedding status."),
428 from_utf8(it->outputFilename())));
430 // update the inset with this embedding status.
431 const_cast<Inset*>(inset)->updateEmbeddedFile(buffer, *it);
438 back().addInset(inset);
442 void EmbeddedFileList::update(Buffer const & buffer)
446 for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
447 it->registerEmbeddedFiles(buffer, *this);
451 bool EmbeddedFileList::writeFile(DocFileName const & filename, Buffer const & buffer)
453 // file in the temporary path has the content
454 string const content = FileName(addName(buffer.temppath(),
455 "content.lyx")).toFilesystemEncoding();
457 vector<pair<string, string> > filenames;
458 // add content.lyx to filenames
459 filenames.push_back(make_pair(content, "content.lyx"));
460 // prepare list of embedded file
462 std::vector<EmbeddedFile>::iterator it = begin();
463 std::vector<EmbeddedFile>::iterator it_end = end();
464 for (; it != it_end; ++it) {
465 if (it->embedded()) {
466 string file = it->embeddedFile();
467 if (!FileName(file).exists())
468 throw ExceptionMessage(ErrorException, _("Failed to write file"),
469 bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
471 filenames.push_back(make_pair(file, it->inzipName()));
472 LYXERR(Debug::FILES, "Writing file " << it->outputFilename()
473 << " as " << it->inzipName() << endl);
476 // write a zip file with all these files. Write to a temp file first, to
477 // avoid messing up the original file in case something goes terribly wrong.
478 DocFileName zipfile(addName(buffer.temppath(),
479 onlyFilename(changeExtension(
480 filename.toFilesystemEncoding(), ".zip"))));
482 ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
484 if (!zipfile.copyTo(filename)) {
485 Alert::error(_("Save failure"),
486 bformat(_("Cannot create file %1$s.\n"
487 "Please check whether the directory exists and is writeable."),
488 from_utf8(filename.absFilename())));
489 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());