]> git.lyx.org Git - lyx.git/blob - src/EmbeddedFiles.cpp
Embed: allow the use of embedded layout and class (.cls, .sty) files.
[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 (updateFile)
133                                 updateFromExternalFile();
134                 }
135         } else {
136                 if (embedded() && updateFile)
137                         extract();
138                 temp_path_ = "";
139         }
140 }
141
142
143 bool EmbeddedFile::extract() const
144 {
145         BOOST_ASSERT(enabled());
146
147         string ext_file = absFilename();
148         string emb_file = embeddedFile();
149
150         FileName emb(emb_file);
151         FileName ext(ext_file);
152
153         if (!emb.exists()) {
154                 if (ext.exists())
155                         return true;
156                 else
157                         throw ExceptionMessage(ErrorException, _("Failed to extract file"),
158                                 bformat(_("Cannot extract file '%1$s'.\n"
159                                 "Source file %2$s does not exist"),
160                                 from_utf8(outputFilename()), from_utf8(emb_file)));
161         }
162
163         // if external file already exists ...
164         if (ext.exists()) {
165                 // no need to copy if the files are the same
166                 if (checksum() == FileName(emb_file).checksum())
167                         return true;
168                 // otherwise, ask if overwrite
169                 int ret = Alert::prompt(
170                         _("Overwrite external file?"),
171                         bformat(_("External file %1$s already exists, do you want to overwrite it"),
172                                 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
173                 if (ret != 0)
174                         // if the user does not want to overwrite, we still consider it
175                         // a successful operation.
176                         return true;
177         }
178         // copy file
179
180         // need to make directory?
181         FileName path = ext.onlyPath();
182         if (!path.createPath()) {
183                 throw ExceptionMessage(ErrorException, _("Copy file failure"),
184                         bformat(_("Cannot create file path '%1$s'.\n"
185                         "Please check whether the path is writeable."),
186                         from_utf8(path.absFilename())));
187                 return false;
188         }
189
190         if (emb.copyTo(ext)) {
191                 LYXERR(Debug::FILES, "Extract file " << emb_file << " to " << ext_file << endl);
192                 return true;
193         }
194
195         throw ExceptionMessage(ErrorException, _("Copy file failure"),
196                  bformat(_("Cannot copy file %1$s to %2$s.\n"
197                                  "Please check whether the directory exists and is writeable."),
198                                 from_utf8(emb_file), from_utf8(ext_file)));
199         return false;
200 }
201
202
203 bool EmbeddedFile::updateFromExternalFile() const
204 {
205         BOOST_ASSERT(enabled());
206
207         string ext_file = absFilename();
208         string emb_file = embeddedFile();
209
210         FileName emb(emb_file);
211         FileName ext(ext_file);
212
213         if (!ext.exists()) {
214                 // no need to update
215                 if (emb.exists())
216                         return true;
217                 // no external and internal file
218                 throw ExceptionMessage(ErrorException,
219                         _("Failed to embed file"),
220                         bformat(_("Failed to embed file %1$s.\n"
221                            "Please check whether this file exists and is readable."),
222                                 from_utf8(ext_file)));
223         }
224
225         // if embedded file already exists ...
226         if (emb.exists()) {
227                 // no need to copy if the files are the same
228                 if (checksum() == FileName(emb_file).checksum())
229                         return true;
230                 // other wise, ask if overwrite
231                 int const ret = Alert::prompt(
232                         _("Update embedded file?"),
233                         bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
234                                 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
235                 if (ret != 0)
236                         // if the user does not want to overwrite, we still consider it
237                         // a successful operation.
238                         return true;
239         }
240         // copy file
241         // need to make directory?
242         FileName path = emb.onlyPath();
243         if (!path.isDirectory())
244                 path.createPath();
245         if (ext.copyTo(emb))
246                 return true;
247         throw ExceptionMessage(ErrorException,
248                 _("Copy file failure"),
249                 bformat(_("Cannot copy file %1$s to %2$s.\n"
250                            "Please check whether the directory exists and is writeable."),
251                                 from_utf8(ext_file), from_utf8(emb_file)));
252         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
253         return false;
254 }
255
256
257 void EmbeddedFile::updateInsets() const
258 {
259         vector<Inset const *>::const_iterator it = inset_list_.begin();
260         vector<Inset const *>::const_iterator it_end = inset_list_.end();
261         for (; it != it_end; ++it)
262                 const_cast<Inset *>(*it)->updateEmbeddedFile(*this);
263 }
264
265
266 bool EmbeddedFile::isReadableFile() const
267 {
268         return availableFile().isReadableFile();
269 }
270
271
272 unsigned long EmbeddedFile::checksum() const
273 {
274         return availableFile().checksum();
275 }
276
277 /**
278 Under the lyx temp directory, content.lyx and its embedded files are usually
279 saved as
280
281 $temp/$embDirName/file.lyx
282 $temp/$embDirName/figure1.png     for ./figure1.png)
283 $temp/$embDirName/sub/figure2.png for ./sub/figure2.png)
284
285 This works fine for embedded files that are in the current or deeper directory
286 of the document directory, but not for files such as ../figures/figure.png.
287 A unique name $upDirName is chosen to represent .. in such filenames so that
288 'up' directories can be stored 'down' the directory tree:
289
290 $temp/$embDirName/$upDirName/figures/figure.png     for ../figures/figure.png
291 $temp/$embDirName/$upDirName/$upDirName/figure.png  for ../../figure.png
292
293 This name has to be fixed because it is used in lyx bundled .zip file.
294
295 Using a similar trick, we use $absDirName for absolute path so that
296 an absolute filename can be saved as
297
298 $temp/$embDirName/$absDirName/a/absolute/path for /a/absolute/path
299
300 FIXME:
301 embDirName is set to . so that embedded layout and class files can be
302 used directly. However, putting all embedded files directly under
303 the temp directory may lead to file conflicts. For example, if a user
304 embeds a file blah.log in blah.lyx, it will be replaced when
305 'latex blah.tex' is called.
306 */
307 const std::string embDirName = ".";
308 const std::string upDirName = "LyX.Embed.Dir.Up";
309 const std::string absDirName = "LyX.Embed.Dir.Abs";
310 const std::string driveName = "LyX.Embed.Drive";
311 const std::string spaceName = "LyX.Embed.Space";
312
313 std::string EmbeddedFile::calcInzipName(std::string const & buffer_path)
314 {
315         string inzipName = to_utf8(makeRelPath(from_utf8(absFilename()),
316                         from_utf8(buffer_path)));
317         
318         if (FileName(inzipName).isAbsolute())
319                 inzipName = absDirName + '/' + inzipName;
320
321         // replace .. by upDirName
322         if (prefixIs(inzipName, "."))
323                 inzipName = subst(inzipName, "..", upDirName);
324         // replace special characters by their value
325         inzipName = subst(inzipName, ":", driveName);
326         inzipName = subst(inzipName, " ", spaceName);
327
328         // to avoid name conflict between $docu_path/file and $temp_path/file
329         // embedded files are in a subdirectory of $temp_path.
330         inzipName = embDirName + '/' + inzipName;
331         return inzipName;
332 }
333
334
335 void EmbeddedFile::syncInzipFile(std::string const & buffer_path)
336 {
337         BOOST_ASSERT(enabled());
338         string old_emb_file = temp_path_ + '/' + inzip_name_;
339         FileName old_emb(old_emb_file);
340
341         if (!old_emb.exists())
342                 throw ExceptionMessage(ErrorException, _("Failed to open file"),
343                         bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
344                                 old_emb.displayName()));
345
346         string new_inzip_name = calcInzipName(buffer_path);
347         if (new_inzip_name == inzip_name_)
348                 return;
349
350         LYXERR(Debug::FILES, " OLD ZIP " << old_emb_file <<
351                 " NEW ZIP " << calcInzipName(buffer_path));
352
353         string new_emb_file = temp_path_ + '/' + new_inzip_name;
354         FileName new_emb(new_emb_file);
355         
356         // need to make directory?
357         FileName path = new_emb.onlyPath();
358         if (!path.createPath()) {
359                 throw ExceptionMessage(ErrorException, _("Sync file failure"),
360                         bformat(_("Cannot create file path '%1$s'.\n"
361                         "Please check whether the path is writeable."),
362                         from_utf8(path.absFilename())));
363                 return;
364         }
365
366         if (old_emb.copyTo(new_emb)) {
367                 LYXERR(Debug::FILES, "Sync inzip file from " << inzip_name_ 
368                         << " to " << new_inzip_name);
369                 inzip_name_ = new_inzip_name;
370                 return;
371         }
372         throw ExceptionMessage(ErrorException, _("Sync file failure"),
373                  bformat(_("Cannot copy file %1$s to %2$s.\n"
374                                  "Please check whether the directory exists and is writeable."),
375                                 from_utf8(old_emb_file), from_utf8(new_emb_file)));
376 }
377
378
379 bool operator==(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
380 {
381         return lhs.absFilename() == rhs.absFilename()
382                 && lhs.saveAbsPath() == rhs.saveAbsPath()
383                 && lhs.embedded() == rhs.embedded();
384 }
385
386
387 bool operator!=(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
388 {
389         return !(lhs == rhs);
390 }
391
392
393 void EmbeddedFileList::enable(bool flag, Buffer & buffer, bool updateFile)
394 {
395         // update embedded file list
396         update(buffer);
397         
398         int count_embedded = 0;
399         int count_external = 0;
400         iterator it = begin();
401         iterator it_end = end();
402         // an exception may be thrown
403         for (; it != it_end; ++it) {
404                 it->enable(flag, &buffer, updateFile);
405                 if (it->embedded())
406                         ++count_embedded;
407                 else
408                         ++count_external;
409         }
410         // if operation is successful (no exception is thrown)
411         buffer.markDirty();
412         buffer.params().embedded = flag;
413
414         // if the operation is successful, update insets
415         for (it = begin(); it != it_end; ++it)
416                 it->updateInsets();
417
418         if (!updateFile)
419                 return;
420
421         // show result
422         if (flag) {
423                 docstring const msg = bformat(_("%1$d external files are ignored.\n"
424                         "%2$d embeddable files are embedded.\n"), count_external, count_embedded);
425                 Alert::information(_("Packing all files"), msg);
426         } else {
427                 docstring const msg = bformat(_("%1$d external files are ignored.\n"
428                         "%2$d embedded files are extracted.\n"), count_external, count_embedded);
429                 Alert::information(_("Unpacking all files"), msg);
430         }
431 }
432
433
434 void EmbeddedFileList::registerFile(EmbeddedFile const & file,
435         Inset const * inset, Buffer const & buffer)
436 {
437         BOOST_ASSERT(!buffer.embedded() || file.enabled());
438
439         // try to find this file from the list
440         std::vector<EmbeddedFile>::iterator it = begin();
441         std::vector<EmbeddedFile>::iterator it_end = end();
442         for (; it != it_end; ++it)
443                 if (it->absFilename() == file.absFilename()) {
444                         if (it->embedded() != file.embedded()) {
445                                 Alert::error(_("Wrong embedding status."),
446                                         bformat(_("File %1$s is included in more than one insets, "
447                                                 "but with different embedding status. Assuming embedding status."),
448                                                 from_utf8(it->outputFilename())));
449                                 it->setEmbed(true);
450                                 // update the inset with this embedding status.
451                                 const_cast<Inset*>(inset)->updateEmbeddedFile(*it);
452                         }
453                         it->addInset(inset);
454                         return;
455                 }
456         //
457         file.clearInsets();
458         push_back(file);
459         back().addInset(inset);
460 }
461
462
463 void EmbeddedFileList::validate(Buffer const & buffer)
464 {
465         clear();
466         
467         for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
468                 it->registerEmbeddedFiles(*this);
469
470         iterator it = begin();
471         iterator it_end = end();
472         for (; it != it_end; ++it) {
473                 if (buffer.embedded() && it->embedded())
474                         // An exception will be raised if inzip file does not exist
475                         it->syncInzipFile(buffer.filePath());
476                 else
477                         // inzipName may be OS dependent
478                         it->setInzipName(it->calcInzipName(buffer.filePath()));
479         }
480         for (it = begin(); it != it_end; ++it)
481                 it->updateInsets();
482         
483         if (!buffer.embedded())
484                 return;
485
486         // check if extra embedded files exist
487         vector<string> extra = buffer.params().extraEmbeddedFiles();
488         vector<string>::iterator e_it = extra.begin();
489         vector<string>::iterator e_end = extra.end();
490         for (; e_it != e_end; ++e_it) {
491                 EmbeddedFile file = EmbeddedFile(*e_it, buffer.filePath());
492                 // do not update from external file
493                 file.enable(true, &buffer, false);
494                 // but we do need to check file existence.
495                 if (!FileName(file.embeddedFile()).exists())
496                         throw ExceptionMessage(ErrorException, _("Failed to open file"),
497                                 bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
498                                         file.displayName()));
499         }
500 }
501
502
503 void EmbeddedFileList::update(Buffer const & buffer)
504 {
505         clear();
506
507         for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
508                 it->registerEmbeddedFiles(*this);
509
510         // add extra embedded files
511         vector<string> extra = buffer.params().extraEmbeddedFiles();
512         vector<string>::iterator it = extra.begin();
513         vector<string>::iterator it_end = extra.end();
514         for (; it != it_end; ++it) {
515                 EmbeddedFile file = EmbeddedFile(*it, buffer.filePath());
516                 file.setEmbed(true);
517                 file.enable(buffer.embedded(), &buffer, false);
518                 insert(end(), file);
519         }
520 }
521
522
523 bool EmbeddedFileList::writeFile(DocFileName const & filename, Buffer const & buffer)
524 {
525         // file in the temporary path has the content
526         string const content = FileName(addName(buffer.temppath(),
527                 "content.lyx")).toFilesystemEncoding();
528
529         vector<pair<string, string> > filenames;
530         // add content.lyx to filenames
531         filenames.push_back(make_pair(content, "content.lyx"));
532         // prepare list of embedded file
533         update(buffer);
534         //
535         iterator it = begin();
536         iterator it_end = end();
537         for (; it != it_end; ++it) {
538                 if (it->embedded()) {
539                         string file = it->embeddedFile();
540                         if (!FileName(file).exists())
541                                 throw ExceptionMessage(ErrorException, _("Failed to write file"),
542                                         bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
543                                                 it->displayName()));
544                         filenames.push_back(make_pair(file, it->inzipName()));
545                         LYXERR(Debug::FILES, "Writing file " << it->outputFilename()
546                                 << " as " << it->inzipName() << endl);
547                 }
548         }
549         // write a zip file with all these files. Write to a temp file first, to
550         // avoid messing up the original file in case something goes terribly wrong.
551         DocFileName zipfile(addName(buffer.temppath(),
552                 onlyFilename(changeExtension(
553                         filename.toFilesystemEncoding(), ".zip"))));
554
555         ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
556         // copy file back
557         if (!zipfile.copyTo(filename)) {
558                 Alert::error(_("Save failure"),
559                                  bformat(_("Cannot create file %1$s.\n"
560                                            "Please check whether the directory exists and is writeable."),
561                                          from_utf8(filename.absFilename())));
562                 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
563         }
564         return true;
565 }
566
567 } // namespace lyx