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