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