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