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, bool updateFile)
115 // This function will be called when
116 // 1. through EmbeddedFiles::enable() when a file is read. Files
117 // should be in place so no updateFromExternalFile or extract()
118 // should be called. (updateFile should be false in this case).
119 // 2. through menu item enable/disable. updateFile should be true.
120 // 3. A single embedded file is added or modified. updateFile
121 // can be true or false.
122 LYXERR(Debug::FILES, (flag ? "Enable" : "Disable")
123 << " " << absFilename()
124 << (updateFile ? " (update file)." : " (no update)."));
127 temp_path_ = buf->temppath();
128 if (!suffixIs(temp_path_, '/'))
131 if (inzip_name_ != calcInzipName(buf->filePath()))
132 syncInzipFile(buf->filePath());
134 updateFromExternalFile();
137 if (embedded() && updateFile)
144 bool EmbeddedFile::extract() const
146 BOOST_ASSERT(enabled());
148 string ext_file = absFilename();
149 string emb_file = embeddedFile();
151 FileName emb(emb_file);
152 FileName ext(ext_file);
158 throw ExceptionMessage(ErrorException, _("Failed to extract file"),
159 bformat(_("Cannot extract file '%1$s'.\n"
160 "Source file %2$s does not exist"),
161 from_utf8(outputFilename()), from_utf8(emb_file)));
164 // if external file already exists ...
166 // no need to copy if the files are the same
167 if (checksum() == FileName(emb_file).checksum())
169 // otherwise, ask if overwrite
170 int ret = Alert::prompt(
171 _("Overwrite external file?"),
172 bformat(_("External file %1$s already exists, do you want to overwrite it"),
173 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
175 // if the user does not want to overwrite, we still consider it
176 // a successful operation.
181 // need to make directory?
182 FileName path = ext.onlyPath();
183 if (!path.createPath()) {
184 throw ExceptionMessage(ErrorException, _("Copy file failure"),
185 bformat(_("Cannot create file path '%1$s'.\n"
186 "Please check whether the path is writeable."),
187 from_utf8(path.absFilename())));
191 if (emb.copyTo(ext)) {
192 LYXERR(Debug::FILES, "Extract file " << emb_file << " to " << ext_file << endl);
196 throw ExceptionMessage(ErrorException, _("Copy file failure"),
197 bformat(_("Cannot copy file %1$s to %2$s.\n"
198 "Please check whether the directory exists and is writeable."),
199 from_utf8(emb_file), from_utf8(ext_file)));
204 bool EmbeddedFile::updateFromExternalFile() const
206 BOOST_ASSERT(enabled());
208 string ext_file = absFilename();
209 string emb_file = embeddedFile();
211 FileName emb(emb_file);
212 FileName ext(ext_file);
218 // no external and internal file
219 throw ExceptionMessage(ErrorException,
220 _("Failed to embed file"),
221 bformat(_("Failed to embed file %1$s.\n"
222 "Please check whether this file exists and is readable."),
223 from_utf8(ext_file)));
226 // if embedded file already exists ...
228 // no need to copy if the files are the same
229 if (checksum() == FileName(emb_file).checksum())
231 // other wise, ask if overwrite
232 int const ret = Alert::prompt(
233 _("Update embedded file?"),
234 bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
235 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
237 // if the user does not want to overwrite, we still consider it
238 // a successful operation.
242 // need to make directory?
243 FileName path = emb.onlyPath();
244 if (!path.isDirectory())
248 throw ExceptionMessage(ErrorException,
249 _("Copy file failure"),
250 bformat(_("Cannot copy file %1$s to %2$s.\n"
251 "Please check whether the directory exists and is writeable."),
252 from_utf8(ext_file), from_utf8(emb_file)));
253 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
258 void EmbeddedFile::updateInsets() const
260 vector<Inset const *>::const_iterator it = inset_list_.begin();
261 vector<Inset const *>::const_iterator it_end = inset_list_.end();
262 for (; it != it_end; ++it)
263 const_cast<Inset *>(*it)->updateEmbeddedFile(*this);
267 bool EmbeddedFile::isReadableFile() const
269 return availableFile().isReadableFile();
273 unsigned long EmbeddedFile::checksum() const
275 return availableFile().checksum();
279 Under the lyx temp directory, content.lyx and its embedded files are usually
282 $temp/$embDirName/file.lyx
283 $temp/$embDirName/figure1.png for ./figure1.png)
284 $temp/$embDirName/sub/figure2.png for ./sub/figure2.png)
286 This works fine for embedded files that are in the current or deeper directory
287 of the document directory, but not for files such as ../figures/figure.png.
288 A unique name $upDirName is chosen to represent .. in such filenames so that
289 'up' directories can be stored 'down' the directory tree:
291 $temp/$embDirName/$upDirName/figures/figure.png for ../figures/figure.png
292 $temp/$embDirName/$upDirName/$upDirName/figure.png for ../../figure.png
294 This name has to be fixed because it is used in lyx bundled .zip file.
296 Using a similar trick, we use $absDirName for absolute path so that
297 an absolute filename can be saved as
299 $temp/$embDirName/$absDirName/a/absolute/path for /a/absolute/path
302 const std::string embDirName = "LyX.Embedded.Files";
303 const std::string upDirName = "LyX.Embed.Dir.Up";
304 const std::string absDirName = "LyX.Embed.Dir.Abs";
305 const std::string driveName = "LyX.Embed.Drive";
306 const std::string spaceName = "LyX.Embed.Space";
308 std::string EmbeddedFile::calcInzipName(std::string const & buffer_path)
310 string inzipName = to_utf8(makeRelPath(from_utf8(absFilename()),
311 from_utf8(buffer_path)));
313 if (FileName(inzipName).isAbsolute())
314 inzipName = absDirName + '/' + inzipName;
316 // replace .. by upDirName
317 if (prefixIs(inzipName, "."))
318 inzipName = subst(inzipName, "..", upDirName);
319 // replace special characters by their value
320 inzipName = subst(inzipName, ":", driveName);
321 inzipName = subst(inzipName, " ", spaceName);
323 // to avoid name conflict between $docu_path/file and $temp_path/file
324 // embedded files are in a subdirectory of $temp_path.
325 inzipName = embDirName + '/' + inzipName;
330 void EmbeddedFile::syncInzipFile(std::string const & buffer_path)
332 BOOST_ASSERT(enabled());
333 string old_emb_file = temp_path_ + '/' + inzip_name_;
334 FileName old_emb(old_emb_file);
336 LYXERR(Debug::FILES, " OLD ZIP " << old_emb_file <<
337 " NEW ZIP " << calcInzipName(buffer_path));
339 //BOOST_ASSERT(old_emb.exists());
341 string new_inzip_name = calcInzipName(buffer_path);
342 string new_emb_file = temp_path_ + '/' + new_inzip_name;
343 FileName new_emb(new_emb_file);
345 // need to make directory?
346 FileName path = new_emb.onlyPath();
347 if (!path.createPath()) {
348 throw ExceptionMessage(ErrorException, _("Sync file failure"),
349 bformat(_("Cannot create file path '%1$s'.\n"
350 "Please check whether the path is writeable."),
351 from_utf8(path.absFilename())));
355 if (old_emb.copyTo(new_emb)) {
356 LYXERR(Debug::FILES, "Sync inzip file from " << inzip_name_
357 << " to " << new_inzip_name);
358 inzip_name_ = new_inzip_name;
361 throw ExceptionMessage(ErrorException, _("Sync file failure"),
362 bformat(_("Cannot copy file %1$s to %2$s.\n"
363 "Please check whether the directory exists and is writeable."),
364 from_utf8(old_emb_file), from_utf8(new_emb_file)));
368 bool operator==(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
370 return lhs.absFilename() == rhs.absFilename()
371 && lhs.saveAbsPath() == rhs.saveAbsPath()
372 && lhs.embedded() == rhs.embedded();
376 bool operator!=(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
378 return !(lhs == rhs);
382 void EmbeddedFileList::enable(bool flag, Buffer & buffer, bool updateFile)
384 // update embedded file list
387 int count_embedded = 0;
388 int count_external = 0;
389 std::vector<EmbeddedFile>::iterator it = begin();
390 std::vector<EmbeddedFile>::iterator it_end = end();
391 // an exception may be thrown
392 for (; it != it_end; ++it) {
393 it->enable(flag, &buffer, updateFile);
399 // if operation is successful (no exception is thrown)
401 buffer.params().embedded = flag;
403 // if the operation is successful, update insets
404 for (it = begin(); it != it_end; ++it)
412 docstring const msg = bformat(_("%1$d external files are ignored.\n"
413 "%2$d embeddable files are embedded.\n"), count_external, count_embedded);
414 Alert::information(_("Packing all files"), msg);
416 docstring const msg = bformat(_("%1$d external files are ignored.\n"
417 "%2$d embedded files are extracted.\n"), count_external, count_embedded);
418 Alert::information(_("Unpacking all files"), msg);
423 void EmbeddedFileList::registerFile(EmbeddedFile const & file,
424 Inset const * inset, Buffer const & buffer)
426 BOOST_ASSERT(!buffer.embedded() || file.enabled());
428 // try to find this file from the list
429 std::vector<EmbeddedFile>::iterator it = begin();
430 std::vector<EmbeddedFile>::iterator it_end = end();
431 for (; it != it_end; ++it)
432 if (it->absFilename() == file.absFilename()) {
433 if (it->embedded() != file.embedded()) {
434 Alert::error(_("Wrong embedding status."),
435 bformat(_("File %1$s is included in more than one insets, "
436 "but with different embedding status. Assuming embedding status."),
437 from_utf8(it->outputFilename())));
439 // update the inset with this embedding status.
440 const_cast<Inset*>(inset)->updateEmbeddedFile(*it);
447 back().addInset(inset);
451 void EmbeddedFileList::update(Buffer const & buffer)
455 for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
456 it->registerEmbeddedFiles(*this);
460 bool EmbeddedFileList::writeFile(DocFileName const & filename, Buffer const & buffer)
462 // file in the temporary path has the content
463 string const content = FileName(addName(buffer.temppath(),
464 "content.lyx")).toFilesystemEncoding();
466 vector<pair<string, string> > filenames;
467 // add content.lyx to filenames
468 filenames.push_back(make_pair(content, "content.lyx"));
469 // prepare list of embedded file
471 std::vector<EmbeddedFile>::iterator it = begin();
472 std::vector<EmbeddedFile>::iterator it_end = end();
473 for (; it != it_end; ++it) {
474 if (it->embedded()) {
475 string file = it->embeddedFile();
476 if (!FileName(file).exists())
477 throw ExceptionMessage(ErrorException, _("Failed to write file"),
478 bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
480 filenames.push_back(make_pair(file, it->inzipName()));
481 LYXERR(Debug::FILES, "Writing file " << it->outputFilename()
482 << " as " << it->inzipName() << endl);
485 // write a zip file with all these files. Write to a temp file first, to
486 // avoid messing up the original file in case something goes terribly wrong.
487 DocFileName zipfile(addName(buffer.temppath(),
488 onlyFilename(changeExtension(
489 filename.toFilesystemEncoding(), ".zip"))));
491 ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
493 if (!zipfile.copyTo(filename)) {
494 Alert::error(_("Save failure"),
495 bformat(_("Cannot create file %1$s.\n"
496 "Please check whether the directory exists and is writeable."),
497 from_utf8(filename.absFilename())));
498 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());