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