Fixed #6404 - minimal and maximal zoom factors
[mdictionary] / src / mdictionary / backbone / backbone.cpp
1 /*******************************************************************************
2
3     This file is part of mDictionary.
4
5     mDictionary is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 3 of the License, or
8     (at your option) any later version.
9
10     mDictionary is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with mDictionary.  If not, see <http://www.gnu.org/licenses/>.
17
18     Copyright 2010 Comarch S.A.
19
20 *******************************************************************************/
21 /*! \file backbone.cpp
22 \brief Backbone/core main file \see Backbone
23
24
25 \author Bartosz Szatkowski <bulislaw@linux.com>
26 */
27
28 #include "backbone.h"
29 #include "ConfigGenerator.h"
30 class ConfigGenerator;
31 #include <QDebug>
32
33 int Backbone::_searchLimit;
34
35 // Sadly QtConcurrent::mapped doesn't let me use something like calling method of
36 // some class with supplied argument; so I have to sin against art and put
37 // global function and variable so I could supply function with some parameter
38 QString mappedSearch;
39 QList<Translation*> mapSearch(CommonDictInterface *dict) {
40     if(dict)
41         return dict->searchWordList(mappedSearch, Backbone::_searchLimit);
42     return QList<Translation*>();
43 }
44
45
46
47 /*! Smart pointer (kind of) for translation object
48
49     QtConcurrent::mapped uses collection of data and one function, what I need is
50     to map single data object to method calls for multiple objects. TranslationPtr
51     is an attempt to store method call as a data -> moreover QtConcurrent allows only for
52     methods without any parameters so TranslationPtr is created with Translation
53     object -> ready to call toHtml() for supplied Translation.
54
55     Another thing is that QtConcurrent doesn't like pointers in data collection
56     so TranslationPtr is a way to hide real translation object (pointer to object)
57     */
58 class TranslationPtr {
59     Translation* _tr;
60 public:
61     TranslationPtr(Translation* tr) :_tr(tr) {}
62
63     /*! \return translation text for corresponding Translation object */
64     QString toHtml() const {
65         QString trans;
66         trans = _tr->toHtml();
67         return trans;
68
69     }
70 };
71
72 void Backbone::init() {
73
74    _dictNum = 0;
75    _dir = QDir::homePath() + "/.mdictionary/";
76    if(!QDir(_dir).exists())
77        QDir().mkdir(_dir);
78
79   _configPath = _dir + "mdictionary.config";
80   _pluginPath = "/usr/lib/mdictionary/plugins/";
81
82    //Install default config files
83    ConfigGenerator confGen;
84    ///confGen.generateCss(_dir + "style.css");
85    confGen.generateDefaultConfig(_configPath);
86
87    loadPrefs(_configPath);
88
89    loadPlugins();
90
91    loadDicts(_configPath);
92
93    connect(&_resultWatcher, SIGNAL(finished()), this, SLOT(translationReady()));
94    connect(&_htmlResultWatcher, SIGNAL(finished()), this,
95            SLOT(htmlTranslationReady()));
96    connect(&_bookmarkWatcher, SIGNAL(finished()), this,
97            SLOT(bookmarksListReady()));
98    connect(&_bookmarkSearchWatcher, SIGNAL(finished()), this,
99            SLOT(translationReady()));
100
101    // In common opinion perfect thread count is cores_number+1 (in qt perfect
102    // thread count is set to cores number) so iam changin it
103    QThreadPool::globalInstance()->setMaxThreadCount(
104            QThreadPool::globalInstance()->maxThreadCount()+1);
105
106    _history = new History(_historyLen, this);
107 }
108
109
110
111 Backbone::Backbone(QString pluginPath, QString configPath, bool dry,
112                    QObject *parent)
113     : QObject(parent)
114 {
115     _pluginPath = pluginPath;
116     _configPath = configPath;
117
118     dryRun = false;
119     if(dry)
120         dryRun = true;
121     init();
122 }
123
124
125
126 Backbone::~Backbone()
127 {
128     QListIterator<CommonDictInterface*> it(_dicts.keys());
129
130     while(it.hasNext())
131         delete it.next();
132
133     it = QListIterator<CommonDictInterface*>(_plugins);
134     while(it.hasNext())
135         delete it.next();
136
137     QHashIterator<QString, Translation*> it2(_result);
138     while(it2.hasNext())
139         delete it2.next().value();
140
141 }
142
143
144
145
146 Backbone::Backbone(const Backbone &b) :QObject(b.parent()) {
147     init();
148     _dicts = QHash<CommonDictInterface*, bool > (b._dicts);
149     _plugins = QList<CommonDictInterface* > (b._plugins);
150     _result = QHash<QString, Translation* > (b._result);
151     _searchLimit = b.searchLimit();
152 }
153
154
155
156
157 int Backbone::searchLimit() const {
158     return _searchLimit;
159 }
160
161
162
163 QHash<CommonDictInterface*, bool > Backbone::getDictionaries() {
164     return _dicts;
165 }
166
167
168
169 QList<CommonDictInterface* > Backbone::getPlugins() {
170     return _plugins;
171 }
172
173
174
175 History* Backbone::history() {
176     return _history;
177 }
178
179
180
181 QMultiHash<QString, Translation*> Backbone::result() {
182     return _result;
183 }
184
185
186
187 void Backbone::stopSearching() {
188     if(stopped)
189         return;
190
191     foreach(CommonDictInterface* dict, _dicts.keys())
192         dict->stop();
193     stopped = true;
194     _innerHtmlResult.cancel();
195     _innerResult.cancel();
196     Q_EMIT searchCanceled();
197 }
198
199
200
201 void Backbone::search(QString word){
202     _result.clear();
203     mappedSearch = word.toLower();
204
205     stopped = false;
206
207     // When dictFin and bookmarkFin is set to true then translationReady()
208     // signal is emitted see translationReady(),
209     // so when searching only in one of them, corresponding *Fin is set to false
210     // and other to true so program is waiting only for one translation
211     dictFin = !_searchDicts;
212     bookmarkFin = !_searchBookmarks;
213
214     if(!_searchDicts && !_searchBookmarks) {
215         Q_EMIT ready();
216         Q_EMIT notify(Notify::Warning, tr("You have to specify where You want "
217                 "to look for translations"));
218     }
219
220     if (_searchDicts) {
221         _innerResult = QtConcurrent::mapped(activeDicts(), mapSearch);
222         _resultWatcher.setFuture(_innerResult);
223     }
224
225     if(_searchBookmarks) {
226         _innerBookmarks = QtConcurrent::run(_bookmarks,
227                 &Bookmarks::searchWordList, word);
228         _bookmarkSearchWatcher.setFuture(_innerBookmarks);
229     }
230 }
231
232
233
234 void Backbone::selectedDictionaries(QList<CommonDictInterface* > activeDicts) {
235     foreach(CommonDictInterface* dict, _dicts.keys())
236         if(activeDicts.contains(dict))
237             _dicts[dict] = 1;
238         else
239             _dicts[dict] = 0;
240     dictUpdated();
241  }
242
243
244
245 void Backbone::addDictionary(CommonDictInterface *dict, bool active) {
246     addInternalDictionary(dict,active);
247     dictUpdated();
248 }
249
250
251
252 void Backbone::addInternalDictionary(CommonDictInterface* dict, bool active) {
253     if(dict) {
254         dict->setHash(++_dictNum); // Hash must be uniqe in every session but not between
255         _dicts[dict] = active;
256         connect(dict, SIGNAL(settingsChanged()), this, SLOT(dictUpdated()));
257         connect(dict, SIGNAL(notify(Notify::NotifyType,QString)), this,
258             SIGNAL(notify(Notify::NotifyType,QString)));
259     }
260 }
261
262
263
264  void Backbone::removeDictionary(CommonDictInterface *dict) {
265      _dicts.remove(dict);
266      if(dict) {
267         dict->clean();
268         delete dict;
269      }
270      dictUpdated();
271  }
272
273
274
275  void Backbone::quit() {
276     stopSearching();
277     Q_EMIT closeOk();
278 }
279
280
281
282 void Backbone::translationReady() {
283     bool changed = 0; // prevents from doubling ready() signal, when both if's are
284                       //  executed in one translationReady() call then second
285                       // translationReady() call doubles ready*() emit
286
287     if(!dictFin && _innerResult.isFinished()) {
288         changed = 1;
289         dictFin = 1;
290         QFutureIterator<QList<Translation*> > it(_innerResult);
291
292         while(it.hasNext()) {
293             QList<Translation* > list = it.next();
294             foreach(Translation* trans, list) {
295                 if(!trans)
296                     continue;
297                 if(!_searchBookmarks)
298                     trans->setBookmark(_bookmarks.
299                             inBookmarks(trans->key()));
300                 _result.insert(trans->key().toLower(), trans);
301            }
302         }
303     }
304
305     if(!bookmarkFin && _innerBookmarks.isFinished()) {
306         changed = 1;
307         bookmarkFin = 1;
308         QList<Translation*> list = _innerBookmarks.result();
309
310         foreach(Translation* trans, list)
311                 _result.insert(trans->key().toLower(), trans);
312     }
313
314     if(!stopped && bookmarkFin && dictFin && changed) {
315         Q_EMIT ready();
316     }
317 }
318
319
320
321
322 QStringList Backbone::getFilesFromDir(QString dir, QStringList nameFilter) {
323     QDir plug(QDir::toNativeSeparators(dir));
324     if(!plug.exists()) {
325         qDebug() << plug.absolutePath() << " folder doesn't exist";
326         Q_EMIT notify(Notify::Warning,
327                 tr("%1 folder doesn't exist.").arg(plug.path()));
328         return QStringList();
329     }
330     plug.setFilter(QDir::Files);
331     QStringList list = plug.entryList(nameFilter);
332
333     for(int i = 0; i < list.size(); i++)
334         list[i] = plug.absoluteFilePath(list.at(i));
335     return list;
336 }
337
338
339 void Backbone::loadPlugins() {
340     if(dryRun)
341         return;
342     QStringList nameFilter;
343     nameFilter << "*.so" << "*.so.*";
344     QStringList files = getFilesFromDir(_pluginPath, nameFilter);
345
346     foreach(QString file, files) {
347         QPluginLoader loader(file);
348         if(!loader.load()) {
349             Q_EMIT notify(Notify::Error,
350                     tr("%1 plugin cannot be loaded: %2.")
351                     .arg(file).arg(loader.errorString()));
352             continue;
353         }
354         QObject *pl = loader.instance();
355
356         bool exists = 0;
357         CommonDictInterface *plugin = qobject_cast<CommonDictInterface*>(pl);
358         foreach(CommonDictInterface* pl, _plugins)
359             if(pl->type() == plugin->type()) {
360                 exists = 1;
361                 break;
362            }
363         if(!exists) {
364             _plugins.append(plugin);
365             plugin->retranslate();
366             connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
367                     this, SIGNAL(notify(Notify::NotifyType,QString)));
368         }
369     }
370 }
371
372
373
374 CommonDictInterface* Backbone::plugin(QString type) {
375     foreach(CommonDictInterface* plugin, _plugins)
376         if(plugin->type() == type)
377             return plugin;
378     return 0;
379 }
380
381
382
383 void Backbone::loadPrefs(QString fileName) {
384     if(dryRun)
385         return;
386     QFileInfo file(QDir::toNativeSeparators(fileName));
387     QDir confDir(file.dir());
388     if(!confDir.exists()){
389         qDebug() << "Configuration file doesn't exist ("
390                 << file.filePath() << ")";
391         Q_EMIT notify(Notify::Warning,
392                 tr("%1 configuration file doesn't exist.")
393                 .arg(file.filePath()));
394         return;
395     }
396     QSettings set(file.filePath(), QSettings::IniFormat);
397     _pluginPath = set.value("general/plugin_path", _pluginPath).toString();
398     _historyLen = set.value("general/history_size", 10).toInt();
399     _searchLimit = set.value("general/search_limit", 15).toInt();
400     _searchBookmarks = set.value("general/search_bookmarks",1).toBool();
401     _searchDicts = set.value("general/search_dictionaries",1).toBool();
402     _zoom = set.value("general/zoom", 1.0).toReal();
403 }
404
405
406
407 void Backbone::savePrefs(QSettings *set) {
408     if(dryRun)
409         return;
410     set->setValue("general/plugin_path", _pluginPath);
411     set->setValue("general/history_size", _historyLen);
412     set->setValue("general/search_limit", _searchLimit);
413     set->setValue("general/search_bookmarks", _searchBookmarks);
414     set->setValue("general/search_dictionaries", _searchDicts);
415     set->setValue("general/zoom", _zoom);
416 }
417
418
419
420 void Backbone::loadDicts(QString fileName) {
421     if(dryRun)
422         return;
423
424     QFileInfo file(QDir::toNativeSeparators(fileName));
425     QDir confDir(file.dir());
426     if(!confDir.exists()){
427         qDebug() << "Configuration file doesn't exist ("
428                 << file.filePath() << ")";
429         Q_EMIT notify(Notify::Warning,
430                 tr("%1 configuration file doesn't exist.")
431                 .arg(file.filePath()));
432         return;
433     }
434
435     QSettings set(file.filePath(), QSettings::IniFormat);
436     QStringList dicts = set.childGroups();
437     foreach(QString dict, dicts) {
438         if(!dict.contains("dictionary_"))
439             continue;
440         CommonDictInterface* plug = plugin
441                                     (set.value(dict + "/type", "").toString());
442         if(!plug) {
443             qDebug() << "Config file error: "
444                     << set.value(dict + "/type", "").toString()
445                     << " doesn't exist";
446             Q_EMIT notify(Notify::Warning,
447                     tr("Configuration file error. %2 plugin doesn't exist.")
448                     .arg(set.value(dict + "/type", "").toString()));
449             continue;
450         }
451         Settings* plugSet = new Settings();
452         set.beginGroup(dict);
453         QStringList items = set.childKeys();
454         foreach(QString item, items) {
455             plugSet->setValue(item, set.value(item, "").toString());
456         }
457         bool active = set.value("active",1).toBool();
458
459         set.endGroup();
460         addInternalDictionary(plug->getNew(plugSet), active);
461         delete plugSet;
462     }
463 }
464
465
466
467 void Backbone::dictUpdated() {
468     if(dryRun)
469         return;
470
471     // For convienence this function is called for each change in dictionaries
472     // and each call dumps configuration for all dictionaries into file.
473     // Maybe a better way would be to store new/changed configuration but
474     // parsing settings file and figuring out what was changed, in my opinion,
475     // would take more time
476     _history->setMaxSize(_historyLen);
477     QFileInfo file(QDir::toNativeSeparators(_configPath));
478     QDir confDir(file.dir());
479     if(!confDir.exists())
480         confDir.mkpath(file.dir().path());
481     QSettings set(file.filePath(), QSettings::IniFormat);
482     set.clear();
483
484     savePrefs(&set);
485
486     foreach(CommonDictInterface* dict, _dicts.keys()){
487         if(!dict || !dict->settings())
488             continue;
489         saveState(&set, dict->settings(), _dicts[dict], dict->hash());
490     }
491 }
492
493
494
495 void Backbone::saveState(QSettings* set, Settings* plugSet, bool active
496                          , uint hash) {
497     if(dryRun)
498         return;
499     if(!set || !plugSet)
500         return;
501
502     QString section;
503     section.append(QString("dictionary_%1").arg(hash));
504     QList<QString> keys = plugSet->keys();
505     foreach(QString key, keys)
506         set->setValue(section + "/" + key, plugSet->value(key));
507     set->setValue(section + "/active", active);
508 }
509
510
511
512 QStringList Backbone::htmls() {
513     return _htmlResult;
514 }
515
516
517
518 void Backbone::searchHtml(QList<Translation *> translations) {
519     _htmlResult.clear();
520
521     QList<TranslationPtr> dummy;
522     stopped = false;
523     foreach(Translation* tr, translations) {
524          if(containsDict(tr->dict()) || !tr->dict())
525             dummy.append(TranslationPtr(tr));
526   /*      foreach(CommonDictInterface* dict, activeDicts()) {
527             Translation* trans = dict->getTranslationFor(tr->key());
528             if(trans)
529                 dummy.append(TranslationPtr(trans));
530         } */
531     }
532     if(translations.size()>0) {
533         Translation *tr = translations.at(0);
534         foreach(CommonDictInterface* dict, activeDicts()) {
535             Translation* trans = dict->getTranslationFor(tr->key());
536             if(trans)
537                 dummy.append(TranslationPtr(trans));
538         }
539     }
540
541    _innerHtmlResult = QtConcurrent::mapped(dummy,
542                                             &TranslationPtr::toHtml);
543    _htmlResultWatcher.setFuture(_innerHtmlResult);
544 }
545
546
547
548 void Backbone::htmlTranslationReady() {
549
550     QFutureIterator<QString> it(_innerHtmlResult);
551     QSet<QString> uniqe;
552     while(it.hasNext())
553         uniqe.insert(it.next());
554     _htmlResult.clear();
555     _htmlResult = uniqe.toList();
556
557     if(!stopped)
558         Q_EMIT htmlReady();
559
560 }
561
562
563 QList<CommonDictInterface*> Backbone::activeDicts() {
564     QList<CommonDictInterface*>res;
565     foreach(CommonDictInterface* dict, _dicts.keys())
566         if(_dicts[dict])
567             res.append(dict);
568     return res;
569
570 }
571
572
573
574 void Backbone::bookmarksListReady() {
575    _bookmarksResult = _innerBookmarks.result();
576    Q_EMIT bookmarksReady();
577 }
578
579
580
581
582 void Backbone::setSettings(Settings *settings) {
583     _historyLen = settings->value("history_size").toInt();
584     _searchLimit = settings->value("search_limit").toInt();
585     if(settings->value("search_dictionaries") == "true")
586         _searchDicts = 1;
587     else
588         _searchDicts = 0;
589     if(settings->value("search_bookmarks") == "true")
590         _searchBookmarks = 1;
591     else
592         _searchBookmarks = 0;
593     _zoom = settings->value("zoom").toFloat();
594     if(!_zoom)
595         _zoom ++;
596
597     dictUpdated();
598     if(settings)
599         delete settings;
600 }
601
602
603
604
605 Settings* Backbone::settings() {
606     Settings * settings = new Settings();
607     settings->setValue("history_size", QString("%1").arg(_historyLen));
608     settings->setValue("search_limit", QString("%1").arg(_searchLimit));
609     settings->setValue("zoom", QString("%1").arg(_zoom));
610     if(_searchBookmarks)
611         settings->setValue("search_bookmarks", "true");
612     else
613         settings->setValue("search_bookmarks", "false");
614
615     if(_searchDicts)
616         settings->setValue("search_dictionaries", "true");
617     else
618         settings->setValue("search_dictionaries", "false");
619     return settings;
620 }
621
622
623 bool Backbone::containsDict(uint hash) const {
624     QHashIterator<CommonDictInterface*, bool> it(_dicts);
625     if (!hash)
626         return false;
627     while(it.hasNext())
628         if(it.next().key()->hash() == hash)
629             return true;
630     return false;
631 }