]> git.lyx.org Git - features.git/blob - src/ConverterCache.cpp
Fix copy&paste error.
[features.git] / src / ConverterCache.cpp
1 /**
2  * \file ConverterCache.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Baruch Even
7  * \author Angus Leeming
8  * \author Georg Baum
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "ConverterCache.h"
16
17 #include "Format.h"
18 #include "Lexer.h"
19 #include "LyXRC.h"
20 #include "Mover.h"
21
22 #include "support/convert.h"
23 #include "support/debug.h"
24 #include "support/filetools.h"
25 #include "support/lyxlib.h"
26 #include "support/lyxtime.h"
27 #include "support/Package.h"
28
29 #include <boost/assert.hpp>
30 #include <boost/crc.hpp>
31
32 #include <algorithm>
33 #include <fstream>
34 #include <iomanip>
35 #include <map>
36 #include <sstream>
37
38 using namespace std;
39 using namespace lyx::support;
40
41 namespace lyx {
42
43 namespace {
44
45 unsigned long do_crc(string const & s)
46 {
47         boost::crc_32_type crc;
48         crc = for_each(s.begin(), s.end(), crc);
49         return crc.checksum();
50 }
51
52
53 static FileName cache_dir;
54
55
56 class CacheItem {
57 public:
58         CacheItem() {}
59         CacheItem(FileName const & orig_from, string const & to_format,
60                   time_t t, unsigned long c)
61                 : timestamp(t), checksum(c)
62         {
63                 ostringstream os;
64                 os << setw(10) << setfill('0') << do_crc(orig_from.absFilename())
65                    << '-' << to_format;
66                 cache_name = FileName(addName(cache_dir.absFilename(), os.str()));
67                 LYXERR(Debug::FILES, "Add file cache item " << orig_from
68                                      << ' ' << to_format << ' ' << cache_name
69                                      << ' ' << long(timestamp) << ' ' << checksum << '.');
70         }
71         ~CacheItem() {}
72         FileName cache_name;
73         time_t timestamp;
74         unsigned long checksum;
75 };
76
77 }
78
79
80 /** The cache contains one item per orig file and target format, so use a
81  *  nested map to find the cache item quickly by filename and format.
82  */
83 typedef map<string, CacheItem> FormatCacheType;
84 class FormatCache {
85 public:
86         /// Format of the source file
87         string from_format;
88         /// Cache target format -> item to quickly find the item by format
89         FormatCacheType cache;
90 };
91 typedef map<FileName, FormatCache> CacheType;
92
93
94 class ConverterCache::Impl {
95 public:
96         ///
97         void readIndex();
98         ///
99         void writeIndex();
100         ///
101         CacheItem * find(FileName const & from, string const & format);
102         CacheType cache;
103 };
104
105
106 void ConverterCache::Impl::readIndex()
107 {
108         time_t const now = current_time();
109         FileName const index(addName(cache_dir.absFilename(), "index"));
110         ifstream is(index.toFilesystemEncoding().c_str());
111         Lexer lex(0, 0);
112         lex.setStream(is);
113         while (lex.isOK()) {
114                 if (!lex.next(true))
115                         break;
116                 string const orig_from = lex.getString();
117                 if (!lex.next())
118                         break;
119                 string const to_format = lex.getString();
120                 if (!lex.next())
121                         break;
122                 time_t const timestamp =
123                         convert<unsigned long>(lex.getString());
124                 if (!lex.next())
125                         break;
126                 unsigned long const checksum =
127                         convert<unsigned long>(lex.getString());
128                 FileName const orig_from_name(orig_from);
129                 CacheItem item(orig_from_name, to_format, timestamp, checksum);
130
131                 // Don't cache files that do not exist anymore
132                 if (!orig_from_name.exists()) {
133                         LYXERR(Debug::FILES, "Not caching file `"
134                                 << orig_from << "' (does not exist anymore).");
135                         item.cache_name.removeFile();
136                         continue;
137                 }
138
139                 // Don't add items that are not in the cache anymore
140                 // This can happen if two instances of LyX are running
141                 // at the same time and update the index file independantly.
142                 if (!item.cache_name.exists()) {
143                         LYXERR(Debug::FILES, "Not caching file `" << orig_from
144                                 << "' (cached copy does not exist anymore).");
145                         continue;
146                 }
147
148                 // Delete the cached file if it is too old
149                 if (difftime(now, item.cache_name.lastModified())
150                                 > lyxrc.converter_cache_maxage) {
151                         LYXERR(Debug::FILES, "Not caching file `"
152                                 << orig_from << "' (too old).");
153                         item.cache_name.removeFile();
154                         continue;
155                 }
156
157                 FormatCache & format_cache = cache[orig_from_name];
158                 if (format_cache.from_format.empty())
159                         format_cache.from_format =
160                                 formats.getFormatFromFile(orig_from_name);
161                 format_cache.cache[to_format] = item;
162         }
163         is.close();
164 }
165
166
167 void ConverterCache::Impl::writeIndex()
168 {
169         FileName const index(addName(cache_dir.absFilename(), "index"));
170         ofstream os(index.toFilesystemEncoding().c_str());
171         os.close();
172         if (!chmod(index, 0600))
173                 return;
174         os.open(index.toFilesystemEncoding().c_str());
175         CacheType::iterator it1 = cache.begin();
176         CacheType::iterator const end1 = cache.end();
177         for (; it1 != end1; ++it1) {
178                 FormatCacheType const & format_cache = it1->second.cache;
179                 FormatCacheType::const_iterator it2 = format_cache.begin();
180                 FormatCacheType::const_iterator const end2 = format_cache.end();
181                 for (; it2 != end2; ++it2)
182                         os << Lexer::quoteString(it1->first.absFilename())
183                            << ' ' << it2->first << ' '
184                            << it2->second.timestamp << ' '
185                            << it2->second.checksum << '\n';
186         }
187         os.close();
188 }
189
190
191 CacheItem * ConverterCache::Impl::find(FileName const & from,
192                 string const & format)
193 {
194         if (!lyxrc.use_converter_cache)
195                 return 0;
196         CacheType::iterator const it1 = cache.find(from);
197         if (it1 == cache.end())
198                 return 0;
199         FormatCacheType & format_cache = it1->second.cache;
200         FormatCacheType::iterator const it2 = format_cache.find(format);
201         if (it2 == format_cache.end())
202                 return 0;
203         return &(it2->second);
204 }
205
206
207 /////////////////////////////////////////////////////////////////////
208 //
209 // ConverterCache
210 //
211 /////////////////////////////////////////////////////////////////////
212
213 ConverterCache::ConverterCache()
214         : pimpl_(new Impl)
215 {}
216
217
218 ConverterCache::~ConverterCache()
219 {
220         if (!lyxrc.use_converter_cache)
221                 return;
222         pimpl_->writeIndex();
223         delete pimpl_;
224 }
225
226
227 ConverterCache & ConverterCache::get()
228 {
229         // Now return the cache
230         static ConverterCache singleton;
231         return singleton;
232 }
233
234
235 void ConverterCache::init()
236 {
237         if (!lyxrc.use_converter_cache)
238                 return;
239         // We do this here and not in the constructor because package() gets
240         // initialized after all static variables.
241         cache_dir = FileName(addName(package().user_support().absFilename(), "cache"));
242         if (!cache_dir.exists())
243                 if (support::mkdir(cache_dir, 0700) != 0) {
244                         lyxerr << "Could not create cache directory `"
245                                << cache_dir << "'." << endl;
246                         exit(EXIT_FAILURE);
247                 }
248         get().pimpl_->readIndex();
249 }
250
251
252 static bool changeMode(FileName const & fname, unsigned long int mode)
253 {
254         if (mode == (unsigned long int)-1)
255                 return true;
256
257         ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::binary | ios::out | ios::trunc);
258         if (!ofs)
259                 return false;
260         ofs.close();
261         if (!chmod(fname, mode))
262                 return false;
263         return true;
264 }
265
266
267 void ConverterCache::add(FileName const & orig_from, string const & to_format,
268                 FileName const & converted_file) const
269 {
270         if (!lyxrc.use_converter_cache || orig_from.empty() ||
271             converted_file.empty())
272                 return;
273         LYXERR(Debug::FILES, ' ' << orig_from
274                              << ' ' << to_format << ' ' << converted_file);
275
276         // FIXME: Should not hardcode this (see bug 3819 for details)
277         if (to_format == "pstex") {
278                 FileName const converted_eps(changeExtension(converted_file.absFilename(), "eps"));
279                 add(orig_from, "eps", converted_eps);
280         } else if (to_format == "pdftex") {
281                 FileName const converted_pdf(changeExtension(converted_file.absFilename(), "pdf"));
282                 add(orig_from, "pdf", converted_pdf);
283         }
284
285         // Is the file in the cache already?
286         CacheItem * item = pimpl_->find(orig_from, to_format);
287
288         time_t const timestamp = orig_from.lastModified();
289         Mover const & mover = getMover(to_format);
290         if (item) {
291                 LYXERR(Debug::FILES, "ConverterCache::add(" << orig_from << "):\n"
292                                         "The file is already in the cache.");
293                 // First test for timestamp
294                 if (timestamp == item->timestamp) {
295                         LYXERR(Debug::FILES, "Same timestamp.");
296                         return;
297                 }
298                 // Maybe the contents is still the same?
299                 item->timestamp = timestamp;
300                 unsigned long const checksum = orig_from.checksum();
301                 if (checksum == item->checksum) {
302                         LYXERR(Debug::FILES, "Same checksum.");
303                         return;
304                 }
305                 item->checksum = checksum;
306                 if (!mover.copy(converted_file, item->cache_name,
307                               onlyFilename(item->cache_name.absFilename()))) {
308                         LYXERR(Debug::FILES, "Could not copy file " << orig_from << " to "
309                                 << item->cache_name);
310                 } else if (!changeMode(item->cache_name, 0600)) {
311                         LYXERR(Debug::FILES, "Could not change file mode"
312                                 << item->cache_name);
313                 }
314         } else {
315                 CacheItem new_item(orig_from, to_format, timestamp,
316                                 orig_from.checksum());
317                 if (mover.copy(converted_file, new_item.cache_name,
318                               onlyFilename(new_item.cache_name.absFilename()))) {
319                         if (!changeMode(new_item.cache_name, 0600)) {
320                                 LYXERR(Debug::FILES, "Could not change file mode"
321                                         << item->cache_name);
322                         }
323                         FormatCache & format_cache = pimpl_->cache[orig_from];
324                         if (format_cache.from_format.empty())
325                                 format_cache.from_format =
326                                         formats.getFormatFromFile(orig_from);
327                         format_cache.cache[to_format] = new_item;
328                 } else
329                         LYXERR(Debug::FILES, "ConverterCache::add(" << orig_from << "):\n"
330                                                 "Could not copy file.");
331         }
332 }
333
334
335 void ConverterCache::remove(FileName const & orig_from,
336                 string const & to_format) const
337 {
338         if (!lyxrc.use_converter_cache || orig_from.empty())
339                 return;
340         LYXERR(Debug::FILES, orig_from << ' ' << to_format);
341
342         CacheType::iterator const it1 = pimpl_->cache.find(orig_from);
343         if (it1 == pimpl_->cache.end())
344                 return;
345         FormatCacheType & format_cache = it1->second.cache;
346         FormatCacheType::iterator const it2 = format_cache.find(to_format);
347         if (it2 == format_cache.end())
348                 return;
349
350         format_cache.erase(it2);
351         if (format_cache.empty())
352                 pimpl_->cache.erase(it1);
353 }
354
355
356 void ConverterCache::remove_all(string const & from_format,
357                 string const & to_format) const
358 {
359         if (!lyxrc.use_converter_cache)
360                 return;
361         CacheType::iterator it1 = pimpl_->cache.begin();
362         while (it1 != pimpl_->cache.end()) {
363                 if (it1->second.from_format != from_format) {
364                         ++it1;
365                         continue;
366                 }
367                 FormatCacheType & format_cache = it1->second.cache;
368                 FormatCacheType::iterator it2 = format_cache.begin();
369                 while (it2 != format_cache.end()) {
370                         if (it2->first == to_format) {
371                                 LYXERR(Debug::FILES, "Removing file cache item "
372                                         << it1->first << ' ' << to_format);
373                                 it2->second.cache_name.removeFile();
374                                 format_cache.erase(it2);
375                                 // Have to start over again since items in a
376                                 // map are not ordered
377                                 it2 = format_cache.begin();
378                         } else {
379                                 ++it2;
380                         }
381                 }
382                 if (format_cache.empty()) {
383                         pimpl_->cache.erase(it1);
384                         // Have to start over again since items in a map are
385                         // not ordered
386                         it1 = pimpl_->cache.begin();
387                 } else {
388                         ++it1;
389                 }
390         }
391         pimpl_->writeIndex();
392 }
393
394
395 bool ConverterCache::inCache(FileName const & orig_from,
396                 string const & to_format) const
397 {
398         if (!lyxrc.use_converter_cache || orig_from.empty())
399                 return false;
400         LYXERR(Debug::FILES, orig_from << ' ' << to_format);
401
402         CacheItem * const item = pimpl_->find(orig_from, to_format);
403         if (!item) {
404                 LYXERR(Debug::FILES, "not in cache.");
405                 return false;
406         }
407         time_t const timestamp = orig_from.lastModified();
408         if (item->timestamp == timestamp) {
409                 LYXERR(Debug::FILES, "identical timestamp.");
410                 return true;
411         }
412         if (item->checksum == orig_from.checksum()) {
413                 item->timestamp = timestamp;
414                 LYXERR(Debug::FILES, "identical checksum.");
415                 return true;
416         }
417         LYXERR(Debug::FILES, "in cache, but too old.");
418         return false;
419 }
420
421
422 FileName const & ConverterCache::cacheName(FileName const & orig_from,
423                 string const & to_format) const
424 {
425         LYXERR(Debug::FILES, orig_from << ' ' << to_format);
426
427         CacheItem * const item = pimpl_->find(orig_from, to_format);
428         BOOST_ASSERT(item);
429         return item->cache_name;
430 }
431
432
433 bool ConverterCache::copy(FileName const & orig_from, string const & to_format,
434                 FileName const & dest) const
435 {
436         if (!lyxrc.use_converter_cache || orig_from.empty() || dest.empty())
437                 return false;
438         LYXERR(Debug::FILES, orig_from << ' ' << to_format << ' ' << dest);
439
440         // FIXME: Should not hardcode this (see bug 3819 for details)
441         if (to_format == "pstex") {
442                 FileName const dest_eps(changeExtension(dest.absFilename(), "eps"));
443                 if (!copy(orig_from, "eps", dest_eps))
444                         return false;
445         } else if (to_format == "pdftex") {
446                 FileName const dest_pdf(changeExtension(dest.absFilename(), "pdf"));
447                 if (!copy(orig_from, "pdf", dest_pdf))
448                         return false;
449         }
450
451         CacheItem * const item = pimpl_->find(orig_from, to_format);
452         BOOST_ASSERT(item);
453         Mover const & mover = getMover(to_format);
454         return mover.copy(item->cache_name, dest,
455                           onlyFilename(dest.absFilename()));
456 }
457
458 } // namespace lyx