]> git.lyx.org Git - lyx.git/blob - src/EmbeddedFiles.cpp
Embedding: fix a few embedding bugs
[lyx.git] / src / EmbeddedFiles.cpp
1 // -*- C++ -*-
2 /**
3  * \file EmbeddedFiles.cpp
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Bo Peng
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "EmbeddedFiles.h"
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "Paragraph.h"
19 #include "ParIterator.h"
20 #include "debug.h"
21 #include "gettext.h"
22 #include "Format.h"
23
24 #include "frontends/alert.h"
25
26 #include <boost/filesystem/operations.hpp>
27
28 #include "support/filetools.h"
29 #include "support/fs_extras.h"
30 #include "support/convert.h"
31 #include "support/lyxlib.h"
32 #include "support/lstrings.h"
33
34 #include <sstream>
35 #include <fstream>
36 #include <utility>
37
38 using std::ofstream;
39 using std::endl;
40 using std::vector;
41 using std::string;
42 using std::pair;
43 using std::make_pair;
44 using std::istream;
45 using std::ostream;
46 using std::getline;
47 using std::istringstream;
48
49 namespace lyx {
50
51 namespace fs = boost::filesystem;
52 namespace Alert = frontend::Alert;
53
54 using support::FileName;
55 using support::DocFileName;
56 using support::makeAbsPath;
57 using support::addName;
58 using support::onlyPath;
59 using support::absolutePath;
60 using support::onlyFilename;
61 using support::makeRelPath;
62 using support::changeExtension;
63 using support::bformat;
64 using support::zipFiles;
65 using support::prefixIs;
66 using support::sum;
67 using support::makedir;
68
69
70 EmbeddedFile::EmbeddedFile(string const & file, string const & inzip_name,
71         STATUS status, ParConstIterator const & pit)
72         : DocFileName(file, true), inzip_name_(inzip_name), status_(status),
73                 valid_(true), par_it_(pit)
74 {}
75
76
77 string EmbeddedFile::embeddedFile(Buffer const * buf) const
78 {
79         return addName(buf->temppath(), inzip_name_);
80 }
81
82
83 int const EmbeddedFile::parID() const
84 {
85         // some embedded file do not have a valid par iterator
86         return par_it_ == ParConstIterator() ? 0 : par_it_->id();
87 }
88
89
90 void EmbeddedFile::setParIter(ParConstIterator const & pit)
91 {
92         par_it_ = pit;
93 }
94
95
96 string EmbeddedFile::availableFile(Buffer const * buf) const
97 {
98         string ext_file = absFilename();
99         string emb_file = embeddedFile(buf);
100         if (status_ == AUTO) {
101                 // use external file first
102                 if (fs::exists(ext_file))
103                         return ext_file;
104                 else if (fs::exists(emb_file))
105                         return emb_file;
106                 else
107                         return string();
108         } else if (status_ == EMBEDDED) {
109                 // use embedded file first
110                 if (fs::exists(emb_file))
111                         return emb_file;
112                 else if (fs::exists(ext_file))
113                         return ext_file;
114                 else
115                         return string();
116         } else
117                 return string();
118 }
119
120
121 bool EmbeddedFile::extract(Buffer const * buf) const
122 {
123         string ext_file = absFilename();
124         string emb_file = embeddedFile(buf);
125         bool copyFile = false;
126         // both files exist, are different, and in EMBEDDED status
127         if (fs::exists(ext_file) && fs::exists(emb_file) && status_ == EMBEDDED
128                 && sum(*this) != sum(FileName(emb_file))) {
129                 int const ret = Alert::prompt(
130                         _("Overwrite external file?"),
131                         bformat(_("External file %1$s already exists, do you want to overwrite it"),
132                                 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
133                 copyFile = ret == 0;
134         }
135         // copy file in the previous case, and a new case
136         if (copyFile || (!fs::exists(ext_file) && fs::exists(emb_file))) {
137                 try {
138                         // need to make directory?
139                         string path = onlyPath(ext_file);
140                         if (!fs::is_directory(path))
141                                 makedir(const_cast<char*>(path.c_str()), 0755);
142                         fs::copy_file(emb_file, ext_file, false);
143                         return true;
144                 } catch (fs::filesystem_error const & fe) {
145                         Alert::error(_("Copy file failure"),
146                                  bformat(_("Cannot copy file %1$s to %2$s.\n"
147                                            "Please check whether the directory exists and is writeable."),
148                                                 from_utf8(emb_file), from_utf8(ext_file)));
149                         LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
150                 }
151         }
152         return false;
153 }
154
155  
156 bool EmbeddedFiles::enabled() const
157 {
158         return buffer_->params().embedded;
159 }
160
161
162 void EmbeddedFiles::enable(bool flag)
163 {
164         if (enabled() != flag) {
165                 // if disable embedding, first extract all embedded files
166                 if (flag || (!flag && extractAll())) {
167                         // file will be changed
168                         buffer_->markDirty();
169                         buffer_->params().embedded = flag;
170                 }
171         }
172 }
173
174
175 void EmbeddedFiles::registerFile(string const & filename,
176         EmbeddedFile::STATUS status, ParConstIterator const & pit)
177 {
178         string abs_filename = makeAbsPath(filename, buffer_->filePath()).absFilename();
179         // try to find this file from the list
180         EmbeddedFileList::iterator it = file_list_.begin();
181         EmbeddedFileList::iterator it_end = file_list_.end();
182         for (; it != it_end; ++it)
183                 if (it->absFilename() == abs_filename)
184                         break;
185         // find this filename
186         if (it != file_list_.end()) {
187                 it->setParIter(pit);
188                 it->setStatus(status);
189                 it->validate();
190                 return;
191         }
192         file_list_.push_back(EmbeddedFile(abs_filename, 
193                 getInzipName(abs_filename), status, pit));
194 }
195
196
197 void EmbeddedFiles::update()
198 {
199         // invalidate all files, obsolete files will then not be validated by the
200         // following document scan. These files will still be kept though, because
201         // they may be added later and their embedding status will be meaningful
202         // again (thinking of cut/paste of an InsetInclude).
203         EmbeddedFileList::iterator it = file_list_.begin();
204         EmbeddedFileList::iterator it_end = file_list_.end();
205         for (; it != it_end; ++it)
206                 // Only AUTO files will be updated. If the status of a file is EMBEDDED, 
207                 // it will be embedded even if it is not referred by a document.
208                 if (it->status() == EmbeddedFile::AUTO)
209                         it->invalidate();
210
211         ParIterator pit = buffer_->par_iterator_begin();
212         ParIterator pit_end = buffer_->par_iterator_end();
213         for (; pit != pit_end; ++pit) {
214                 // For each paragraph, traverse its insets and register embedded files
215                 InsetList::const_iterator iit = pit->insetlist.begin();
216                 InsetList::const_iterator iit_end = pit->insetlist.end();
217                 for (; iit != iit_end; ++iit) {
218                         Inset & inset = *iit->inset;
219                         inset.registerEmbeddedFiles(*buffer_, *this, pit);
220                 }
221         }
222         LYXERR(Debug::FILES) << "Manifest updated: " << endl
223                 << *this
224                 << "End Manifest" << endl;
225 }
226
227
228 bool EmbeddedFiles::write(DocFileName const & filename)
229 {
230         // file in the temporary path has the content
231         string const content = FileName(addName(buffer_->temppath(),
232                 onlyFilename(filename.toFilesystemEncoding()))).toFilesystemEncoding();
233
234         // get a file list and write a manifest file
235         vector<pair<string, string> > filenames;
236         string const manifest = FileName(
237                 addName(buffer_->temppath(), "manifest.txt")).toFilesystemEncoding();
238
239         // write a manifest file
240         ofstream os(manifest.c_str());
241         os << *this;
242         os.close();
243         // prepare list of embedded file
244         EmbeddedFileList::iterator it = file_list_.begin();
245         EmbeddedFileList::iterator it_end = file_list_.end();
246         for (; it != it_end; ++it) {
247                 if (it->valid() && it->embedded()) {
248                         string file = it->availableFile(buffer_);
249                         if (file.empty())
250                                 lyxerr << "File " << it->absFilename() << " does not exist. Skip embedding it. " << endl;
251                         else
252                                 filenames.push_back(make_pair(file, it->inzipName()));
253                 }
254         }
255         // add filename (.lyx) and manifest to filenames
256         filenames.push_back(make_pair(content, onlyFilename(filename.toFilesystemEncoding())));
257         filenames.push_back(make_pair(manifest, "manifest.txt"));
258         // write a zip file with all these files. Write to a temp file first, to
259         // avoid messing up the original file in case something goes terribly wrong.
260         DocFileName zipfile(addName(buffer_->temppath(),
261                 onlyFilename(changeExtension(
262                         filename.toFilesystemEncoding(), ".zip"))));
263
264         zipFiles(zipfile, filenames);
265         // copy file back
266         try {
267                 fs::copy_file(zipfile.toFilesystemEncoding(), filename.toFilesystemEncoding(), false);
268         } catch (fs::filesystem_error const & fe) {
269                 Alert::error(_("Save failure"),
270                                  bformat(_("Cannot create file %1$s.\n"
271                                            "Please check whether the directory exists and is writeable."),
272                                          from_utf8(filename.absFilename())));
273                 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
274         }
275         return true;
276 }
277
278
279 bool EmbeddedFiles::extractAll() const
280 {
281         EmbeddedFileList::const_iterator it = file_list_.begin();
282         EmbeddedFileList::const_iterator it_end = file_list_.end();
283         // FIXME: the logic here is hard to decide, we should allow cancel for
284         // 'do not overwrite' this file, and cancel for 'cancel extract all files'.
285         // I am not sure how to do this now.
286         for (; it != it_end; ++it)
287                 if (it->valid() && it->status() != EmbeddedFile::EXTERNAL)
288                         it->extract(buffer_);
289         return true;
290 }
291
292
293 string const EmbeddedFiles::getInzipName(string const & abs_filename)
294 {
295         // register a new one, using relative file path as inzip_name
296         string inzip_name = to_utf8(makeRelPath(from_utf8(abs_filename),
297                 from_utf8(buffer_->fileName())));
298         // if inzip_name is an absolute path, use filename only to avoid
299         // leaking of filesystem information in inzip_name
300         // The second case covers cases '../path/file' and '.'
301         if (absolutePath(inzip_name) || prefixIs(inzip_name, "."))
302                 inzip_name = onlyFilename(abs_filename);
303         // if this name has been used...
304         // use _1_name, _2_name etc
305         string tmp = inzip_name;
306         EmbeddedFileList::iterator it;
307         EmbeddedFileList::iterator it_end = file_list_.end();
308         bool unique_name = false;
309         while (!unique_name) {
310                 unique_name = true;
311                 size_t i = 0;
312                 if (i > 0)
313                         inzip_name = convert<string>(i) + "_" + tmp;
314                 it = file_list_.begin();
315                 for (; it != it_end; ++it)
316                         if (it->inzipName() == inzip_name) {
317                                 unique_name = false;
318                                 ++i;
319                                 break;
320                         }
321         }
322         return inzip_name;
323 }
324
325
326 istream & operator>> (istream & is, EmbeddedFiles & files)
327 {
328         files.clear();
329         string tmp;
330         getline(is, tmp);
331         // get version
332         istringstream itmp(tmp);
333         int version;
334         itmp.ignore(string("# LyX manifest version ").size());
335         itmp >> version;
336
337         if (version != 1) {
338                 lyxerr << "This version of LyX can only read LyX manifest version 1" << endl;
339                 return is;
340         }
341
342         getline(is, tmp);
343         if (tmp != "<manifest>") {
344                 lyxerr << "Invalid manifest file, lacking <manifest>" << endl;
345                 return is;
346         }
347         // manifest file may be messed up, be carefully
348         while (is.good()) {
349                 getline(is, tmp);
350                 if (tmp != "<file>")
351                         break;
352
353                 string fname;
354                 getline(is, fname);
355                 string inzip_name;
356                 getline(is, inzip_name);
357                 getline(is, tmp);
358                 istringstream itmp(tmp);
359                 int status;
360                 itmp >> status;
361
362                 getline(is, tmp);
363                 if (tmp != "</file>") {
364                         lyxerr << "Invalid manifest file, lacking </file>" << endl;
365                         break;
366                 }
367
368                 files.registerFile(fname, static_cast<EmbeddedFile::STATUS>(status));
369         };
370         // the last line must be </manifest>
371         if (tmp != "</manifest>") {
372                 lyxerr << "Invalid manifest file, lacking </manifest>" << endl;
373                 return is;
374         }
375         return is;
376 }
377
378
379 ostream & operator<< (ostream & os, EmbeddedFiles const & files)
380 {
381         // store a version so that operator >> can read later versions
382         // using version information.
383         os << "# lyx manifest version 1\n";
384         os << "<manifest>\n";
385         EmbeddedFiles::EmbeddedFileList::const_iterator it = files.begin();
386         EmbeddedFiles::EmbeddedFileList::const_iterator it_end = files.end();
387         for (; it != it_end; ++it) {
388                 if (!it->valid())
389                         continue;
390                 // use differnt lines to make reading easier.
391                 os << "<file>\n"
392                         // save the relative path
393                         << to_utf8(makeRelPath(from_utf8(it->absFilename()),
394                                 from_utf8(files.buffer_->filePath()))) << '\n'
395                         << it->inzipName() << '\n'
396                         << it->status() << '\n'
397                         << "</file>\n";
398         }
399         os << "</manifest>\n";
400         return os;
401 }
402
403 }