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