Merge branch 'master' of ssh://drop.maemo.org/git/mdictionary
[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     delete _history;
142 }
143
144
145
146
147 Backbone::Backbone(const Backbone &b) :QObject(b.parent()) {
148     init();
149     _dicts = QHash<CommonDictInterface*, bool > (b._dicts);
150     _plugins = QList<CommonDictInterface* > (b._plugins);
151     _result = QHash<QString, Translation* > (b._result);
152     _searchLimit = b.searchLimit();
153 }
154
155
156
157
158 int Backbone::searchLimit() const {
159     return _searchLimit;
160 }
161
162
163
164 QHash<CommonDictInterface*, bool > Backbone::getDictionaries() {
165     return _dicts;
166 }
167
168
169
170 QList<CommonDictInterface* > Backbone::getPlugins() {
171     return _plugins;
172 }
173
174
175
176 History* Backbone::history() {
177     return _history;
178 }
179
180
181
182 QMultiHash<QString, Translation*> Backbone::result() {
183     return _result;
184 }
185
186
187
188 void Backbone::stopSearching() {
189     if(stopped)
190         return;
191
192     foreach(CommonDictInterface* dict, _dicts.keys())
193         dict->stop();
194     stopped = true;
195     _innerHtmlResult.cancel();
196     _innerResult.cancel();
197     Q_EMIT searchCanceled();
198 }
199
200
201
202 void Backbone::search(QString word){
203     _result.clear();
204     mappedSearch = word.toLower();
205
206     stopped = false;
207
208     // When dictFin and bookmarkFin is set to true then translationReady()
209     // signal is emitted see translationReady(),
210     // so when searching only in one of them, corresponding *Fin is set to false
211     // and other to true so program is waiting only for one translation
212     dictFin = !_searchDicts;
213     bookmarkFin = !_searchBookmarks;
214
215     if(!_searchDicts && !_searchBookmarks) {
216         Q_EMIT ready();
217         Q_EMIT notify(Notify::Warning, tr("You have to specify where You want "
218                 "to look for translations"));
219     }
220
221     if (_searchDicts) {
222         _innerResult = QtConcurrent::mapped(activeDicts(), mapSearch);
223         _resultWatcher.setFuture(_innerResult);
224     }
225
226     if(_searchBookmarks) {
227         _innerBookmarks = QtConcurrent::run(_bookmarks,
228                 &Bookmarks::searchWordList, word);
229         _bookmarkSearchWatcher.setFuture(_innerBookmarks);
230     }
231 }
232
233
234
235 void Backbone::selectedDictionaries(QList<CommonDictInterface* > activeDicts) {
236     foreach(CommonDictInterface* dict, _dicts.keys())
237         if(activeDicts.contains(dict))
238             _dicts[dict] = 1;
239         else
240             _dicts[dict] = 0;
241     dictUpdated();
242  }
243
244
245
246 void Backbone::addDictionary(CommonDictInterface *dict, bool active) {
247     addInternalDictionary(dict,active);
248     dictUpdated();
249 }
250
251
252
253 void Backbone::addInternalDictionary(CommonDictInterface* dict, bool active) {
254     if(dict) {
255         dict->setHash(++_dictNum); // Hash must be uniqe in every session but not between
256         _dicts[dict] = active;
257         connect(dict, SIGNAL(settingsChanged()), this, SLOT(dictUpdated()));
258         connect(dict, SIGNAL(notify(Notify::NotifyType,QString)), this,
259             SIGNAL(notify(Notify::NotifyType,QString)));
260     }
261 }
262
263
264
265  void Backbone::removeDictionary(CommonDictInterface *dict) {
266      _dicts.remove(dict);
267      if(dict) {
268         dict->clean();
269         delete dict;
270      }
271      dictUpdated();
272  }
273
274
275
276  void Backbone::quit() {
277     stopSearching();
278     Q_EMIT closeOk();
279 }
280
281
282
283 void Backbone::translationReady() {
284     bool changed = 0; // prevents from doubling ready() signal, when both if's are
285                       //  executed in one translationReady() call then second
286                       // translationReady() call doubles ready*() emit
287
288     if(!dictFin && _innerResult.isFinished()) {
289         changed = 1;
290         dictFin = 1;
291         QFutureIterator<QList<Translation*> > it(_innerResult);
292
293         while(it.hasNext()) {
294             QList<Translation* > list = it.next();
295             foreach(Translation* trans, list) {
296                 if(!trans)
297                     continue;
298                 if(!_searchBookmarks)
299                     trans->setBookmark(_bookmarks.
300                             inBookmarks(trans->key()));
301                 _result.insert(trans->key().toLower(), trans);
302            }
303         }
304     }
305
306     if(!bookmarkFin && _innerBookmarks.isFinished()) {
307         changed = 1;
308         bookmarkFin = 1;
309         QList<Translation*> list = _innerBookmarks.result();
310
311         foreach(Translation* trans, list)
312                 _result.insert(trans->key().toLower(), trans);
313     }
314
315     if(!stopped && bookmarkFin && dictFin && changed) {
316         Q_EMIT ready();
317     }
318 }
319
320
321
322
323 QStringList Backbone::getFilesFromDir(QString dir, QStringList nameFilter) {
324     QDir plug(QDir::toNativeSeparators(dir));
325     if(!plug.exists()) {
326         qDebug() << plug.absolutePath() << " folder doesn't exist";
327         Q_EMIT notify(Notify::Warning,
328                 tr("%1 folder doesn't exist.").arg(plug.path()));
329         return QStringList();
330     }
331     plug.setFilter(QDir::Files);
332     QStringList list = plug.entryList(nameFilter);
333
334     for(int i = 0; i < list.size(); i++)
335         list[i] = plug.absoluteFilePath(list.at(i));
336     return list;
337 }
338
339
340 void Backbone::loadPlugins() {
341     if(dryRun)
342         return;
343     QStringList nameFilter;
344     nameFilter << "*.so" << "*.so.*";
345     QStringList files = getFilesFromDir(_pluginPath, nameFilter);
346
347     foreach(QString file, files) {
348         QPluginLoader loader(file);
349         if(!loader.load()) {
350             Q_EMIT notify(Notify::Error,
351                     tr("%1 plugin cannot be loaded: %2.")
352                     .arg(file).arg(loader.errorString()));
353             continue;
354         }
355         QObject *pl = loader.instance();
356
357         bool exists = 0;
358         CommonDictInterface *plugin = qobject_cast<CommonDictInterface*>(pl);
359         foreach(CommonDictInterface* pl, _plugins)
360             if(pl->type() == plugin->type()) {
361                 exists = 1;
362                 break;
363            }
364         if(!exists) {
365             _plugins.append(plugin);
366             plugin->retranslate();
367             connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
368                     this, SIGNAL(notify(Notify::NotifyType,QString)));
369         }
370     }
371 }
372
373
374
375 CommonDictInterface* Backbone::plugin(QString type) {
376     foreach(CommonDictInterface* plugin, _plugins)
377         if(plugin->type() == type)
378             return plugin;
379     return 0;
380 }
381
382
383
384 void Backbone::loadPrefs(QString fileName) {
385     if(dryRun)
386         return;
387     QFileInfo file(QDir::toNativeSeparators(fileName));
388     QDir confDir(file.dir());
389     if(!confDir.exists()){
390         qDebug() << "Configuration file doesn't exist ("
391                 << file.filePath() << ")";
392         Q_EMIT notify(Notify::Warning,
393                 tr("%1 configuration file doesn't exist.")
394                 .arg(file.filePath()));
395         return;
396     }
397     QSettings set(file.filePath(), QSettings::IniFormat);
398     _pluginPath = set.value("general/plugin_path", _pluginPath).toString();
399     _historyLen = set.value("general/history_size", 10).toInt();
400     _searchLimit = set.value("general/search_limit", 15).toInt();
401     _searchBookmarks = set.value("general/search_bookmarks",1).toBool();
402     _searchDicts = set.value("general/search_dictionaries",1).toBool();
403     _zoom = set.value("general/zoom", 1.0).toReal();
404 }
405
406
407
408 void Backbone::savePrefs(QSettings *set) {
409     if(dryRun)
410         return;
411     set->setValue("general/plugin_path", _pluginPath);
412     set->setValue("general/history_size", _historyLen);
413     set->setValue("general/search_limit", _searchLimit);
414     set->setValue("general/search_bookmarks", _searchBookmarks);
415     set->setValue("general/search_dictionaries", _searchDicts);
416     set->setValue("general/zoom", _zoom);
417 }
418
419
420
421 void Backbone::loadDicts(QString fileName) {
422     if(dryRun)
423         return;
424
425     QFileInfo file(QDir::toNativeSeparators(fileName));
426     QDir confDir(file.dir());
427     if(!confDir.exists()){
428         qDebug() << "Configuration file doesn't exist ("
429                 << file.filePath() << ")";
430         Q_EMIT notify(Notify::Warning,
431                 tr("%1 configuration file doesn't exist.")
432                 .arg(file.filePath()));
433         return;
434     }
435
436     QSettings set(file.filePath(), QSettings::IniFormat);
437     QStringList dicts = set.childGroups();
438     foreach(QString dict, dicts) {
439         if(!dict.contains("dictionary_"))
440             continue;
441         CommonDictInterface* plug = plugin
442                                     (set.value(dict + "/type", "").toString());
443         if(!plug) {
444             qDebug() << "Config file error: "
445                     << set.value(dict + "/type", "").toString()
446                     << " doesn't exist";
447             Q_EMIT notify(Notify::Warning,
448                     tr("Configuration file error. %2 plugin doesn't exist.")
449                     .arg(set.value(dict + "/type", "").toString()));
450             continue;
451         }
452         Settings* plugSet = new Settings();
453         set.beginGroup(dict);
454         QStringList items = set.childKeys();
455         foreach(QString item, items) {
456             plugSet->setValue(item, set.value(item, "").toString());
457         }
458         bool active = set.value("active",1).toBool();
459
460         set.endGroup();
461         addInternalDictionary(plug->getNew(plugSet), active);
462         delete plugSet;
463     }
464 }
465
466
467
468 void Backbone::dictUpdated() {
469     if(dryRun)
470         return;
471
472     // For convienence this function is called for each change in dictionaries
473     // and each call dumps configuration for all dictionaries into file.
474     // Maybe a better way would be to store new/changed configuration but
475     // parsing settings file and figuring out what was changed, in my opinion,
476     // would take more time
477     _history->setMaxSize(_historyLen);
478     QFileInfo file(QDir::toNativeSeparators(_configPath));
479     QDir confDir(file.dir());
480     if(!confDir.exists())
481         confDir.mkpath(file.dir().path());
482     QSettings set(file.filePath(), QSettings::IniFormat);
483     set.clear();
484
485     savePrefs(&set);
486
487     foreach(CommonDictInterface* dict, _dicts.keys()){
488         if(!dict || !dict->settings())
489             continue;
490         saveState(&set, dict->settings(), _dicts[dict], dict->hash());
491     }
492 }
493
494
495
496 void Backbone::saveState(QSettings* set, Settings* plugSet, bool active
497                          , uint hash) {
498     if(dryRun)
499         return;
500     if(!set || !plugSet)
501         return;
502
503     QString section;
504     section.append(QString("dictionary_%1").arg(hash));
505     QList<QString> keys = plugSet->keys();
506     foreach(QString key, keys)
507         set->setValue(section + "/" + key, plugSet->value(key));
508     set->setValue(section + "/active", active);
509 }
510
511
512
513 QStringList Backbone::htmls() {
514     return _htmlResult;
515 }
516
517
518
519 void Backbone::searchHtml(QList<Translation *> translations) {
520     _htmlResult.clear();
521
522     QList<TranslationPtr> dummy;
523     stopped = false;
524     foreach(Translation* tr, translations) {
525          if(containsDict(tr->dict()) || !tr->dict())
526             dummy.append(TranslationPtr(tr));
527   /*      foreach(CommonDictInterface* dict, activeDicts()) {
528             Translation* trans = dict->getTranslationFor(tr->key());
529             if(trans)
530                 dummy.append(TranslationPtr(trans));
531         } */
532     }
533     if(translations.size()>0) {
534         Translation *tr = translations.at(0);
535         foreach(CommonDictInterface* dict, activeDicts()) {
536             Translation* trans = dict->getTranslationFor(tr->key());
537             if(trans)
538                 dummy.append(TranslationPtr(trans));
539         }
540     }
541
542    _innerHtmlResult = QtConcurrent::mapped(dummy,
543                                             &TranslationPtr::toHtml);
544    _htmlResultWatcher.setFuture(_innerHtmlResult);
545 }
546
547
548
549 void Backbone::htmlTranslationReady() {
550
551     QFutureIterator<QString> it(_innerHtmlResult);
552     QSet<QString> uniqe;
553     while(it.hasNext())
554         uniqe.insert(it.next());
555     _htmlResult.clear();
556     _htmlResult = uniqe.toList();
557
558     if(!stopped)
559         Q_EMIT htmlReady();
560
561 }
562
563
564 QList<CommonDictInterface*> Backbone::activeDicts() {
565     QList<CommonDictInterface*>res;
566     foreach(CommonDictInterface* dict, _dicts.keys())
567         if(_dicts[dict])
568             res.append(dict);
569     return res;
570
571 }
572
573
574
575 void Backbone::bookmarksListReady() {
576    _bookmarksResult = _innerBookmarks.result();
577    Q_EMIT bookmarksReady();
578 }
579
580
581
582
583 void Backbone::setSettings(Settings *settings) {
584     _historyLen = settings->value("history_size").toInt();
585     _searchLimit = settings->value("search_limit").toInt();
586     if(settings->value("search_dictionaries") == "true")
587         _searchDicts = 1;
588     else
589         _searchDicts = 0;
590     if(settings->value("search_bookmarks") == "true")
591         _searchBookmarks = 1;
592     else
593         _searchBookmarks = 0;
594     _zoom = settings->value("zoom").toFloat();
595     if(!_zoom)
596         _zoom ++;
597
598     dictUpdated();
599     if(settings)
600         delete settings;
601 }
602
603
604
605
606 Settings* Backbone::settings() {
607     Settings * settings = new Settings();
608     settings->setValue("history_size", QString("%1").arg(_historyLen));
609     settings->setValue("search_limit", QString("%1").arg(_searchLimit));
610     settings->setValue("zoom", QString("%1").arg(_zoom));
611     if(_searchBookmarks)
612         settings->setValue("search_bookmarks", "true");
613     else
614         settings->setValue("search_bookmarks", "false");
615
616     if(_searchDicts)
617         settings->setValue("search_dictionaries", "true");
618     else
619         settings->setValue("search_dictionaries", "false");
620     return settings;
621 }
622
623
624 bool Backbone::containsDict(uint hash) const {
625     QHashIterator<CommonDictInterface*, bool> it(_dicts);
626     if (!hash)
627         return false;
628     while(it.hasNext())
629         if(it.next().key()->hash() == hash)
630             return true;
631     return false;
632 }