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