]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsLoader.cpp
Do not compute metrics at each preview when loading file
[lyx.git] / src / graphics / GraphicsLoader.cpp
1 /**
2  * \file GraphicsLoader.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "GraphicsLoader.h"
14
15 #include "GraphicsCacheItem.h"
16 #include "GraphicsImage.h"
17 #include "GraphicsParams.h"
18 #include "GraphicsCache.h"
19
20 #include "support/debug.h"
21 #include "support/lassert.h"
22 #include "support/Timeout.h"
23
24 #include <list>
25 #include <queue>
26 #include <memory>
27 #include <set>
28
29 using namespace std;
30 using namespace lyx::support;
31
32 namespace lyx {
33
34 namespace graphics {
35
36
37 /////////////////////////////////////////////////////////////////////
38 //
39 // LoaderQueue
40 //
41 /////////////////////////////////////////////////////////////////////
42
43 class LoaderQueue {
44 public:
45         /// Use this to request that the item is loaded.
46         void touch(Cache::ItemPtr const & item);
47         /// Query whether the clock is ticking.
48         bool running() const;
49         ///get the and only instance of the class
50         static LoaderQueue & get();
51 private:
52         /// This class is a singleton class... use LoaderQueue::get() instead
53         LoaderQueue();
54         /// The in-progress loading queue (elements are unique here).
55         list<Cache::ItemPtr> cache_queue_;
56         /// Used to make the insertion of new elements faster.
57         set<Cache::ItemPtr> cache_set_;
58         /// Newly touched elements go here. loadNext moves them to cache_queue_
59         queue<Cache::ItemPtr> bucket_;
60         ///
61         Timeout timer;
62         ///
63         bool running_;
64
65         /** This is the 'threaded' method, that does the loading in the
66          *  background.
67          */
68         void loadNext();
69         ///
70         void startLoader();
71         ///
72         void stopLoader();
73 };
74
75
76
77 //static int const s_numimages_ = 5;
78 static int const s_numimages_ = 10;
79 static int const s_millisecs_ = 500;
80
81
82 LoaderQueue & LoaderQueue::get()
83 {
84         static LoaderQueue singleton;
85         return singleton;
86 }
87
88
89 void LoaderQueue::loadNext()
90 {
91         LYXERR(Debug::GRAPHICS, "LoaderQueue: "
92                 << cache_queue_.size() << " items in the queue");
93         int counter = s_numimages_;
94         while (!cache_queue_.empty() && counter--) {
95                 Cache::ItemPtr ptr = cache_queue_.front();
96                 cache_set_.erase(ptr);
97                 cache_queue_.pop_front();
98                 if (ptr->status() == WaitingToLoad)
99                         ptr->startLoading();
100         }
101         if (!cache_queue_.empty())
102                 startLoader();
103         else
104                 stopLoader();
105 }
106
107
108 LoaderQueue::LoaderQueue() : timer(s_millisecs_, Timeout::ONETIME),
109                              running_(false)
110 {
111         // Disconnected when this is destroyed
112         timer.timeout.connect([this](){ loadNext(); });
113 }
114
115
116 void LoaderQueue::startLoader()
117 {
118         LYXERR(Debug::GRAPHICS, "LoaderQueue: waking up");
119         running_ = true;
120         timer.setTimeout(s_millisecs_);
121         timer.start();
122 }
123
124
125 void LoaderQueue::stopLoader()
126 {
127         timer.stop();
128         running_ = false ;
129         LYXERR(Debug::GRAPHICS, "LoaderQueue: I'm going to sleep");
130 }
131
132
133 bool LoaderQueue::running() const
134 {
135         return running_ ;
136 }
137
138
139 void LoaderQueue::touch(Cache::ItemPtr const & item)
140 {
141         if (! cache_set_.insert(item).second) {
142                 list<Cache::ItemPtr>::iterator
143                         it = cache_queue_.begin();
144                 list<Cache::ItemPtr>::iterator
145                         end = cache_queue_.end();
146
147                 it = find(it, end, item);
148                 if (it != end)
149                         cache_queue_.erase(it);
150         }
151         cache_queue_.push_front(item);
152         if (!running_)
153                 startLoader();
154 }
155
156
157
158 /////////////////////////////////////////////////////////////////////
159 //
160 // GraphicsLoader
161 //
162 /////////////////////////////////////////////////////////////////////
163
164 typedef std::shared_ptr<Image> ImagePtr;
165
166 class Loader::Impl {
167         friend class Loader;
168 public:
169         ///
170         Impl(FileName const & doc_file);
171         ///
172         ~Impl();
173         ///
174         void resetFile(FileName const &);
175         ///
176         void resetParams(Params const &);
177         ///
178         void createPixmap();
179         ///
180         void startLoading();
181         ///
182         Params const & params() const { return params_; }
183
184         ///
185         FileName doc_file_;
186         /// The loading status of the image.
187         ImageStatus status_;
188         /** Must store a copy of the cached item to ensure that it is not
189          *  erased unexpectedly by the cache itself.
190          */
191         Cache::ItemPtr cached_item_;
192         /// We modify a local copy of the image once it is loaded.
193         ImagePtr image_;
194         /// This signal is emitted when the image loading status changes.
195         signal<void()> signal_;
196         /// The connection of the signal statusChanged
197         scoped_connection connection_;
198
199         double displayPixelRatio() const
200         {
201                 return params_.pixel_ratio;
202         }
203         void setDisplayPixelRatio(double scale)
204         {
205                 params_.pixel_ratio = scale;
206         }
207
208 private:
209         ///
210         void statusChanged();
211         ///
212         void checkedLoading();
213
214         ///
215         Params params_;
216 };
217
218
219 Loader::Loader(FileName const & doc_file)
220         : pimpl_(new Impl(doc_file))
221 {}
222
223
224 Loader::Loader(FileName const & doc_file, FileName const & file, bool display)
225         : pimpl_(new Impl(doc_file))
226 {
227         reset(file, display);
228 }
229
230
231 Loader::Loader(FileName const & doc_file, FileName const & file, Params const & params)
232         : pimpl_(new Impl(doc_file))
233 {
234         reset(file, params);
235 }
236
237
238 Loader::Loader(FileName const & doc_file, Loader const & other)
239         : pimpl_(new Impl(doc_file))
240 {
241         Params const & params = other.pimpl_->params();
242         reset(params.filename, params);
243 }
244
245
246 Loader::Loader(Loader const & other)
247         : pimpl_(new Impl(other.pimpl_->doc_file_))
248 {
249         Params const & params = other.pimpl_->params();
250         reset(params.filename, params);
251 }
252
253
254 Loader::~Loader()
255 {
256         delete pimpl_;
257 }
258
259
260 Loader & Loader::operator=(Loader const & other)
261 {
262   LASSERT(false, /**/);
263         if (this != &other) {
264                 delete pimpl_;
265                 pimpl_ = new Impl(other.pimpl_->doc_file_);
266                 Params const & params = other.pimpl_->params();
267                 reset(params.filename, params);
268         }
269         return *this;
270 }
271
272
273 void Loader::reset(FileName const & file, bool display) const
274 {
275         Params params;
276         params.display = display;
277         pimpl_->resetParams(params);
278
279         pimpl_->resetFile(file);
280         pimpl_->createPixmap();
281 }
282
283
284 void Loader::reset(FileName const & file, Params const & params) const
285 {
286         pimpl_->resetParams(params);
287         pimpl_->resetFile(file);
288         pimpl_->createPixmap();
289 }
290
291
292 void Loader::reset(Params const & params) const
293 {
294         pimpl_->resetParams(params);
295         pimpl_->createPixmap();
296 }
297
298
299 void Loader::startLoading() const
300 {
301         if (pimpl_->status_ != WaitingToLoad || !pimpl_->cached_item_
302             || pimpl_->cached_item_->status() == Converting)
303                 return;
304         pimpl_->startLoading();
305 }
306
307
308 void Loader::reload() const
309 {
310         pimpl_->cached_item_->startLoading();
311 }
312
313
314 void Loader::startMonitoring() const
315 {
316         if (!pimpl_->cached_item_)
317                 return;
318
319         pimpl_->cached_item_->startMonitoring();
320 }
321
322
323 bool Loader::monitoring() const
324 {
325         if (!pimpl_->cached_item_)
326                 return false;
327
328         return pimpl_->cached_item_->monitoring();
329 }
330
331
332 void Loader::checkModifiedAsync() const
333 {
334         if (!pimpl_->cached_item_)
335                 return;
336
337         pimpl_->cached_item_->checkModifiedAsync();
338 }
339
340
341 FileName const & Loader::filename() const
342 {
343         static FileName const empty;
344         return pimpl_->cached_item_ ?
345                 pimpl_->cached_item_->filename() : empty;
346 }
347
348
349 ImageStatus Loader::status() const
350 {
351         return pimpl_->status_;
352 }
353
354
355 double Loader::displayPixelRatio() const
356 {
357         return pimpl_->displayPixelRatio();
358 }
359
360
361 void Loader::setDisplayPixelRatio(double scale)
362 {
363         pimpl_->setDisplayPixelRatio(scale);
364 }
365
366
367 connection Loader::connect(slot const & slot) const
368 {
369         return pimpl_->signal_.connect(slot);
370 }
371
372
373 Image const * Loader::image() const
374 {
375         return pimpl_->image_.get();
376 }
377
378
379 Loader::Impl::Impl(FileName const & doc_file)
380         : doc_file_(doc_file), status_(WaitingToLoad)
381 {
382 }
383
384
385 Loader::Impl::~Impl()
386 {
387         resetFile(FileName());
388 }
389
390
391 void Loader::Impl::resetFile(FileName const & file)
392 {
393         FileName const old_file = cached_item_ ?
394                 cached_item_->filename() : FileName();
395
396         if (file == old_file)
397                 return;
398
399         // If monitoring() the current file, should continue to monitor the
400         // new file.
401         bool continue_monitoring = false;
402
403         if (cached_item_ && !old_file.empty()) {
404                 continue_monitoring = cached_item_->monitoring();
405                 // cached_item_ is going to be reset, so the connected
406                 // signal needs to be disconnected.
407                 try {
408                         // This can in theory throw a BufferException
409                         connection_.disconnect();
410                 } catch (...) {
411                         LYXERR(Debug::GRAPHICS, "Unable to disconnect signal.");
412                 }
413                 cached_item_.reset();
414                 if (status_ != Converting) {
415                         Cache::get().remove(old_file);
416                 } else {
417                         //TODO remove cache item when it is not busy any more, see #7163
418                 }
419         }
420
421         status_ = cached_item_ ? cached_item_->status() : WaitingToLoad;
422         image_.reset();
423
424         if (cached_item_ || file.empty())
425                 return;
426
427         Cache & gc = Cache::get();
428         if (!gc.inCache(file))
429                 gc.add(file, doc_file_);
430
431         // We /must/ make a local copy of this.
432         cached_item_ = gc.item(file);
433         status_ = cached_item_->status();
434
435         if (continue_monitoring && !cached_item_->monitoring())
436                 cached_item_->startMonitoring();
437
438         // This is a scoped connection
439         connection_ = cached_item_->connect([this](){ statusChanged(); });
440 }
441
442
443 void Loader::Impl::resetParams(Params const & params)
444 {
445         if (params == params_)
446                 return;
447
448         params_ = params;
449         status_ = cached_item_ ? cached_item_->status() : WaitingToLoad;
450         image_.reset();
451 }
452
453
454 void Loader::Impl::statusChanged()
455 {
456         status_ = cached_item_ ? cached_item_->status() : WaitingToLoad;
457         createPixmap();
458         signal_();
459 }
460
461
462 void Loader::Impl::createPixmap()
463 {
464         if (!params_.display || status_ != Loaded)
465                 return;
466
467         if (!cached_item_) {
468                 LYXERR(Debug::GRAPHICS, "pixmap not cached yet");
469                 return;
470         }
471
472         if (!cached_item_->image()) {
473                 // There must have been a problem reading the file.
474                 LYXERR(Debug::GRAPHICS, "Graphics file not loaded.");
475                 return;
476         }
477
478         image_.reset(cached_item_->image()->clone());
479
480         if (params_.pixel_ratio == 1.0) {
481                 string filename = cached_item_->filename().absFileName();
482                 size_t idx = filename.find_last_of('.');
483                 if (idx != string::npos && idx > 3) {
484                         if (filename.substr(idx - 3, 3) == "@2x") {
485                                 params_.pixel_ratio = 2.0;
486                         }
487                 }
488         }
489
490         bool const success = image_->setPixmap(params_);
491
492         if (success) {
493                 status_ = Ready;
494         } else {
495                 image_.reset();
496                 status_ = ErrorGeneratingPixmap;
497         }
498 }
499
500 void Loader::Impl::startLoading()
501 {
502         if (status_ != WaitingToLoad)
503                 return;
504
505         if (cached_item_->tryDisplayFormat()) {
506                 status_ = Loaded;
507                 createPixmap();
508                 return;
509         }
510
511         LoaderQueue::get().touch(cached_item_);
512 }
513
514
515 } // namespace graphics
516 } // namespace lyx