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