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