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