Searching in bookmarks
[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
183     _innerResult = QtConcurrent::mapped(activeDicts(), mapSearch);
184     _resultWatcher.setFuture(_innerResult);
185
186     _innerBookmarks = QtConcurrent::run(bookmarks, &Bookmarks::searchWordList,
187                                         word);
188     _bookmarkSearchWatcher.setFuture(_innerBookmarks);
189 }
190
191
192
193 void Backbone::selectedDictionaries(QList<CommonDictInterface* > activeDicts) {
194     foreach(CommonDictInterface* dict, _dicts.keys())
195         if(activeDicts.contains(dict))
196             _dicts[dict] = 1;
197         else
198             _dicts[dict] = 0;
199     dictUpdated();
200  }
201
202
203
204 void Backbone::addDictionary(CommonDictInterface *dict, bool active) {
205     addInternalDictionary(dict,active);
206     dictUpdated();
207 }
208
209
210
211  void Backbone::addInternalDictionary(CommonDictInterface* dict, bool active) {
212      dict->setHash(_dicts.size()+1);
213      _dicts[dict] = active;
214      connect(dict, SIGNAL(settingsChanged()), this, SLOT(dictUpdated()));
215  }
216
217  void Backbone::removeDictionary(CommonDictInterface *dict) {
218      _dicts.remove(dict);
219      dictUpdated();
220
221  }
222
223
224
225  void Backbone::quit() {
226     stopSearching();
227     Q_EMIT closeOk();
228 }
229
230
231
232 void Backbone::translationReady() {
233     if(_innerResult.isFinished()) {
234         QFutureIterator<QList<Translation*> > it(_innerResult);
235
236         while(it.hasNext()) {
237             QList<Translation* > list = it.next();
238             foreach(Translation* trans, list)
239                 _result.insert(trans->key().toLower(), trans);
240         }
241     }
242
243     if(_innerBookmarks.isFinished()) {
244         QList<Translation*> list = _innerBookmarks.result();
245         qDebug() << "translation bookmarks" << list.size();
246         foreach(Translation* trans, list)
247                 _result.insert(trans->key().toLower(), trans);
248     }
249
250     if(!stopped && _innerResult.isFinished() && _innerBookmarks.isFinished())
251         Q_EMIT ready();
252 }
253
254 QStringList Backbone::getFilesFromDir(QString dir, QStringList nameFilter) {
255     QDir plug(QDir::toNativeSeparators(dir));
256     if(!plug.exists()) {
257         qDebug() << plug.absolutePath() << " folder dosen't exists";
258         return QStringList();
259     }
260     plug.setFilter(QDir::Files);
261     QStringList list = plug.entryList(nameFilter);
262
263     for(int i = 0; i < list.size(); i++)
264         list[i] = plug.absoluteFilePath(list.at(i));
265     return list;
266 }
267
268
269 void Backbone::loadPlugins() {
270     if(dryRun)
271         return;
272     QStringList nameFilter;
273     nameFilter << "*.so";
274     QStringList files = getFilesFromDir(_pluginPath, nameFilter);
275
276     foreach(QString file, files) {
277         QPluginLoader loader(file);
278         if(!loader.load()) {
279             qDebug()<< file << " " << loader.errorString();
280             continue;
281         }
282         QObject *pl = loader.instance();
283
284         CommonDictInterface *plugin = qobject_cast<CommonDictInterface*>(pl);
285         _plugins.append(plugin);
286     }
287 }
288
289
290
291 CommonDictInterface* Backbone::plugin(QString type) {
292     foreach(CommonDictInterface* plugin, _plugins)
293         if(plugin->type() == type)
294             return plugin;
295     return 0;
296 }
297
298
299
300 void Backbone::loadPrefs(QString fileName) {
301     if(dryRun)
302         return;
303     QFileInfo file(QDir::toNativeSeparators(fileName));
304     QDir confDir(file.dir());
305     if(!confDir.exists()){
306         qDebug() << "Configuration file dosn't exists ("
307                 << file.filePath() << ")";
308         return;
309     }
310     QSettings set(file.filePath(), QSettings::IniFormat);
311     _pluginPath = set.value("general/plugin_path", _pluginPath).toString();
312     _historyLen = set.value("general/history_length", 10).toInt();
313     _searchLimit = set.value("general/search_limit", 15).toInt();
314 }
315
316
317
318 void Backbone::savePrefs(QSettings *set) {
319     if(dryRun)
320         return;
321     set->setValue("general/plugin_path", _pluginPath);
322     set->setValue("general/history_length", _historyLen);
323     set->setValue("general/search_limit", _searchLimit);
324 }
325
326
327
328 void Backbone::saveDefaultPrefs(QSettings *set) {
329     if(dryRun)
330         return;
331     set->setValue("general/plugin_path", _defaultPluginPath);
332     set->setValue("general/history_length", _defaultHistoryLen);
333     set->setValue("general/search_limit", _defaultSearchLimit);
334 }
335
336
337
338 void Backbone::loadDicts(QString fileName, bool _default) {
339     if(dryRun)
340         return;
341     QFileInfo file(QDir::toNativeSeparators(fileName));
342     QDir confDir(file.dir());
343     if(!confDir.exists()){
344         qDebug() << "Configuration file dosn't exists ("
345                 << file.filePath() << ")";
346         return;
347     }
348
349     QSettings set(file.filePath(), QSettings::IniFormat);
350     QStringList dicts = set.childGroups();
351     foreach(QString dict, dicts) {
352         if(!dict.contains("dictionary_"))
353             continue;
354         CommonDictInterface* plug = plugin
355                                     (set.value(dict + "/type", "").toString());
356         if(!plug) {
357             qDebug() << "Config file error: "
358                     << set.value(dict + "/type", "").toString()
359                     << " dosen't exists";
360             continue;
361         }
362         Settings* plugSet = new Settings();
363         set.beginGroup(dict);
364         QStringList items = set.childKeys();
365         foreach(QString item, items) {
366             plugSet->setValue(item, set.value(item, "").toString());
367         }
368         bool active = set.value("active",1).toBool();
369
370         if(_default)
371             plugSet->setValue("_default_", "true");
372
373         set.endGroup();
374         addInternalDictionary(plug->getNew(plugSet), active);
375     }
376 }
377
378
379
380 void Backbone::dictUpdated() {
381     if(dryRun)
382         return;
383     QFileInfo file(QDir::toNativeSeparators(_configPath));
384     QDir confDir(file.dir());
385     if(!confDir.exists())
386         confDir.mkpath(file.dir().path());
387     QSettings set(file.filePath(), QSettings::IniFormat);
388     set.clear();
389
390     QFileInfo defFile(QDir::toNativeSeparators(_defaultConfigPath));
391     QDir defConfDir(defFile.dir());
392     if(!defConfDir.exists())
393         defConfDir.mkpath(defFile.dir().path());
394     QSettings defSet(defFile.filePath(), QSettings::IniFormat);
395     defSet.clear();
396     savePrefs(&set);
397     saveDefaultPrefs(&defSet);
398
399     foreach(CommonDictInterface* dict, _dicts.keys()){
400         if(!dict || !dict->settings())
401             continue;
402         if(!dict->settings()->keys().contains("_default_"))
403             saveState(&set, dict->settings(), _dicts[dict], dict->hash());
404         else
405             saveState(&defSet, dict->settings(), _dicts[dict], dict->hash());
406     }
407 }
408
409
410
411 void Backbone::saveState(QSettings* set, Settings* plugSet, bool active
412                          , uint hash) {
413     if(dryRun)
414         return;
415     if(!set || !plugSet)
416         return;
417     QString section;
418     section.append(QString("dictionary_%1").arg(hash));
419     QList<QString> keys = plugSet->keys();
420     foreach(QString key, keys)
421         set->setValue(section + "/" + key, plugSet->value(key));
422     set->setValue(section + "/active", active);
423 }
424
425
426
427 QStringList Backbone::htmls() {
428     return _htmlResult;
429 }
430
431
432
433 void Backbone::searchHtml(QList<Translation *> translations) {
434     _htmlResult.clear();
435     QList<TranslationPtr> dummy;
436     stopped = false;
437     qDebug()<< "search html";
438     foreach(Translation* tr, translations)
439         dummy.append(TranslationPtr(tr));
440     qDebug()<< "search html mapp " << dummy.size();
441
442    _innerHtmlResult = QtConcurrent::mapped(dummy,
443                                             &TranslationPtr::toHtml);
444     qDebug()<< "search html after map";
445    _htmlResultWatcher.setFuture(_innerHtmlResult);
446 }
447
448 void Backbone::htmlTranslationReady() {
449
450     QFutureIterator<QString> it(_innerHtmlResult);
451     while(it.hasNext())
452        _htmlResult.append(it.next());
453
454     if(!stopped)
455         Q_EMIT htmlReady();
456
457 }
458
459
460 QList<CommonDictInterface*> Backbone::activeDicts() {
461     QList<CommonDictInterface*>res;
462     foreach(CommonDictInterface* dict, _dicts.keys())
463         if(_dicts[dict])
464             res.append(dict);
465     return res;
466
467 }
468
469
470
471 void Backbone::bookmarksListReady() {
472    _bookmarksResult = _innerBookmarks.result();
473    Q_EMIT bookmarksReady();
474 }