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"
17 #include "BufferParams.h"
18 #include "Paragraph.h"
19 #include "InsetIterator.h"
24 #include "ErrorList.h"
26 #include "frontends/alert.h"
28 #include <boost/filesystem/operations.hpp>
30 #include "support/filetools.h"
31 #include "support/fs_extras.h"
32 #include "support/convert.h"
33 #include "support/lyxlib.h"
34 #include "support/lstrings.h"
52 using std::istringstream;
56 namespace fs = boost::filesystem;
57 namespace Alert = frontend::Alert;
59 using support::FileName;
60 using support::DocFileName;
61 using support::makeAbsPath;
62 using support::addName;
63 using support::onlyPath;
64 using support::absolutePath;
65 using support::onlyFilename;
66 using support::makeRelPath;
67 using support::changeExtension;
68 using support::bformat;
69 using support::prefixIs;
71 using support::makedir;
74 EmbeddedFile::EmbeddedFile(string const & file, string const & inzip_name,
75 bool embed, Inset const * inset)
76 : DocFileName(file, true), inzip_name_(inzip_name), embedded_(embed),
80 inset_list_.push_back(inset);
84 string EmbeddedFile::embeddedFile(Buffer const * buf) const
86 return addName(buf->temppath(), inzip_name_);
90 void EmbeddedFile::addInset(Inset const * inset)
92 inset_list_.push_back(inset);
96 Inset const * EmbeddedFile::inset(int idx) const
98 BOOST_ASSERT(idx < refCount());
99 // some embedded file do not have a valid par iterator
100 return inset_list_[idx];
104 void EmbeddedFile::saveBookmark(Buffer const * buf, int idx) const
106 Inset const * ptr = inset(idx);
107 // This might not be the most efficient method ...
108 for (InsetIterator it = inset_iterator_begin(buf->inset()); it; ++it)
110 // this is basically BufferView::saveBookmark(0)
111 LyX::ref().session().bookmarks().save(
112 FileName(buf->absFileName()),
120 // this inset can not be located. There is something wrong that needs
126 string EmbeddedFile::availableFile(Buffer const * buf) const
128 return embedded() ? embeddedFile(buf) : absFilename();
132 bool EmbeddedFile::extract(Buffer const * buf) const
134 string ext_file = absFilename();
135 string emb_file = embeddedFile(buf);
137 if (!fs::exists(emb_file))
140 // if external file already exists ...
141 if (fs::exists(ext_file)) {
142 // no need to copy if the files are the same
143 if (sum(*this) == sum(FileName(emb_file)))
145 // otherwise, ask if overwrite
146 int ret = Alert::prompt(
147 _("Overwrite external file?"),
148 bformat(_("External file %1$s already exists, do you want to overwrite it"),
149 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
151 // if the user does not want to overwrite, we still consider it
152 // a successful operation.
157 // need to make directory?
158 string path = onlyPath(ext_file);
159 if (!fs::is_directory(path))
160 makedir(const_cast<char*>(path.c_str()), 0755);
161 fs::copy_file(emb_file, ext_file, false);
163 } catch (fs::filesystem_error const & fe) {
164 Alert::error(_("Copy file failure"),
165 bformat(_("Cannot copy file %1$s to %2$s.\n"
166 "Please check whether the directory exists and is writeable."),
167 from_utf8(emb_file), from_utf8(ext_file)));
168 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
174 bool EmbeddedFile::updateFromExternalFile(Buffer const * buf) const
176 string ext_file = absFilename();
177 string emb_file = embeddedFile(buf);
179 if (!fs::exists(ext_file))
182 // if embedded file already exists ...
183 if (fs::exists(emb_file)) {
184 // no need to copy if the files are the same
185 if (sum(*this) == sum(FileName(emb_file)))
187 // other wise, ask if overwrite
188 int const ret = Alert::prompt(
189 _("Update embedded file?"),
190 bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
191 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
193 // if the user does not want to overwrite, we still consider it
194 // a successful operation.
199 // need to make directory?
200 string path = onlyPath(emb_file);
201 if (!fs::is_directory(path))
202 makedir(const_cast<char*>(path.c_str()), 0755);
203 fs::copy_file(ext_file, emb_file, false);
205 } catch (fs::filesystem_error const & fe) {
206 Alert::error(_("Copy file failure"),
207 bformat(_("Cannot copy file %1$s to %2$s.\n"
208 "Please check whether the directory exists and is writeable."),
209 from_utf8(ext_file), from_utf8(emb_file)));
210 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
216 void EmbeddedFile::updateInsets(Buffer const * buf) const
218 vector<Inset const *>::const_iterator it = inset_list_.begin();
219 vector<Inset const *>::const_iterator it_end = inset_list_.end();
220 for (; it != it_end; ++it)
221 const_cast<Inset *>(*it)->updateEmbeddedFile(*buf, *this);
225 bool EmbeddedFiles::enabled() const
227 return buffer_->params().embedded;
231 void EmbeddedFiles::enable(bool flag)
233 if (enabled() != flag) {
234 // if enable, copy all files to temppath()
235 // if disable, extract all files
236 if ((flag && !updateFromExternalFile()) || (!flag && !extract()))
238 // if operation is successful
239 buffer_->markDirty();
240 buffer_->params().embedded = flag;
247 EmbeddedFile & EmbeddedFiles::registerFile(string const & filename,
248 bool embed, Inset const * inset, string const & inzipName)
250 // filename can be relative or absolute, translate to absolute filename
251 string abs_filename = makeAbsPath(filename, buffer_->filePath()).absFilename();
252 // try to find this file from the list
253 EmbeddedFileList::iterator it = file_list_.begin();
254 EmbeddedFileList::iterator it_end = file_list_.end();
255 for (; it != it_end; ++it)
256 if (it->absFilename() == abs_filename || it->embeddedFile(buffer_) == abs_filename)
258 // find this filename, keep the original embedding status
259 if (it != file_list_.end()) {
264 file_list_.push_back(EmbeddedFile(abs_filename,
265 getInzipName(abs_filename, inzipName), embed, inset));
266 return file_list_.back();
270 void EmbeddedFiles::update()
274 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it)
275 it->registerEmbeddedFiles(*buffer_, *this);
279 bool EmbeddedFiles::writeFile(DocFileName const & filename)
281 // file in the temporary path has the content
282 string const content = FileName(addName(buffer_->temppath(),
283 "content.lyx")).toFilesystemEncoding();
285 vector<pair<string, string> > filenames;
286 // add content.lyx to filenames
287 filenames.push_back(make_pair(content, "content.lyx"));
288 // prepare list of embedded file
289 EmbeddedFileList::iterator it = file_list_.begin();
290 EmbeddedFileList::iterator it_end = file_list_.end();
291 for (; it != it_end; ++it) {
292 if (it->embedded()) {
293 string file = it->availableFile(buffer_);
295 lyxerr << "File " << it->absFilename() << " does not exist. Skip embedding it. " << endl;
297 filenames.push_back(make_pair(file, it->inzipName()));
300 // write a zip file with all these files. Write to a temp file first, to
301 // avoid messing up the original file in case something goes terribly wrong.
302 DocFileName zipfile(addName(buffer_->temppath(),
303 onlyFilename(changeExtension(
304 filename.toFilesystemEncoding(), ".zip"))));
306 ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
309 fs::copy_file(zipfile.toFilesystemEncoding(), filename.toFilesystemEncoding(), false);
310 } catch (fs::filesystem_error const & fe) {
311 Alert::error(_("Save failure"),
312 bformat(_("Cannot create file %1$s.\n"
313 "Please check whether the directory exists and is writeable."),
314 from_utf8(filename.absFilename())));
315 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
321 EmbeddedFiles::EmbeddedFileList::const_iterator EmbeddedFiles::find(std::string filename) const
323 EmbeddedFileList::const_iterator it = file_list_.begin();
324 EmbeddedFileList::const_iterator it_end = file_list_.end();
325 for (; it != it_end; ++it)
326 if (it->absFilename() == filename || it->embeddedFile(buffer_) == filename)
328 return file_list_.end();
332 bool EmbeddedFiles::extract() const
334 EmbeddedFileList::const_iterator it = file_list_.begin();
335 EmbeddedFileList::const_iterator it_end = file_list_.end();
336 for (; it != it_end; ++it)
338 if(!it->extract(buffer_))
344 bool EmbeddedFiles::updateFromExternalFile() const
346 EmbeddedFileList::const_iterator it = file_list_.begin();
347 EmbeddedFileList::const_iterator it_end = file_list_.end();
348 for (; it != it_end; ++it)
350 if (!it->updateFromExternalFile(buffer_))
356 string const EmbeddedFiles::getInzipName(string const & abs_filename, string const & name)
358 // register a new one, using relative file path as inzip_name
359 string inzip_name = name;
361 inzip_name = to_utf8(makeRelPath(from_utf8(abs_filename),
362 from_utf8(buffer_->filePath())));
363 // if inzip_name is an absolute path, use filename only to avoid
364 // leaking of filesystem information in inzip_name
365 // The second case covers cases '../path/file' and '.'
366 if (absolutePath(inzip_name) || prefixIs(inzip_name, "."))
367 inzip_name = onlyFilename(abs_filename);
368 // if this name has been used...
369 // use _1_name, _2_name etc
370 string tmp = inzip_name;
371 EmbeddedFileList::iterator it;
372 EmbeddedFileList::iterator it_end = file_list_.end();
373 bool unique_name = false;
375 while (!unique_name) {
378 inzip_name = convert<string>(i) + "_" + tmp;
379 it = file_list_.begin();
380 for (; it != it_end; ++it)
381 if (it->inzipName() == inzip_name) {
391 void EmbeddedFiles::updateInsets() const
393 EmbeddedFiles::EmbeddedFileList::const_iterator it = begin();
394 EmbeddedFiles::EmbeddedFileList::const_iterator it_end = end();
395 for (; it != it_end; ++it)
396 if (it->refCount() > 0)
397 it->updateInsets(buffer_);