Minor clean up
[mdictionary] / trunk / src / base / 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 <QDebug>
30
31 int Backbone::_searchLimit;
32
33 // Sadly QtConcurent mapped dont let me use something like calling method of
34 // some class with supplied argument
35 QString mappedSearch;
36 QList<Translation*> mapSearch(CommonDictInterface *dict) {
37     if(dict)
38         return dict->searchWordList(mappedSearch, Backbone::_searchLimit);
39     return QList<Translation*>();
40 }
41
42 class TranslationPtr {
43     Translation* _tr;
44 public:
45     TranslationPtr(Translation* tr) :_tr(tr) {}
46     QString toHtml() const {
47         QString trans;
48         trans = _tr->toHtml();
49         return trans;
50
51     }
52 };
53
54 void Backbone::init() {
55
56    if(!_configPath.size())
57        _configPath = QDir::homePath() + "/.mdictionary/mdictionary.config";
58    if(!_defaultConfigPath.size())
59        _defaultConfigPath = QDir::homePath() + "/.mdictionary/mdictionary.defaults";
60    if(!_pluginPath.size())
61        _pluginPath = "/usr/lib/mdictionary";
62    _historyLen = 10;
63    _searchLimit = 15;
64
65    loadPrefs(_defaultConfigPath);
66    _defaultPluginPath = _pluginPath;
67    _defaultHistoryLen = _historyLen;
68    _defaultSearchLimit = _searchLimit;
69    loadPrefs(_configPath);
70
71    loadPlugins();
72
73    loadDicts(_defaultConfigPath, true);
74    loadDicts(_configPath);
75
76    connect(&_resultWatcher, SIGNAL(finished()), this, SLOT(translationReady()));
77    connect(&_htmlResultWatcher, SIGNAL(finished()), this,
78            SLOT(htmlTranslationReady()));
79    connect(&_bookmarkWatcher, SIGNAL(finished()), this,
80            SLOT(bookmarksListReady()));
81    connect(&_bookmarkSearchWatcher, SIGNAL(finished()), this,
82            SLOT(translationReady()));
83
84    QThreadPool::globalInstance()->setMaxThreadCount(
85            QThreadPool::globalInstance()->maxThreadCount()+1);
86
87    _history = new History(5, this);
88    _dictNum = 0;
89 }
90
91
92
93 Backbone::Backbone(QString pluginPath, QString configPath, bool dry,
94                    QObject *parent)
95     : QObject(parent)
96 {
97     _pluginPath = pluginPath;
98     _configPath = configPath;
99     _defaultConfigPath = configPath;
100     dryRun = false;
101     if(dry)
102         dryRun = true;
103     init();
104 }
105
106
107
108 Backbone::~Backbone()
109 {
110     QListIterator<CommonDictInterface*> it(_dicts.keys());
111
112     while(it.hasNext())
113         delete it.next();
114
115     it = QListIterator<CommonDictInterface*>(_plugins);
116     while(it.hasNext())
117         delete it.next();
118
119     QHashIterator<QString, Translation*> it2(_result);
120     while(it2.hasNext())
121         delete it2.next().value();
122
123 }
124
125
126
127
128 Backbone::Backbone(const Backbone &b) :QObject(b.parent()) {
129     _dicts = QHash<CommonDictInterface*, bool > (b._dicts);
130     _plugins = QList<CommonDictInterface* > (b._plugins);
131     _result = QHash<QString, Translation* > (b._result);
132     _searchLimit = b.searchLimit();
133 }
134
135
136
137
138 int Backbone::searchLimit() const {
139     return _searchLimit;
140 }
141
142
143
144 QHash<CommonDictInterface*, bool > Backbone::getDictionaries() {
145     return _dicts;
146 }
147
148
149
150 QList<CommonDictInterface* > Backbone::getPlugins() {
151     return _plugins;
152 }
153
154
155
156 History* Backbone::history() {
157     return _history;
158 }
159
160
161
162 QMultiHash<QString, Translation*> Backbone::result() {
163     return _result;
164 }
165
166
167
168 void Backbone::stopSearching() {
169     if(stopped)
170         return;
171
172     foreach(CommonDictInterface* dict, _dicts.keys())
173         dict->stop();
174     stopped = true;
175     _innerHtmlResult.cancel();
176     _innerResult.cancel();
177     Q_EMIT searchCanceled();
178 }
179
180
181
182 void Backbone::search(QString word){
183     _result.clear();
184     mappedSearch = word.toLower();
185
186     stopped = false;
187     dictFin = !_searchDicts;
188     bookmarkFin = !_searchBookmarks;
189
190     if (_searchDicts) {
191         _innerResult = QtConcurrent::mapped(activeDicts(), mapSearch);
192         _resultWatcher.setFuture(_innerResult);
193     }
194
195     if(_searchBookmarks) {
196         _innerBookmarks = QtConcurrent::run(_bookmarks,
197                 &Bookmarks::searchWordList, word);
198         _bookmarkSearchWatcher.setFuture(_innerBookmarks);
199     }
200 }
201
202
203
204 void Backbone::selectedDictionaries(QList<CommonDictInterface* > activeDicts) {
205     foreach(CommonDictInterface* dict, _dicts.keys())
206         if(activeDicts.contains(dict))
207             _dicts[dict] = 1;
208         else
209             _dicts[dict] = 0;
210     dictUpdated();
211  }
212
213
214
215 void Backbone::addDictionary(CommonDictInterface *dict, bool active) {
216     addInternalDictionary(dict,active);
217     dictUpdated();
218 }
219
220
221
222  void Backbone::addInternalDictionary(CommonDictInterface* dict, bool active) {
223      dict->setHash(++_dictNum);
224      _dicts[dict] = active;
225      connect(dict, SIGNAL(settingsChanged()), this, SLOT(dictUpdated()));
226      connect(dict, SIGNAL(notify(Notify::NotifyType,QString)), this,
227              SIGNAL(notify(Notify::NotifyType,QString)));
228  }
229
230  void Backbone::removeDictionary(CommonDictInterface *dict) {
231      _dicts.remove(dict);
232      delete dict;
233      dictUpdated();
234
235  }
236
237
238
239  void Backbone::quit() {
240     stopSearching();
241     Q_EMIT closeOk();
242 }
243
244
245
246 void Backbone::translationReady() {
247     bool changed = 0; // prevents doubling ready() signal, when both if are
248                       //  executed in one translationReady() call then second
249                       // call doubles ready*() emit without any new data
250     if(!dictFin && _innerResult.isFinished()) {
251         changed = 1;
252         dictFin = 1;
253         QFutureIterator<QList<Translation*> > it(_innerResult);
254
255         while(it.hasNext()) {
256             QList<Translation* > list = it.next();
257             foreach(Translation* trans, list)
258                 _result.insert(trans->key().toLower(), trans);
259         }
260     }
261
262     if(!bookmarkFin && _innerBookmarks.isFinished()) {
263         changed = 1;
264         bookmarkFin = 1;
265         QList<Translation*> list = _innerBookmarks.result();
266
267         foreach(Translation* trans, list)
268                 _result.insert(trans->key().toLower(), trans);
269     }
270
271     if(!stopped && bookmarkFin && dictFin && changed) {
272         qDebug() << "EMITTTTTT";
273         Q_EMIT ready();
274         }
275 }
276
277 QStringList Backbone::getFilesFromDir(QString dir, QStringList nameFilter) {
278     QDir plug(QDir::toNativeSeparators(dir));
279     if(!plug.exists()) {
280         qDebug() << plug.absolutePath() << " folder dosen't exists";
281         Q_EMIT notify(Notify::Warning,
282                 QString("%1 folder dosen't exists.").arg(plug.path()));
283         return QStringList();
284     }
285     plug.setFilter(QDir::Files);
286     QStringList list = plug.entryList(nameFilter);
287
288     for(int i = 0; i < list.size(); i++)
289         list[i] = plug.absoluteFilePath(list.at(i));
290     return list;
291 }
292
293
294 void Backbone::loadPlugins() {
295     if(dryRun)
296         return;
297     QStringList nameFilter;
298     nameFilter << "*.so";
299     QStringList files = getFilesFromDir(_pluginPath, nameFilter);
300
301     foreach(QString file, files) {
302         QPluginLoader loader(file);
303         if(!loader.load()) {
304             Q_EMIT notify(Notify::Error,
305                     QString("%1 plugin cannot be loaded: %2.")
306                     .arg(file).arg(loader.errorString()));
307             qDebug()<< file << " " << loader.errorString();
308             continue;
309         }
310         QObject *pl = loader.instance();
311
312         CommonDictInterface *plugin = qobject_cast<CommonDictInterface*>(pl);
313         _plugins.append(plugin);
314     }
315 }
316
317
318
319 CommonDictInterface* Backbone::plugin(QString type) {
320     foreach(CommonDictInterface* plugin, _plugins)
321         if(plugin->type() == type)
322             return plugin;
323     return 0;
324 }
325
326
327
328 void Backbone::loadPrefs(QString fileName) {
329     if(dryRun)
330         return;
331     QFileInfo file(QDir::toNativeSeparators(fileName));
332     QDir confDir(file.dir());
333     if(!confDir.exists()){
334         qDebug() << "Configuration file dosn't exists ("
335                 << file.filePath() << ")";
336         Q_EMIT notify(Notify::Warning,
337                 QString("%1 configurationfile dosen't exists.")
338                 .arg(file.filePath()));
339         return;
340     }
341     QSettings set(file.filePath(), QSettings::IniFormat);
342     _pluginPath = set.value("general/plugin_path", _pluginPath).toString();
343     _historyLen = set.value("general/history_size", 10).toInt();
344     _searchLimit = set.value("general/search_limit", 15).toInt();
345     _searchBookmarks = set.value("general/search_bookmarks",1).toBool();
346     _searchDicts = set.value("general/search_dictionaries",1).toBool();
347 }
348
349
350
351 void Backbone::savePrefs(QSettings *set) {
352     if(dryRun)
353         return;
354     set->setValue("general/plugin_path", _pluginPath);
355     set->setValue("general/history_size", _historyLen);
356     set->setValue("general/search_limit", _searchLimit);
357     set->setValue("general/search_bookmarks", _searchBookmarks);
358     set->setValue("general/search_dictionaries", _searchDicts);
359 }
360
361
362
363 void Backbone::saveDefaultPrefs(QSettings *set) {
364     if(dryRun)
365         return;
366     set->setValue("general/plugin_path", _defaultPluginPath);
367     set->setValue("general/history_size", _defaultHistoryLen);
368     set->setValue("general/search_limit", _defaultSearchLimit);
369 }
370
371
372
373 void Backbone::loadDicts(QString fileName, bool _default) {
374     if(dryRun)
375         return;
376     QFileInfo file(QDir::toNativeSeparators(fileName));
377     QDir confDir(file.dir());
378     if(!confDir.exists()){
379         qDebug() << "Configuration file dosn't exists ("
380                 << file.filePath() << ")";
381         Q_EMIT notify(Notify::Warning,
382                 QString("%1 configurationfile dosen't exists.")
383                 .arg(file.filePath()));
384         return;
385     }
386
387     QSettings set(file.filePath(), QSettings::IniFormat);
388     QStringList dicts = set.childGroups();
389     foreach(QString dict, dicts) {
390         if(!dict.contains("dictionary_"))
391             continue;
392         CommonDictInterface* plug = plugin
393                                     (set.value(dict + "/type", "").toString());
394         if(!plug) {
395             qDebug() << "Config file error: "
396                     << set.value(dict + "/type", "").toString()
397                     << " dosen't exists";
398             Q_EMIT notify(Notify::Warning,
399                     QString("Configuration file error. %2 plugin dosen't exists.")
400                     .arg(set.value(dict + "/type", "").toString()));
401             continue;
402         }
403         Settings* plugSet = new Settings();
404         set.beginGroup(dict);
405         QStringList items = set.childKeys();
406         foreach(QString item, items) {
407             plugSet->setValue(item, set.value(item, "").toString());
408         }
409         bool active = set.value("active",1).toBool();
410
411         if(_default)
412             plugSet->setValue("_default_", "true");
413
414         set.endGroup();
415         addInternalDictionary(plug->getNew(plugSet), active);
416     }
417 }
418
419
420
421 void Backbone::dictUpdated() {
422     if(dryRun)
423         return;
424     _history->setMaxSize(_historyLen);
425     QFileInfo file(QDir::toNativeSeparators(_configPath));
426     QDir confDir(file.dir());
427     if(!confDir.exists())
428         confDir.mkpath(file.dir().path());
429     QSettings set(file.filePath(), QSettings::IniFormat);
430     set.clear();
431
432     QFileInfo defFile(QDir::toNativeSeparators(_defaultConfigPath));
433     QDir defConfDir(defFile.dir());
434     if(!defConfDir.exists())
435         defConfDir.mkpath(defFile.dir().path());
436     QSettings defSet(defFile.filePath(), QSettings::IniFormat);
437     defSet.clear();
438     savePrefs(&set);
439     saveDefaultPrefs(&defSet);
440
441     foreach(CommonDictInterface* dict, _dicts.keys()){
442         if(!dict || !dict->settings())
443             continue;
444         if(!dict->settings()->keys().contains("_default_"))
445             saveState(&set, dict->settings(), _dicts[dict], dict->hash());
446         else
447             saveState(&defSet, dict->settings(), _dicts[dict], dict->hash());
448     }
449 }
450
451
452
453 void Backbone::saveState(QSettings* set, Settings* plugSet, bool active
454                          , uint hash) {
455     if(dryRun)
456         return;
457     if(!set || !plugSet)
458         return;
459     QString section;
460     section.append(QString("dictionary_%1").arg(hash));
461     QList<QString> keys = plugSet->keys();
462     foreach(QString key, keys)
463         set->setValue(section + "/" + key, plugSet->value(key));
464     set->setValue(section + "/active", active);
465 }
466
467
468
469 QStringList Backbone::htmls() {
470     return _htmlResult;
471 }
472
473
474
475 void Backbone::searchHtml(QList<Translation *> translations) {
476     _htmlResult.clear();
477
478     QList<TranslationPtr> dummy;
479     stopped = false;
480     foreach(Translation* tr, translations) {
481         if(containsDict(tr->dict()) || !tr->dict())
482             dummy.append(TranslationPtr(tr));
483   }
484
485    _innerHtmlResult = QtConcurrent::mapped(dummy,
486                                             &TranslationPtr::toHtml);
487    _htmlResultWatcher.setFuture(_innerHtmlResult);
488 }
489
490
491
492 void Backbone::htmlTranslationReady() {
493
494     QFutureIterator<QString> it(_innerHtmlResult);
495     while(it.hasNext())
496        _htmlResult.append(it.next());
497
498     if(!stopped)
499         Q_EMIT htmlReady();
500
501 }
502
503
504 QList<CommonDictInterface*> Backbone::activeDicts() {
505     QList<CommonDictInterface*>res;
506     foreach(CommonDictInterface* dict, _dicts.keys())
507         if(_dicts[dict])
508             res.append(dict);
509     return res;
510
511 }
512
513
514
515 void Backbone::bookmarksListReady() {
516    _bookmarksResult = _innerBookmarks.result();
517    Q_EMIT bookmarksReady();
518 }
519
520
521
522
523 void Backbone::setSettings(Settings *settings) {
524     _historyLen = settings->value("history_size").toInt();
525     _searchLimit = settings->value("search_limit").toInt();
526     if(settings->value("search_dictionaries") == "true")
527         _searchDicts = 1;
528     else
529         _searchDicts = 0;
530     if(settings->value("search_bookmarks") == "true")
531         _searchBookmarks = 1;
532     else
533         _searchBookmarks = 0;
534     dictUpdated();
535 }
536
537
538
539
540 Settings* Backbone::settings() {
541     Settings * settings = new Settings();
542     settings->setValue("history_size", QString("%1").arg(_historyLen));
543     settings->setValue("search_limit", QString("%1").arg(_searchLimit));
544     if(_searchBookmarks)
545         settings->setValue("search_bookmarks", "true");
546     else
547         settings->setValue("search_bookmarks", "false");
548
549     if(_searchDicts)
550         settings->setValue("search_dictionaries", "true");
551     else
552         settings->setValue("search_dictionaries", "false");
553     return settings;
554 }
555
556
557 bool Backbone::containsDict(uint hash) const {
558     QHashIterator<CommonDictInterface*, bool> it(_dicts);
559     if (!hash)
560         return false;
561     while(it.hasNext())
562         if(it.next().key()->hash() == hash)
563             return true;
564     return false;
565 }