]> git.lyx.org Git - lyx.git/blob - src/EmbeddedFiles.cpp
Embedding: add option \extra_embedded_files to buffer params. This increase
[lyx.git] / src / EmbeddedFiles.cpp
1 // -*- C++ -*-
2 /**
3  * \file EmbeddedFileList.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
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "ErrorList.h"
20 #include "Format.h"
21 #include "InsetIterator.h"
22 #include "Lexer.h"
23 #include "LyX.h"
24 #include "Paragraph.h"
25 #include "Session.h"
26
27 #include "frontends/alert.h"
28
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"
36
37 #include <sstream>
38 #include <fstream>
39 #include <utility>
40
41 using namespace std;
42 using namespace lyx::support;
43
44 namespace lyx {
45
46 namespace Alert = frontend::Alert;
47
48 EmbeddedFile::EmbeddedFile(string const & file, std::string const & buffer_path)
49         : DocFileName("", false), inzip_name_(""), embedded_(false), inset_list_(),
50         temp_path_("")
51 {
52         set(file, buffer_path);
53 }
54
55
56 void EmbeddedFile::set(std::string const & filename, std::string const & buffer_path)
57 {
58         DocFileName::set(filename, buffer_path);
59         if (filename.empty())
60                 return;
61
62         if (!buffer_path.empty())
63                 inzip_name_ = calcInzipName(buffer_path);
64 }
65
66
67 void EmbeddedFile::setInzipName(std::string const & name)
68 {
69         if (name.empty() || name == inzip_name_)
70                 return;
71
72         // an enabled EmbeededFile should have this problem handled
73         BOOST_ASSERT(!enabled());
74         // file will be synced when it is enabled
75         inzip_name_ = name;
76 }
77
78
79 string EmbeddedFile::embeddedFile() const
80 {
81         BOOST_ASSERT(enabled());
82         return temp_path_ + inzip_name_;
83 }
84
85
86 FileName EmbeddedFile::availableFile() const
87 {
88         if (enabled() && embedded())
89                 return FileName(embeddedFile());
90         else
91                 return *this;
92 }
93
94
95 string EmbeddedFile::latexFilename(std::string const & buffer_path) const
96 {
97         return (enabled() && embedded()) ? inzip_name_ : relFilename(buffer_path);
98 }
99
100
101 void EmbeddedFile::addInset(Inset const * inset)
102 {
103         if (inset != NULL)
104                 inset_list_.push_back(inset);
105 }
106
107
108 void EmbeddedFile::setEmbed(bool embed)
109 {
110         embedded_ = embed;
111 }
112
113
114 void EmbeddedFile::enable(bool flag, Buffer const * buf, bool updateFile)
115 {
116         // This function will be called when
117         // 1. through EmbeddedFiles::enable() when a file is read. Files
118         //    should be in place so no updateFromExternalFile or extract()
119         //    should be called. (updateFile should be false in this case).
120         // 2. through menu item enable/disable. updateFile should be true.
121         // 3. A single embedded file is added or modified. updateFile
122         //    can be true or false.
123         LYXERR(Debug::FILES, (flag ? "Enable" : "Disable") 
124                 << " " << absFilename() 
125                 << (updateFile ? " (update file)." : " (no update)."));
126
127         if (flag) {
128                 temp_path_ = buf->temppath();
129                 if (!suffixIs(temp_path_, '/'))
130                         temp_path_ += '/';
131                 if (embedded()) {
132                         if (inzip_name_ != calcInzipName(buf->filePath()))
133                                 syncInzipFile(buf->filePath());
134                         if (updateFile)
135                                 updateFromExternalFile();
136                 }
137         } else {
138                 if (embedded() && updateFile)
139                         extract();
140                 temp_path_ = "";
141         }
142 }
143
144
145 bool EmbeddedFile::extract() const
146 {
147         BOOST_ASSERT(enabled());
148
149         string ext_file = absFilename();
150         string emb_file = embeddedFile();
151
152         FileName emb(emb_file);
153         FileName ext(ext_file);
154
155         if (!emb.exists()) {
156                 if (ext.exists())
157                         return true;
158                 else
159                         throw ExceptionMessage(ErrorException, _("Failed to extract file"),
160                                 bformat(_("Cannot extract file '%1$s'.\n"
161                                 "Source file %2$s does not exist"),
162                                 from_utf8(outputFilename()), from_utf8(emb_file)));
163         }
164
165         // if external file already exists ...
166         if (ext.exists()) {
167                 // no need to copy if the files are the same
168                 if (checksum() == FileName(emb_file).checksum())
169                         return true;
170                 // otherwise, ask if overwrite
171                 int ret = Alert::prompt(
172                         _("Overwrite external file?"),
173                         bformat(_("External file %1$s already exists, do you want to overwrite it"),
174                                 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
175                 if (ret != 0)
176                         // if the user does not want to overwrite, we still consider it
177                         // a successful operation.
178                         return true;
179         }
180         // copy file
181
182         // need to make directory?
183         FileName path = ext.onlyPath();
184         if (!path.createPath()) {
185                 throw ExceptionMessage(ErrorException, _("Copy file failure"),
186                         bformat(_("Cannot create file path '%1$s'.\n"
187                         "Please check whether the path is writeable."),
188                         from_utf8(path.absFilename())));
189                 return false;
190         }
191
192         if (emb.copyTo(ext)) {
193                 LYXERR(Debug::FILES, "Extract file " << emb_file << " to " << ext_file << endl);
194                 return true;
195         }
196
197         throw ExceptionMessage(ErrorException, _("Copy file failure"),
198                  bformat(_("Cannot copy file %1$s to %2$s.\n"
199                                  "Please check whether the directory exists and is writeable."),
200                                 from_utf8(emb_file), from_utf8(ext_file)));
201         return false;
202 }
203
204
205 bool EmbeddedFile::updateFromExternalFile() const
206 {
207         BOOST_ASSERT(enabled());
208
209         string ext_file = absFilename();
210         string emb_file = embeddedFile();
211
212         FileName emb(emb_file);
213         FileName ext(ext_file);
214
215         if (!ext.exists()) {
216                 // no need to update
217                 if (emb.exists())
218                         return true;
219                 // no external and internal file
220                 throw ExceptionMessage(ErrorException,
221                         _("Failed to embed file"),
222                         bformat(_("Failed to embed file %1$s.\n"
223                            "Please check whether this file exists and is readable."),
224                                 from_utf8(ext_file)));
225         }
226
227         // if embedded file already exists ...
228         if (emb.exists()) {
229                 // no need to copy if the files are the same
230                 if (checksum() == FileName(emb_file).checksum())
231                         return true;
232                 // other wise, ask if overwrite
233                 int const ret = Alert::prompt(
234                         _("Update embedded file?"),
235                         bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
236                                 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
237                 if (ret != 0)
238                         // if the user does not want to overwrite, we still consider it
239                         // a successful operation.
240                         return true;
241         }
242         // copy file
243         // need to make directory?
244         FileName path = emb.onlyPath();
245         if (!path.isDirectory())
246                 path.createPath();
247         if (ext.copyTo(emb))
248                 return true;
249         throw ExceptionMessage(ErrorException,
250                 _("Copy file failure"),
251                 bformat(_("Cannot copy file %1$s to %2$s.\n"
252                            "Please check whether the directory exists and is writeable."),
253                                 from_utf8(ext_file), from_utf8(emb_file)));
254         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
255         return false;
256 }
257
258
259 void EmbeddedFile::updateInsets() const
260 {
261         vector<Inset const *>::const_iterator it = inset_list_.begin();
262         vector<Inset const *>::const_iterator it_end = inset_list_.end();
263         for (; it != it_end; ++it)
264                 const_cast<Inset *>(*it)->updateEmbeddedFile(*this);
265 }
266
267
268 bool EmbeddedFile::isReadableFile() const
269 {
270         return availableFile().isReadableFile();
271 }
272
273
274 unsigned long EmbeddedFile::checksum() const
275 {
276         return availableFile().checksum();
277 }
278
279 /**
280 Under the lyx temp directory, content.lyx and its embedded files are usually
281 saved as
282
283 $temp/$embDirName/file.lyx
284 $temp/$embDirName/figure1.png     for ./figure1.png)
285 $temp/$embDirName/sub/figure2.png for ./sub/figure2.png)
286
287 This works fine for embedded files that are in the current or deeper directory
288 of the document directory, but not for files such as ../figures/figure.png.
289 A unique name $upDirName is chosen to represent .. in such filenames so that
290 'up' directories can be stored 'down' the directory tree:
291
292 $temp/$embDirName/$upDirName/figures/figure.png     for ../figures/figure.png
293 $temp/$embDirName/$upDirName/$upDirName/figure.png  for ../../figure.png
294
295 This name has to be fixed because it is used in lyx bundled .zip file.
296
297 Using a similar trick, we use $absDirName for absolute path so that
298 an absolute filename can be saved as
299
300 $temp/$embDirName/$absDirName/a/absolute/path for /a/absolute/path
301
302 */
303 const std::string embDirName = "LyX.Embedded.Files";
304 const std::string upDirName = "LyX.Embed.Dir.Up";
305 const std::string absDirName = "LyX.Embed.Dir.Abs";
306 const std::string driveName = "LyX.Embed.Drive";
307 const std::string spaceName = "LyX.Embed.Space";
308
309 std::string EmbeddedFile::calcInzipName(std::string const & buffer_path)
310 {
311         string inzipName = to_utf8(makeRelPath(from_utf8(absFilename()),
312                         from_utf8(buffer_path)));
313         
314         if (FileName(inzipName).isAbsolute())
315                 inzipName = absDirName + '/' + inzipName;
316
317         // replace .. by upDirName
318         if (prefixIs(inzipName, "."))
319                 inzipName = subst(inzipName, "..", upDirName);
320         // replace special characters by their value
321         inzipName = subst(inzipName, ":", driveName);
322         inzipName = subst(inzipName, " ", spaceName);
323
324         // to avoid name conflict between $docu_path/file and $temp_path/file
325         // embedded files are in a subdirectory of $temp_path.
326         inzipName = embDirName + '/' + inzipName;
327         return inzipName;
328 }
329
330
331 void EmbeddedFile::syncInzipFile(std::string const & buffer_path)
332 {
333         BOOST_ASSERT(enabled());
334         string old_emb_file = temp_path_ + '/' + inzip_name_;
335         FileName old_emb(old_emb_file);
336
337         LYXERR(Debug::FILES, " OLD ZIP " << old_emb_file <<
338                 " NEW ZIP " << calcInzipName(buffer_path));
339
340         //BOOST_ASSERT(old_emb.exists());
341         
342         string new_inzip_name = calcInzipName(buffer_path);
343         string new_emb_file = temp_path_ + '/' + new_inzip_name;
344         FileName new_emb(new_emb_file);
345         
346         // need to make directory?
347         FileName path = new_emb.onlyPath();
348         if (!path.createPath()) {
349                 throw ExceptionMessage(ErrorException, _("Sync file failure"),
350                         bformat(_("Cannot create file path '%1$s'.\n"
351                         "Please check whether the path is writeable."),
352                         from_utf8(path.absFilename())));
353                 return;
354         }
355
356         if (old_emb.copyTo(new_emb)) {
357                 LYXERR(Debug::FILES, "Sync inzip file from " << inzip_name_ 
358                         << " to " << new_inzip_name);
359                 inzip_name_ = new_inzip_name;
360                 return;
361         }
362         throw ExceptionMessage(ErrorException, _("Sync file failure"),
363                  bformat(_("Cannot copy file %1$s to %2$s.\n"
364                                  "Please check whether the directory exists and is writeable."),
365                                 from_utf8(old_emb_file), from_utf8(new_emb_file)));
366 }
367
368
369 bool operator==(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
370 {
371         return lhs.absFilename() == rhs.absFilename()
372                 && lhs.saveAbsPath() == rhs.saveAbsPath()
373                 && lhs.embedded() == rhs.embedded();
374 }
375
376
377 bool operator!=(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
378 {
379         return !(lhs == rhs);
380 }
381
382
383 void EmbeddedFileList::enable(bool flag, Buffer & buffer, bool updateFile)
384 {
385         // update embedded file list
386         update(buffer);
387         
388         int count_embedded = 0;
389         int count_external = 0;
390         iterator it = begin();
391         iterator it_end = end();
392         // an exception may be thrown
393         for (; it != it_end; ++it) {
394                 it->enable(flag, &buffer, updateFile);
395                 if (it->embedded())
396                         ++count_embedded;
397                 else
398                         ++count_external;
399         }
400         // if operation is successful (no exception is thrown)
401         buffer.markDirty();
402         buffer.params().embedded = flag;
403
404         // if the operation is successful, update insets
405         for (it = begin(); it != it_end; ++it)
406                 it->updateInsets();
407
408         if (!updateFile)
409                 return;
410
411         // show result
412         if (flag) {
413                 docstring const msg = bformat(_("%1$d external files are ignored.\n"
414                         "%2$d embeddable files are embedded.\n"), count_external, count_embedded);
415                 Alert::information(_("Packing all files"), msg);
416         } else {
417                 docstring const msg = bformat(_("%1$d external files are ignored.\n"
418                         "%2$d embedded files are extracted.\n"), count_external, count_embedded);
419                 Alert::information(_("Unpacking all files"), msg);
420         }
421 }
422
423
424 void EmbeddedFileList::registerFile(EmbeddedFile const & file,
425         Inset const * inset, Buffer const & buffer)
426 {
427         BOOST_ASSERT(!buffer.embedded() || file.enabled());
428
429         // try to find this file from the list
430         std::vector<EmbeddedFile>::iterator it = begin();
431         std::vector<EmbeddedFile>::iterator it_end = end();
432         for (; it != it_end; ++it)
433                 if (it->absFilename() == file.absFilename()) {
434                         if (it->embedded() != file.embedded()) {
435                                 Alert::error(_("Wrong embedding status."),
436                                         bformat(_("File %1$s is included in more than one insets, "
437                                                 "but with different embedding status. Assuming embedding status."),
438                                                 from_utf8(it->outputFilename())));
439                                 it->setEmbed(true);
440                                 // update the inset with this embedding status.
441                                 const_cast<Inset*>(inset)->updateEmbeddedFile(*it);
442                         }
443                         it->addInset(inset);
444                         return;
445                 }
446         //
447         file.clearInsets();
448         push_back(file);
449         back().addInset(inset);
450 }
451
452
453 void EmbeddedFileList::update(Buffer const & buffer)
454 {
455         clear();
456
457         for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
458                 it->registerEmbeddedFiles(*this);
459
460         // add extra embedded files
461         vector<string> extra = buffer.params().extraEmbeddedFiles();
462         vector<string>::iterator it = extra.begin();
463         vector<string>::iterator it_end = extra.end();
464         for (; it != it_end; ++it) {
465                 EmbeddedFile file = EmbeddedFile(*it, buffer.filePath());
466                 file.setEmbed(true);
467                 file.enable(buffer.embedded(), &buffer, true);
468                 insert(end(), file);
469         }
470 }
471
472
473 bool EmbeddedFileList::writeFile(DocFileName const & filename, Buffer const & buffer)
474 {
475         // file in the temporary path has the content
476         string const content = FileName(addName(buffer.temppath(),
477                 "content.lyx")).toFilesystemEncoding();
478
479         vector<pair<string, string> > filenames;
480         // add content.lyx to filenames
481         filenames.push_back(make_pair(content, "content.lyx"));
482         // prepare list of embedded file
483         update(buffer);
484         //
485         iterator it = begin();
486         iterator it_end = end();
487         for (; it != it_end; ++it) {
488                 if (it->embedded()) {
489                         string file = it->embeddedFile();
490                         if (!FileName(file).exists())
491                                 throw ExceptionMessage(ErrorException, _("Failed to write file"),
492                                         bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
493                                                 it->displayName()));
494                         filenames.push_back(make_pair(file, it->inzipName()));
495                         LYXERR(Debug::FILES, "Writing file " << it->outputFilename()
496                                 << " as " << it->inzipName() << endl);
497                 }
498         }
499         // write a zip file with all these files. Write to a temp file first, to
500         // avoid messing up the original file in case something goes terribly wrong.
501         DocFileName zipfile(addName(buffer.temppath(),
502                 onlyFilename(changeExtension(
503                         filename.toFilesystemEncoding(), ".zip"))));
504
505         ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
506         // copy file back
507         if (!zipfile.copyTo(filename)) {
508                 Alert::error(_("Save failure"),
509                                  bformat(_("Cannot create file %1$s.\n"
510                                            "Please check whether the directory exists and is writeable."),
511                                          from_utf8(filename.absFilename())));
512                 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
513         }
514         return true;
515 }
516
517 } // namespace lyx