]> git.lyx.org Git - lyx.git/blob - src/EmbeddedFiles.cpp
* get rid of lyxlib.h:mkdir() and makedir()
[lyx.git] / src / EmbeddedFiles.cpp
1 // -*- C++ -*-
2 /**
3  * \file EmbeddedFiles.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/lyxlib.h"
34 #include "support/lstrings.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
49 EmbeddedFile::EmbeddedFile(string const & file, string const & inzip_name,
50         bool embed, Inset const * inset)
51         : DocFileName(file, true), inzip_name_(inzip_name), embedded_(embed),
52                 inset_list_()
53 {
54         if (inset != NULL)
55                 inset_list_.push_back(inset);
56 }
57
58
59 string EmbeddedFile::embeddedFile(Buffer const * buf) const
60 {
61         return addName(buf->temppath(), inzip_name_);
62 }
63
64
65 void EmbeddedFile::addInset(Inset const * inset)
66 {
67         inset_list_.push_back(inset);
68 }
69
70
71 Inset const * EmbeddedFile::inset(int idx) const
72 {
73         BOOST_ASSERT(idx < refCount());
74         // some embedded file do not have a valid par iterator
75         return inset_list_[idx];
76 }
77
78
79 void EmbeddedFile::saveBookmark(Buffer const * buf, int idx) const
80 {
81         Inset const * ptr = inset(idx);
82         // This might not be the most efficient method ... 
83         for (InsetIterator it = inset_iterator_begin(buf->inset()); it; ++it)
84                 if (&(*it) == ptr) {
85                         // this is basically BufferView::saveBookmark(0)
86                         LyX::ref().session().bookmarks().save(
87                                 FileName(buf->absFileName()),
88                                 it.bottom().pit(),
89                                 it.bottom().pos(),
90                                 it.paragraph().id(),
91                                 it.pos(),
92                                 0
93                         );
94                 }
95         // this inset can not be located. There is something wrong that needs
96         // to be fixed.
97         BOOST_ASSERT(true);
98 }
99
100
101 string EmbeddedFile::availableFile(Buffer const * buf) const
102 {
103         return embedded() ? embeddedFile(buf) : absFilename();
104 }
105
106
107 bool EmbeddedFile::extract(Buffer const * buf) const
108 {
109         string ext_file = absFilename();
110         string emb_file = embeddedFile(buf);
111
112         FileName emb(emb_file);
113         FileName ext(ext_file);
114
115         if (!emb.exists())
116                 return false;
117
118         // if external file already exists ...
119         if (ext.exists()) {
120                 // no need to copy if the files are the same
121                 if (checksum() == FileName(emb_file).checksum())
122                         return true;
123                 // otherwise, ask if overwrite
124                 int ret = Alert::prompt(
125                         _("Overwrite external file?"),
126                         bformat(_("External file %1$s already exists, do you want to overwrite it"),
127                                 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
128                 if (ret != 0)
129                         // if the user does not want to overwrite, we still consider it
130                         // a successful operation.
131                         return true;
132         }
133         // copy file
134
135         // need to make directory?
136         FileName path = ext.onlyPath();
137         if (!path.createPath()) {
138                 Alert::error(_("Copy file failure"),
139                         bformat(_("Cannot create file path '%1$s'.\n"
140                         "Please check whether the path is writeable."),
141                         from_utf8(path.absFilename())));
142                 return false;
143         }
144
145         if (emb.copyTo(ext, true))
146                 return true;
147
148         Alert::error(_("Copy file failure"),
149                  bformat(_("Cannot copy file %1$s to %2$s.\n"
150                                  "Please check whether the directory exists and is writeable."),
151                                 from_utf8(emb_file), from_utf8(ext_file)));
152         return false;
153 }
154
155
156 bool EmbeddedFile::updateFromExternalFile(Buffer const * buf) const
157 {
158         string ext_file = absFilename();
159         string emb_file = embeddedFile(buf);
160
161         FileName emb(emb_file);
162         FileName ext(ext_file);
163
164         if (!ext.exists())
165                 return false;
166         
167         // if embedded file already exists ...
168         if (emb.exists()) {
169                 // no need to copy if the files are the same
170                 if (checksum() == FileName(emb_file).checksum())
171                         return true;
172                 // other wise, ask if overwrite
173                 int const ret = Alert::prompt(
174                         _("Update embedded file?"),
175                         bformat(_("Embedded file %1$s already exists, do you want to overwrite it"),
176                                 from_utf8(ext_file)), 1, 1, _("&Overwrite"), _("&Cancel"));
177                 if (ret != 0)
178                         // if the user does not want to overwrite, we still consider it
179                         // a successful operation.
180                         return true;
181         }
182         // copy file
183         // need to make directory?
184         FileName path = emb.onlyPath();
185         if (!path.isDirectory())
186                 path.createPath();
187         if (ext.copyTo(emb, true))
188                 return true;
189         Alert::error(_("Copy file failure"),
190                  bformat(_("Cannot copy file %1$s to %2$s.\n"
191                            "Please check whether the directory exists and is writeable."),
192                                 from_utf8(ext_file), from_utf8(emb_file)));
193         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
194         return false;
195 }
196
197
198 void EmbeddedFile::updateInsets(Buffer const * buf) const
199 {
200         vector<Inset const *>::const_iterator it = inset_list_.begin();
201         vector<Inset const *>::const_iterator it_end = inset_list_.end();
202         for (; it != it_end; ++it)
203                 const_cast<Inset *>(*it)->updateEmbeddedFile(*buf, *this);
204 }
205
206
207 bool EmbeddedFiles::enabled() const
208 {
209         return buffer_->params().embedded;
210 }
211
212
213 void EmbeddedFiles::enable(bool flag)
214 {
215         if (enabled() != flag) {
216                 // if enable, copy all files to temppath()
217                 // if disable, extract all files
218                 if ((flag && !updateFromExternalFile()) || (!flag && !extract()))
219                         return;
220                 // if operation is successful
221                 buffer_->markDirty();
222                 buffer_->params().embedded = flag;
223                 if (flag)
224                         updateInsets();
225         }
226 }
227
228
229 EmbeddedFile & EmbeddedFiles::registerFile(string const & filename,
230         bool embed, Inset const * inset, string const & inzipName)
231 {
232         // filename can be relative or absolute, translate to absolute filename
233         string abs_filename = makeAbsPath(filename, buffer_->filePath()).absFilename();
234         // try to find this file from the list
235         EmbeddedFileList::iterator it = file_list_.begin();
236         EmbeddedFileList::iterator it_end = file_list_.end();
237         for (; it != it_end; ++it)
238                 if (it->absFilename() == abs_filename || it->embeddedFile(buffer_) == abs_filename)
239                         break;
240         // find this filename, keep the original embedding status
241         if (it != file_list_.end()) {
242                 it->addInset(inset);
243                 return *it;
244         }
245         //
246         file_list_.push_back(EmbeddedFile(abs_filename, 
247                 getInzipName(abs_filename, inzipName), embed, inset));
248         return file_list_.back();
249 }
250
251
252 void EmbeddedFiles::update()
253 {
254         file_list_.clear();
255
256         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it)
257                 it->registerEmbeddedFiles(*buffer_, *this);
258 }
259
260
261 bool EmbeddedFiles::writeFile(DocFileName const & filename)
262 {
263         // file in the temporary path has the content
264         string const content = FileName(addName(buffer_->temppath(),
265                 "content.lyx")).toFilesystemEncoding();
266
267         vector<pair<string, string> > filenames;
268         // add content.lyx to filenames
269         filenames.push_back(make_pair(content, "content.lyx"));
270         // prepare list of embedded file
271         EmbeddedFileList::iterator it = file_list_.begin();
272         EmbeddedFileList::iterator it_end = file_list_.end();
273         for (; it != it_end; ++it) {
274                 if (it->embedded()) {
275                         string file = it->availableFile(buffer_);
276                         if (file.empty())
277                                 lyxerr << "File " << it->absFilename() << " does not exist. Skip embedding it. " << endl;
278                         else
279                                 filenames.push_back(make_pair(file, it->inzipName()));
280                 }
281         }
282         // write a zip file with all these files. Write to a temp file first, to
283         // avoid messing up the original file in case something goes terribly wrong.
284         DocFileName zipfile(addName(buffer_->temppath(),
285                 onlyFilename(changeExtension(
286                         filename.toFilesystemEncoding(), ".zip"))));
287
288         ::zipFiles(zipfile.toFilesystemEncoding(), filenames);
289         // copy file back
290         if (!zipfile.copyTo(filename, true)) {
291                 Alert::error(_("Save failure"),
292                                  bformat(_("Cannot create file %1$s.\n"
293                                            "Please check whether the directory exists and is writeable."),
294                                          from_utf8(filename.absFilename())));
295                 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
296         }
297         return true;
298 }
299
300
301 EmbeddedFiles::EmbeddedFileList::const_iterator
302 EmbeddedFiles::find(string filename) const
303 {
304         EmbeddedFileList::const_iterator it = file_list_.begin();
305         EmbeddedFileList::const_iterator it_end = file_list_.end();
306         for (; it != it_end; ++it)
307                 if (it->absFilename() == filename || it->embeddedFile(buffer_) == filename)     
308                         return it;
309         return file_list_.end();
310 }
311
312
313 bool EmbeddedFiles::extract() const
314 {
315         EmbeddedFileList::const_iterator it = file_list_.begin();
316         EmbeddedFileList::const_iterator it_end = file_list_.end();
317         for (; it != it_end; ++it)
318                 if (it->embedded())
319                         if(!it->extract(buffer_))
320                                 return false;
321         return true;
322 }
323
324
325 bool EmbeddedFiles::updateFromExternalFile() const
326 {
327         EmbeddedFileList::const_iterator it = file_list_.begin();
328         EmbeddedFileList::const_iterator it_end = file_list_.end();
329         for (; it != it_end; ++it)
330                 if (it->embedded())
331                         if (!it->updateFromExternalFile(buffer_))
332                                 return false;
333         return true;
334 }
335
336
337 string const EmbeddedFiles::getInzipName(string const & abs_filename, string const & name)
338 {
339         // register a new one, using relative file path as inzip_name
340         string inzip_name = name;
341         if (name.empty())
342                 inzip_name = to_utf8(makeRelPath(from_utf8(abs_filename),
343                         from_utf8(buffer_->filePath())));
344         // if inzip_name is an absolute path, use filename only to avoid
345         // leaking of filesystem information in inzip_name
346         // The second case covers cases '../path/file' and '.'
347         if (absolutePath(inzip_name) || prefixIs(inzip_name, "."))
348                 inzip_name = onlyFilename(abs_filename);
349         // if this name has been used...
350         // use _1_name, _2_name etc
351         string tmp = inzip_name;
352         EmbeddedFileList::iterator it;
353         EmbeddedFileList::iterator it_end = file_list_.end();
354         bool unique_name = false;
355         size_t i = 0;
356         while (!unique_name) {
357                 unique_name = true;
358                 if (i > 0)
359                         inzip_name = convert<string>(i) + "_" + tmp;
360                 it = file_list_.begin();
361                 for (; it != it_end; ++it)
362                         if (it->inzipName() == inzip_name) {
363                                 unique_name = false;
364                                 ++i;
365                                 break;
366                         }
367         }
368         return inzip_name;
369 }
370
371
372 void EmbeddedFiles::updateInsets() const
373 {
374         EmbeddedFiles::EmbeddedFileList::const_iterator it = begin();
375         EmbeddedFiles::EmbeddedFileList::const_iterator it_end = end();
376         for (; it != it_end; ++it)
377                 if (it->refCount() > 0)
378                         it->updateInsets(buffer_);
379 }
380
381
382 }