Added exception and event handling: gui & plugin
[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 dosent 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         Q_EMIT ready();
273         }
274 }
275
276 QStringList Backbone::getFilesFromDir(QString dir, QStringList nameFilter) {
277     QDir plug(QDir::toNativeSeparators(dir));
278     if(!plug.exists()) {
279         qDebug() << plug.absolutePath() << " folder dosen't exists";
280         Q_EMIT notify(Notify::Warning,
281                 QString("%1 folder dosen't exists.").arg(plug.path()));
282         return QStringList();
283     }
284     plug.setFilter(QDir::Files);
285     QStringList list = plug.entryList(nameFilter);
286
287     for(int i = 0; i < list.size(); i++)
288         list[i] = plug.absoluteFilePath(list.at(i));
289     return list;
290 }
291
292
293 void Backbone::loadPlugins() {
294     if(dryRun)
295         return;
296     QStringList nameFilter;
297     nameFilter << "*.so";
298     QStringList files = getFilesFromDir(_pluginPath, nameFilter);
299
300     foreach(QString file, files) {
301         QPluginLoader loader(file);
302         if(!loader.load()) {
303             Q_EMIT notify(Notify::Error,
304                     QString("%1 plugin cannot be loaded: %2.")
305                     .arg(file).arg(loader.errorString()));
306             qDebug()<< file << " " << loader.errorString();
307             continue;
308         }
309         QObject *pl = loader.instance();
310
311         CommonDictInterface *plugin = qobject_cast<CommonDictInterface*>(pl);
312         _plugins.append(plugin);
313     }
314 }
315
316
317
318 CommonDictInterface* Backbone::plugin(QString type) {
319     foreach(CommonDictInterface* plugin, _plugins)
320         if(plugin->type() == type)
321             return plugin;
322     return 0;
323 }
324
325
326
327 void Backbone::loadPrefs(QString fileName) {
328     if(dryRun)
329         return;
330     QFileInfo file(QDir::toNativeSeparators(fileName));
331     QDir confDir(file.dir());
332     if(!confDir.exists()){
333         qDebug() << "Configuration file dosn't exists ("
334                 << file.filePath() << ")";
335         Q_EMIT notify(Notify::Warning,
336                 QString("%1 configurationfile dosen't exists.")
337                 .arg(file.filePath()));
338         return;
339     }
340     QSettings set(file.filePath(), QSettings::IniFormat);
341     _pluginPath = set.value("general/plugin_path", _pluginPath).toString();
342     _historyLen = set.value("general/history_size", 10).toInt();
343     _searchLimit = set.value("general/search_limit", 15).toInt();
344     _searchBookmarks = set.value("general/search_bookmarks",1).toBool();
345     _searchDicts = set.value("general/search_dictionaries",1).toBool();
346 }
347
348
349
350 void Backbone::savePrefs(QSettings *set) {
351     if(dryRun)
352         return;
353     set->setValue("general/plugin_path", _pluginPath);
354     set->setValue("general/history_size", _historyLen);
355     set->setValue("general/search_limit", _searchLimit);
356     set->setValue("general/search_bookmarks", _searchBookmarks);
357     set->setValue("general/search_dictionaries", _searchDicts);
358 }
359
360
361
362 void Backbone::saveDefaultPrefs(QSettings *set) {
363     if(dryRun)
364         return;
365     set->setValue("general/plugin_path", _defaultPluginPath);
366     set->setValue("general/history_size", _defaultHistoryLen);
367     set->setValue("general/search_limit", _defaultSearchLimit);
368 }
369
370
371
372 void Backbone::loadDicts(QString fileName, bool _default) {
373     if(dryRun)
374         return;
375     QFileInfo file(QDir::toNativeSeparators(fileName));
376     QDir confDir(file.dir());
377     if(!confDir.exists()){
378         qDebug() << "Configuration file dosn't exists ("
379                 << file.filePath() << ")";
380         Q_EMIT notify(Notify::Warning,
381                 QString("%1 configurationfile dosen't exists.")
382                 .arg(file.filePath()));
383         return;
384     }
385
386     QSettings set(file.filePath(), QSettings::IniFormat);
387     QStringList dicts = set.childGroups();
388     foreach(QString dict, dicts) {
389         if(!dict.contains("dictionary_"))
390             continue;
391         CommonDictInterface* plug = plugin
392                                     (set.value(dict + "/type", "").toString());
393         if(!plug) {
394             qDebug() << "Config file error: "
395                     << set.value(dict + "/type", "").toString()
396                     << " dosen't exists";
397             Q_EMIT notify(Notify::Warning,
398                     QString("Configuration file error. %2 plugin dosen't exists.")
399                     .arg(set.value(dict + "/type", "").toString()));
400             continue;
401         }
402         Settings* plugSet = new Settings();
403         set.beginGroup(dict);
404         QStringList items = set.childKeys();
405         foreach(QString item, items) {
406             plugSet->setValue(item, set.value(item, "").toString());
407         }
408         bool active = set.value("active",1).toBool();
409
410         if(_default)
411             plugSet->setValue("_default_", "true");
412
413         set.endGroup();
414         addInternalDictionary(plug->getNew(plugSet), active);
415     }
416 }
417
418
419
420 void Backbone::dictUpdated() {
421     if(dryRun)
422         return;
423     _history->setMaxSize(_historyLen);
424     QFileInfo file(QDir::toNativeSeparators(_configPath));
425     QDir confDir(file.dir());
426     if(!confDir.exists())
427         confDir.mkpath(file.dir().path());
428     QSettings set(file.filePath(), QSettings::IniFormat);
429     set.clear();
430
431     QFileInfo defFile(QDir::toNativeSeparators(_defaultConfigPath));
432     QDir defConfDir(defFile.dir());
433     if(!defConfDir.exists())
434         defConfDir.mkpath(defFile.dir().path());
435     QSettings defSet(defFile.filePath(), QSettings::IniFormat);
436     defSet.clear();
437     savePrefs(&set);
438     saveDefaultPrefs(&defSet);
439
440     foreach(CommonDictInterface* dict, _dicts.keys()){
441         if(!dict || !dict->settings())
442             continue;
443         if(!dict->settings()->keys().contains("_default_"))
444             saveState(&set, dict->settings(), _dicts[dict], dict->hash());
445         else
446             saveState(&defSet, dict->settings(), _dicts[dict], dict->hash());
447     }
448 }
449
450
451
452 void Backbone::saveState(QSettings* set, Settings* plugSet, bool active
453                          , uint hash) {
454     if(dryRun)
455         return;
456     if(!set || !plugSet)
457         return;
458     QString section;
459     section.append(QString("dictionary_%1").arg(hash));
460     QList<QString> keys = plugSet->keys();
461     foreach(QString key, keys)
462         set->setValue(section + "/" + key, plugSet->value(key));
463     set->setValue(section + "/active", active);
464 }
465
466
467
468 QStringList Backbone::htmls() {
469     return _htmlResult;
470 }
471
472
473
474 void Backbone::searchHtml(QList<Translation *> translations) {
475     _htmlResult.clear();
476
477     QList<TranslationPtr> dummy;
478     stopped = false;
479     foreach(Translation* tr, translations) {
480         if(containsDict(tr->dict()) || !tr->dict())
481             dummy.append(TranslationPtr(tr));
482   }
483
484    _innerHtmlResult = QtConcurrent::mapped(dummy,
485                                             &TranslationPtr::toHtml);
486    _htmlResultWatcher.setFuture(_innerHtmlResult);
487 }
488
489 void Backbone::htmlTranslationReady() {
490
491     QFutureIterator<QString> it(_innerHtmlResult);
492     while(it.hasNext())
493        _htmlResult.append(it.next());
494
495     if(!stopped)
496         Q_EMIT htmlReady();
497
498 }
499
500
501 QList<CommonDictInterface*> Backbone::activeDicts() {
502     QList<CommonDictInterface*>res;
503     foreach(CommonDictInterface* dict, _dicts.keys())
504         if(_dicts[dict])
505             res.append(dict);
506     return res;
507
508 }
509
510
511
512 void Backbone::bookmarksListReady() {
513    _bookmarksResult = _innerBookmarks.result();
514    Q_EMIT bookmarksReady();
515 }
516
517
518
519
520 void Backbone::setSettings(Settings *settings) {
521     _historyLen = settings->value("history_size").toInt();
522     _searchLimit = settings->value("search_limit").toInt();
523     if(settings->value("search_dictionaries") == "true")
524         _searchDicts = 1;
525     else
526         _searchDicts = 0;
527     if(settings->value("search_bookmarks") == "true")
528         _searchBookmarks = 1;
529     else
530         _searchBookmarks = 0;
531     dictUpdated();
532 }
533
534
535
536
537 Settings* Backbone::settings() {
538     Settings * settings = new Settings();
539     settings->setValue("history_size", QString("%1").arg(_historyLen));
540     settings->setValue("search_limit", QString("%1").arg(_searchLimit));
541     if(_searchBookmarks)
542         settings->setValue("search_bookmarks", "true");
543     else
544         settings->setValue("search_bookmarks", "false");
545
546     if(_searchDicts)
547         settings->setValue("search_dictionaries", "true");
548     else
549         settings->setValue("search_dictionaries", "false");
550     return settings;
551 }
552
553
554 bool Backbone::containsDict(uint hash) const {
555     QHashIterator<CommonDictInterface*, bool> it(_dicts);
556     if (!hash)
557         return false;
558     while(it.hasNext())
559         if(it.next().key()->hash() == hash)
560             return true;
561     return false;
562 }