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