]> git.lyx.org Git - lyx.git/blob - src/EmbeddedFiles.cpp
Add calcInzipName.
[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 <boost/assert.hpp>
38
39 #include <sstream>
40 #include <fstream>
41 #include <utility>
42
43 using namespace std;
44 using namespace lyx::support;
45
46 namespace lyx {
47
48 namespace Alert = frontend::Alert;
49
50 EmbeddedFile::EmbeddedFile(string const & file, std::string const & buffer_path)
51         : DocFileName("", false), embedded_(false), inset_list_()
52 {
53         set(file, buffer_path);
54 }
55
56
57 void EmbeddedFile::set(std::string const & filename, std::string const & buffer_path)
58 {
59         DocFileName::set(filename, buffer_path);
60         if (filename.empty())
61                 return;
62
63         if (!buffer_path.empty())
64                 inzip_name_ = calcInzipName(buffer_path);
65 }
66
67
68 void EmbeddedFile::setInzipName(std::string const & name)
69 {
70         if (name.empty() || name == inzip_name_)
71                 return;
72
73         // an enabled EmbeededFile should have this problem handled
74         BOOST_ASSERT(!enabled());
75         // file will be synced when it is enabled
76         inzip_name_ = name;
77 }
78
79
80 string EmbeddedFile::embeddedFile() const
81 {
82         BOOST_ASSERT(enabled());
83         return temp_path_ + inzip_name_;
84 }
85
86
87 FileName EmbeddedFile::availableFile() const
88 {
89         if (enabled() && embedded())
90                 return FileName(embeddedFile());
91         else
92                 return *this;
93 }
94
95
96 string EmbeddedFile::latexFilename(std::string const & buffer_path) const
97 {
98         return (enabled() && embedded()) ? inzip_name_ : relFilename(buffer_path);
99 }
100
101
102 void EmbeddedFile::addInset(Inset const * inset)
103 {
104         if (inset != NULL)
105                 inset_list_.push_back(inset);
106 }
107
108
109 void EmbeddedFile::setEmbed(bool embed)
110 {
111         embedded_ = embed;
112 }
113
114
115 void EmbeddedFile::enable(bool flag, Buffer const * buf, bool updateFile)
116 {
117         // This function will be called when
118         // 1. through EmbeddedFiles::enable() when a file is read. Files
119         //    should be in place so no updateFromExternalFile or extract()
120         //    should be called. (updateFile should be false in this case).
121         // 2. through menu item enable/disable. updateFile should be true.
122         // 3. A single embedded file is added or modified. updateFile
123         //    can be true or false.
124         LYXERR(Debug::FILES, (flag ? "Enable" : "Disable") 
125                 << " " << absFilename() 
126                 << (updateFile ? " (update file)." : " (no update)."));
127
128         if (flag) {
129                 temp_path_ = buf->temppath();
130                 if (!suffixIs(temp_path_, '/'))
131                         temp_path_ += '/';
132                 if (embedded() && updateFile)
133                         updateFromExternalFile();
134         } else {
135                 // when a new embeddeed file is created, it is not enabled, and 
136                 // there is no need to extract.
137                 if (enabled() && embedded() && updateFile)
138                         extract();
139                 temp_path_ = "";
140         }
141 }
142
143
144 bool EmbeddedFile::extract() const
145 {
146         BOOST_ASSERT(enabled());
147
148         string ext_file = absFilename();
149         string emb_file = embeddedFile();
150
151         FileName emb(emb_file);
152         FileName ext(ext_file);
153
154         if (!emb.exists()) {
155                 if (ext.exists())
156                         return true;
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 EmbeddedFile EmbeddedFile::copyTo(Buffer const * buf)
258 {
259         EmbeddedFile file = EmbeddedFile(absFilename(), buf->filePath());
260         file.setEmbed(embedded());
261         file.enable(buf->embedded(), buf, false);
262         
263         // use external file.
264         if (!embedded())
265                 return file;
266
267         LYXERR(Debug::FILES, "Copy " << availableFile()
268                 << " to " << file.availableFile());
269
270         FileName from_file = availableFile();
271         FileName to_file = file.availableFile();
272
273         if (!from_file.exists()) {
274                 // no from file
275                 throw ExceptionMessage(ErrorException,
276                         _("Failed to copy embedded file"),
277                         bformat(_("Failed to embed file %1$s.\n"
278                            "Please check whether the source file is available"),
279                                 from_utf8(absFilename())));
280                 file.setEmbed(false);
281                 return file;
282         }
283
284         // if destination file already exists ...
285         if (to_file.exists()) {
286                 // no need to copy if the files are the same
287                 if (checksum() == to_file.checksum())
288                         return file;
289                 // other wise, ask if overwrite
290                 int const ret = Alert::prompt(
291                         _("Update embedded file?"),
292                         bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
293                                 from_utf8(to_file.absFilename())), 1, 1, _("&Overwrite"), _("&Cancel"));
294                 if (ret != 0)
295                         // if the user does not want to overwrite, we still consider it
296                         // a successful operation.
297                         return file;
298         }
299         // copy file
300         // need to make directory?
301         FileName path = to_file.onlyPath();
302         if (!path.isDirectory())
303                 path.createPath();
304         if (from_file.copyTo(to_file))
305                 return file;
306         throw ExceptionMessage(ErrorException,
307                 _("Copy file failure"),
308                 bformat(_("Cannot copy file %1$s to %2$s.\n"
309                            "Please check whether the directory exists and is writeable."),
310                                 from_utf8(from_file.absFilename()), from_utf8(to_file.absFilename())));
311         return file;
312 }
313
314
315 void EmbeddedFile::updateInsets() const
316 {
317         vector<Inset const *>::const_iterator it = inset_list_.begin();
318         vector<Inset const *>::const_iterator it_end = inset_list_.end();
319         for (; it != it_end; ++it)
320                 const_cast<Inset *>(*it)->updateEmbeddedFile(*this);
321 }
322
323
324 bool EmbeddedFile::isReadableFile() const
325 {
326         return availableFile().isReadableFile();
327 }
328
329
330 unsigned long EmbeddedFile::checksum() const
331 {
332         return availableFile().checksum();
333 }
334
335 /**
336 Under the lyx temp directory, content.lyx and its embedded files are usually
337 saved as
338
339 $temp/$embDirName/file.lyx
340 $temp/$embDirName/figure1.png     for ./figure1.png)
341 $temp/$embDirName/sub/figure2.png for ./sub/figure2.png)
342
343 This works fine for embedded files that are in the current or deeper directory
344 of the document directory, but not for files such as ../figures/figure.png.
345 A unique name $upDirName is chosen to represent .. in such filenames so that
346 'up' directories can be stored 'down' the directory tree:
347
348 $temp/$embDirName/$upDirName/figures/figure.png     for ../figures/figure.png
349 $temp/$embDirName/$upDirName/$upDirName/figure.png  for ../../figure.png
350
351 This name has to be fixed because it is used in lyx bundled .zip file.
352
353 Using a similar trick, we use $absDirName for absolute path so that
354 an absolute filename can be saved as
355
356 $temp/$embDirName/$absDirName/a/absolute/path for /a/absolute/path
357
358 FIXME:
359 embDirName is set to . so that embedded layout and class files can be
360 used directly. However, putting all embedded files directly under
361 the temp directory may lead to file conflicts. For example, if a user
362 embeds a file blah.log in blah.lyx, it will be replaced when
363 'latex blah.tex' is called.
364 */
365 const std::string embDirName = ".";
366 const std::string upDirName = "LyX.Embed.Dir.Up";
367 const std::string absDirName = "LyX.Embed.Dir.Abs";
368 const std::string driveName = "LyX.Embed.Drive";
369 const std::string spaceName = "LyX.Embed.Space";
370
371 // static
372 std::string EmbeddedFile::calcInzipName(
373         std::string const & file, std::string const & buffer_path)
374 {
375         string inzipName = to_utf8(makeRelPath(from_utf8(file),
376                         from_utf8(buffer_path)));
377
378         if (FileName(inzipName).isAbsolute())
379                 inzipName = absDirName + '/' + inzipName;
380
381         // replace .. by upDirName
382         if (prefixIs(inzipName, "."))
383                 inzipName = subst(inzipName, "..", upDirName);
384         // replace special characters by their value
385         inzipName = subst(inzipName, ":", driveName);
386         inzipName = subst(inzipName, " ", spaceName);
387
388         // to avoid name conflict between $docu_path/file and $temp_path/file
389         // embedded files are in a subdirectory of $temp_path.
390         inzipName = embDirName + '/' + inzipName;
391         return inzipName;
392 }
393
394
395 std::string EmbeddedFile::calcInzipName(std::string const & buffer_path)
396 {
397         return calcInzipName(absFilename(), buffer_path);
398 }
399  
400
401 void EmbeddedFile::syncInzipFile(std::string const & buffer_path)
402 {
403         BOOST_ASSERT(enabled());
404         string old_emb_file = temp_path_ + '/' + inzip_name_;
405         FileName old_emb(old_emb_file);
406
407         if (!old_emb.exists())
408                 throw ExceptionMessage(ErrorException, _("Failed to open file"),
409                         bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
410                                 old_emb.displayName()));
411
412         string new_inzip_name = calcInzipName(buffer_path);
413         if (new_inzip_name == inzip_name_)
414                 return;
415
416         LYXERR(Debug::FILES, " OLD ZIP " << old_emb_file <<
417                 " NEW ZIP " << calcInzipName(buffer_path));
418
419         string new_emb_file = temp_path_ + '/' + new_inzip_name;
420         FileName new_emb(new_emb_file);
421         
422         // need to make directory?
423         FileName path = new_emb.onlyPath();
424         if (!path.createPath()) {
425                 throw ExceptionMessage(ErrorException, _("Sync file failure"),
426                         bformat(_("Cannot create file path '%1$s'.\n"
427                         "Please check whether the path is writeable."),
428                         from_utf8(path.absFilename())));
429                 return;
430         }
431
432         if (old_emb.copyTo(new_emb)) {
433                 LYXERR(Debug::FILES, "Sync inzip file from " << inzip_name_ 
434                         << " to " << new_inzip_name);
435                 inzip_name_ = new_inzip_name;
436                 return;
437         }
438         throw ExceptionMessage(ErrorException, _("Sync file failure"),
439                  bformat(_("Cannot copy file %1$s to %2$s.\n"
440                                  "Please check whether the directory exists and is writeable."),
441                                 from_utf8(old_emb_file), from_utf8(new_emb_file)));
442 }
443
444
445 bool operator==(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
446 {
447         return lhs.absFilename() == rhs.absFilename()
448                 && lhs.saveAbsPath() == rhs.saveAbsPath()
449                 && lhs.embedded() == rhs.embedded();
450 }
451
452
453 bool operator!=(EmbeddedFile const & lhs, EmbeddedFile const & rhs)
454 {
455         return !(lhs == rhs);
456 }
457
458
459 void EmbeddedFileList::enable(bool flag, Buffer & buffer, bool updateFile)
460 {
461         // update embedded file list
462         update(buffer);
463         
464         int count_embedded = 0;
465         int count_external = 0;
466         iterator it = begin();
467         iterator it_end = end();
468         // an exception may be thrown
469         for (; it != it_end; ++it) {
470                 it->enable(flag, &buffer, updateFile);
471                 if (it->embedded())
472                         ++count_embedded;
473                 else
474                         ++count_external;
475         }
476         // if operation is successful (no exception is thrown)
477         buffer.params().embedded = flag;
478
479         // if the operation is successful, update insets
480         for (it = begin(); it != it_end; ++it)
481                 it->updateInsets();
482
483         if (!updateFile || (count_external == 0 && count_embedded == 0))
484                 return;
485
486         // show result
487         if (flag) {
488                 docstring const msg = bformat(_("%1$d external files are ignored.\n"
489                         "%2$d embeddable files are embedded.\n"), count_external, count_embedded);
490                 Alert::information(_("Packing all files"), msg);
491         } else {
492                 docstring const msg = bformat(_("%1$d external files are ignored.\n"
493                         "%2$d embedded files are extracted.\n"), count_external, count_embedded);
494                 Alert::information(_("Unpacking all files"), msg);
495         }
496 }
497
498
499 void EmbeddedFileList::registerFile(EmbeddedFile const & file,
500         Inset const * inset, Buffer const & buffer)
501 {
502         BOOST_ASSERT(!buffer.embedded() || file.enabled());
503
504         string newfile = file.absFilename();
505         iterator efp = findFile(newfile);
506         if (efp != end()) {
507                 if (efp->embedded() != file.embedded()) {
508                         Alert::error(_("Wrong embedding status."),
509                                 bformat(_("File %1$s is included in more than one insets, "
510                                         "but with different embedding status. Assuming embedding status."),
511                                         from_utf8(efp->outputFilename())));
512                         efp->setEmbed(true);
513                         // update the inset with this embedding status.
514                         const_cast<Inset*>(inset)->updateEmbeddedFile(*efp);
515                 }
516                 efp->addInset(inset);
517                 return;
518         }
519         file.clearInsets();
520         push_back(file);
521         back().addInset(inset);
522 }
523
524
525 EmbeddedFileList::const_iterator 
526         EmbeddedFileList::findFile(std::string const & filename) const
527 {
528         // try to find this file from the list
529         std::vector<EmbeddedFile>::const_iterator it = begin();
530         std::vector<EmbeddedFile>::const_iterator it_end = end();
531         for (; it != it_end; ++it)
532                 if (it->absFilename() == filename)
533                         return it;
534         return end();
535 }
536
537
538 EmbeddedFileList::iterator 
539         EmbeddedFileList::findFile(std::string const & filename)
540 {
541         // try to find this file from the list
542         std::vector<EmbeddedFile>::iterator it = begin();
543         std::vector<EmbeddedFile>::iterator it_end = end();
544         for (; it != it_end; ++it)
545                 if (it->absFilename() == filename)
546                         return it;
547         return end();
548 }
549
550
551 void EmbeddedFileList::validate(Buffer const & buffer)
552 {
553         clear();
554         
555         for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
556                 it->registerEmbeddedFiles(*this);
557
558         iterator it = begin();
559         iterator it_end = end();
560         for (; it != it_end; ++it) {
561                 if (buffer.embedded() && it->embedded())
562                         // An exception will be raised if inzip file does not exist
563                         it->syncInzipFile(buffer.filePath());
564                 else
565                         // inzipName may be OS dependent
566                         it->setInzipName(it->calcInzipName(buffer.filePath()));
567         }
568         for (it = begin(); it != it_end; ++it)
569                 it->updateInsets();
570         
571         if (!buffer.embedded())
572                 return;
573
574         // check if extra embedded files exist
575         vector<string> extra = buffer.params().extraEmbeddedFiles();
576         vector<string>::iterator e_it = extra.begin();
577         vector<string>::iterator e_end = extra.end();
578         for (; e_it != e_end; ++e_it) {
579                 EmbeddedFile file = EmbeddedFile(*e_it, buffer.filePath());
580                 // do not update from external file
581                 file.enable(true, &buffer, false);
582                 // but we do need to check file existence.
583                 if (!FileName(file.embeddedFile()).exists())
584                         throw ExceptionMessage(ErrorException, _("Failed to open file"),
585                                 bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
586                                         file.displayName()));
587         }
588 }
589
590
591 void EmbeddedFileList::update(Buffer const & buffer)
592 {
593         clear();
594
595         for (InsetIterator it = inset_iterator_begin(buffer.inset()); it; ++it)
596                 it->registerEmbeddedFiles(*this);
597
598         // add extra embedded files
599         vector<string> extra = buffer.params().extraEmbeddedFiles();
600         vector<string>::iterator it = extra.begin();
601         vector<string>::iterator it_end = extra.end();
602         for (; it != it_end; ++it) {
603                 EmbeddedFile file = EmbeddedFile(*it, buffer.filePath());
604                 file.setEmbed(true);
605                 file.enable(buffer.embedded(), &buffer, false);
606                 insert(end(), file);
607         }
608 }
609
610
611 bool EmbeddedFileList::writeFile(DocFileName const & filename, Buffer const & buffer)
612 {
613         // file in the temporary path has the content
614         string const content = FileName(addName(buffer.temppath(),
615                 "content.lyx")).toFilesystemEncoding();
616
617         vector<pair<string, string> > filenames;
618         // add content.lyx to filenames
619         filenames.push_back(make_pair(content, "content.lyx"));
620         // prepare list of embedded file
621         update(buffer);
622         //
623         iterator it = begin();
624         iterator it_end = end();
625         for (; it != it_end; ++it) {
626                 if (it->embedded()) {
627                         string file = it->embeddedFile();
628                         if (!FileName(file).exists())
629                                 throw ExceptionMessage(ErrorException, _("Failed to write file"),
630                                         bformat(_("Embedded file %1$s does not exist. Did you tamper lyx temporary directory?"),
631                                                 it->displayName()));
632                         filenames.push_back(make_pair(file, it->inzipName()));
633                         LYXERR(Debug::FILES, "Writing file " << it->outputFilename()
634                                 << " as " << it->inzipName() << endl);
635                 }
636         }
637         // write a zip file with all these files. Write to a temp file first, to
638         // avoid messing up the original file in case something goes terribly wrong.
639         DocFileName zipfile(addName(buffer.temppath(),
640                 onlyFilename(changeExtension(
641                         filename.toFilesystemEncoding(), ".zip"))));
642
643         ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
644         // copy file back
645         if (!zipfile.copyTo(filename)) {
646                 Alert::error(_("Save failure"),
647                          bformat(_("Cannot create file %1$s.\n"
648                                            "Please check whether the directory exists and is writeable."),
649                                          from_utf8(filename.absFilename())));
650         }
651         return true;
652 }
653
654 } // namespace lyx