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