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