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