1 /*******************************************************************************
3 This file is part of mDictionary.
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.
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.
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/>.
18 Copyright 2010 Comarch S.A.
20 *******************************************************************************/
21 /*! \file backbone.cpp
22 \brief Backbone/core main file \see Backbone
25 \author Bartosz Szatkowski <bulislaw@linux.com>
29 #include "ConfigGenerator.h"
30 class ConfigGenerator;
33 int Backbone::_searchLimit;
35 // Sadly QtConcurrent::mapped doesn't let me use something like calling method of
36 // some class with supplied argument; so I have to sin against art and put
37 // global function and variable so I could supply function with some parameter
39 QList<Translation*> mapSearch(CommonDictInterface *dict) {
41 return dict->searchWordList(mappedSearch, Backbone::_searchLimit);
42 return QList<Translation*>();
47 /*! Smart pointer (kind of) for translation object
49 QtConcurrent::mapped uses collection of data and one function, what I need is
50 to map single data object to method calls for multiple objects. TranslationPtr
51 is an attempt to store method call as a data -> moreover QtConcurrent allows only for
52 methods without any parameters so TranslationPtr is created with Translation
53 object -> ready to call toHtml() for supplied Translation.
55 Another thing is that QtConcurrent doesn't like pointers in data collection
56 so TranslationPtr is a way to hide real translation object (pointer to object)
58 class TranslationPtr {
61 TranslationPtr(Translation* tr) :_tr(tr) {}
63 /*! \return translation text for corresponding Translation object */
64 QString toHtml() const {
66 trans = _tr->toHtml();
72 void Backbone::init() {
75 _dir = QDir::homePath() + "/.mdictionary/";
76 if(!QDir(_dir).exists())
79 _configPath = _dir + "mdictionary.config";
80 _pluginPath = "/usr/lib/mdictionary/plugins/";
82 //Install default config files
83 ConfigGenerator confGen;
84 ///confGen.generateCss(_dir + "style.css");
85 confGen.generateDefaultConfig(_configPath);
87 loadPrefs(_configPath);
91 loadDicts(_configPath);
93 connect(&_resultWatcher, SIGNAL(finished()), this, SLOT(translationReady()));
94 connect(&_htmlResultWatcher, SIGNAL(finished()), this,
95 SLOT(htmlTranslationReady()));
96 connect(&_bookmarkWatcher, SIGNAL(finished()), this,
97 SLOT(bookmarksListReady()));
98 connect(&_bookmarkSearchWatcher, SIGNAL(finished()), this,
99 SLOT(translationReady()));
101 // In common opinion perfect thread count is cores_number+1 (in qt perfect
102 // thread count is set to cores number) so iam changin it
103 QThreadPool::globalInstance()->setMaxThreadCount(
104 QThreadPool::globalInstance()->maxThreadCount()+1);
106 _history = new History(_historyLen, this);
111 Backbone::Backbone(QString pluginPath, QString configPath, bool dry,
115 _pluginPath = pluginPath;
116 _configPath = configPath;
126 Backbone::~Backbone()
128 QListIterator<CommonDictInterface*> it(_dicts.keys());
133 it = QListIterator<CommonDictInterface*>(_plugins);
137 QHashIterator<QString, Translation*> it2(_result);
139 delete it2.next().value();
146 Backbone::Backbone(const Backbone &b) :QObject(b.parent()) {
148 _dicts = QHash<CommonDictInterface*, bool > (b._dicts);
149 _plugins = QList<CommonDictInterface* > (b._plugins);
150 _result = QHash<QString, Translation* > (b._result);
151 _searchLimit = b.searchLimit();
157 int Backbone::searchLimit() const {
163 QHash<CommonDictInterface*, bool > Backbone::getDictionaries() {
169 QList<CommonDictInterface* > Backbone::getPlugins() {
175 History* Backbone::history() {
181 QMultiHash<QString, Translation*> Backbone::result() {
187 void Backbone::stopSearching() {
191 foreach(CommonDictInterface* dict, _dicts.keys())
194 _innerHtmlResult.cancel();
195 _innerResult.cancel();
196 Q_EMIT searchCanceled();
201 void Backbone::search(QString word){
203 mappedSearch = word.toLower();
207 // When dictFin and bookmarkFin is set to true then translationReady()
208 // signal is emitted see translationReady(),
209 // so when searching only in one of them, corresponding *Fin is set to false
210 // and other to true so program is waiting only for one translation
211 dictFin = !_searchDicts;
212 bookmarkFin = !_searchBookmarks;
214 if(!_searchDicts && !_searchBookmarks) {
216 Q_EMIT notify(Notify::Warning, tr("You have to specify where You want "
217 "to look for translations"));
221 _innerResult = QtConcurrent::mapped(activeDicts(), mapSearch);
222 _resultWatcher.setFuture(_innerResult);
225 if(_searchBookmarks) {
226 _innerBookmarks = QtConcurrent::run(_bookmarks,
227 &Bookmarks::searchWordList, word);
228 _bookmarkSearchWatcher.setFuture(_innerBookmarks);
234 void Backbone::selectedDictionaries(QList<CommonDictInterface* > activeDicts) {
235 foreach(CommonDictInterface* dict, _dicts.keys())
236 if(activeDicts.contains(dict))
245 void Backbone::addDictionary(CommonDictInterface *dict, bool active) {
246 addInternalDictionary(dict,active);
252 void Backbone::addInternalDictionary(CommonDictInterface* dict, bool active) {
254 dict->setHash(++_dictNum); // Hash must be uniqe in every session but not between
255 _dicts[dict] = active;
256 connect(dict, SIGNAL(settingsChanged()), this, SLOT(dictUpdated()));
257 connect(dict, SIGNAL(notify(Notify::NotifyType,QString)), this,
258 SIGNAL(notify(Notify::NotifyType,QString)));
264 void Backbone::removeDictionary(CommonDictInterface *dict) {
275 void Backbone::quit() {
282 void Backbone::translationReady() {
283 bool changed = 0; // prevents from doubling ready() signal, when both if's are
284 // executed in one translationReady() call then second
285 // translationReady() call doubles ready*() emit
287 if(!dictFin && _innerResult.isFinished()) {
290 QFutureIterator<QList<Translation*> > it(_innerResult);
292 while(it.hasNext()) {
293 QList<Translation* > list = it.next();
294 foreach(Translation* trans, list) {
297 if(!_searchBookmarks)
298 trans->setBookmark(_bookmarks.
299 inBookmarks(trans->key()));
300 _result.insert(trans->key().toLower(), trans);
305 if(!bookmarkFin && _innerBookmarks.isFinished()) {
308 QList<Translation*> list = _innerBookmarks.result();
310 foreach(Translation* trans, list)
311 _result.insert(trans->key().toLower(), trans);
314 if(!stopped && bookmarkFin && dictFin && changed) {
322 QStringList Backbone::getFilesFromDir(QString dir, QStringList nameFilter) {
323 QDir plug(QDir::toNativeSeparators(dir));
325 qDebug() << plug.absolutePath() << " folder doesn't exist";
326 Q_EMIT notify(Notify::Warning,
327 tr("%1 folder doesn't exist.").arg(plug.path()));
328 return QStringList();
330 plug.setFilter(QDir::Files);
331 QStringList list = plug.entryList(nameFilter);
333 for(int i = 0; i < list.size(); i++)
334 list[i] = plug.absoluteFilePath(list.at(i));
339 void Backbone::loadPlugins() {
342 QStringList nameFilter;
343 nameFilter << "*.so" << "*.so.*";
344 QStringList files = getFilesFromDir(_pluginPath, nameFilter);
346 foreach(QString file, files) {
347 QPluginLoader loader(file);
349 Q_EMIT notify(Notify::Error,
350 tr("%1 plugin cannot be loaded: %2.")
351 .arg(file).arg(loader.errorString()));
354 QObject *pl = loader.instance();
357 CommonDictInterface *plugin = qobject_cast<CommonDictInterface*>(pl);
358 foreach(CommonDictInterface* pl, _plugins)
359 if(pl->type() == plugin->type()) {
364 _plugins.append(plugin);
365 plugin->retranslate();
366 connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
367 this, SIGNAL(notify(Notify::NotifyType,QString)));
374 CommonDictInterface* Backbone::plugin(QString type) {
375 foreach(CommonDictInterface* plugin, _plugins)
376 if(plugin->type() == type)
383 void Backbone::loadPrefs(QString fileName) {
386 QFileInfo file(QDir::toNativeSeparators(fileName));
387 QDir confDir(file.dir());
388 if(!confDir.exists()){
389 qDebug() << "Configuration file doesn't exist ("
390 << file.filePath() << ")";
391 Q_EMIT notify(Notify::Warning,
392 tr("%1 configuration file doesn't exist.")
393 .arg(file.filePath()));
396 QSettings set(file.filePath(), QSettings::IniFormat);
397 _pluginPath = set.value("general/plugin_path", _pluginPath).toString();
398 _historyLen = set.value("general/history_size", 10).toInt();
399 _searchLimit = set.value("general/search_limit", 15).toInt();
400 _searchBookmarks = set.value("general/search_bookmarks",1).toBool();
401 _searchDicts = set.value("general/search_dictionaries",1).toBool();
402 _zoom = set.value("general/zoom", 1.0).toReal();
407 void Backbone::savePrefs(QSettings *set) {
410 set->setValue("general/plugin_path", _pluginPath);
411 set->setValue("general/history_size", _historyLen);
412 set->setValue("general/search_limit", _searchLimit);
413 set->setValue("general/search_bookmarks", _searchBookmarks);
414 set->setValue("general/search_dictionaries", _searchDicts);
415 set->setValue("general/zoom", _zoom);
420 void Backbone::loadDicts(QString fileName) {
424 QFileInfo file(QDir::toNativeSeparators(fileName));
425 QDir confDir(file.dir());
426 if(!confDir.exists()){
427 qDebug() << "Configuration file doesn't exist ("
428 << file.filePath() << ")";
429 Q_EMIT notify(Notify::Warning,
430 tr("%1 configuration file doesn't exist.")
431 .arg(file.filePath()));
435 QSettings set(file.filePath(), QSettings::IniFormat);
436 QStringList dicts = set.childGroups();
437 foreach(QString dict, dicts) {
438 if(!dict.contains("dictionary_"))
440 CommonDictInterface* plug = plugin
441 (set.value(dict + "/type", "").toString());
443 qDebug() << "Config file error: "
444 << set.value(dict + "/type", "").toString()
446 Q_EMIT notify(Notify::Warning,
447 tr("Configuration file error. %2 plugin doesn't exist.")
448 .arg(set.value(dict + "/type", "").toString()));
451 Settings* plugSet = new Settings();
452 set.beginGroup(dict);
453 QStringList items = set.childKeys();
454 foreach(QString item, items) {
455 plugSet->setValue(item, set.value(item, "").toString());
457 bool active = set.value("active",1).toBool();
460 addInternalDictionary(plug->getNew(plugSet), active);
467 void Backbone::dictUpdated() {
471 // For convienence this function is called for each change in dictionaries
472 // and each call dumps configuration for all dictionaries into file.
473 // Maybe a better way would be to store new/changed configuration but
474 // parsing settings file and figuring out what was changed, in my opinion,
475 // would take more time
476 _history->setMaxSize(_historyLen);
477 QFileInfo file(QDir::toNativeSeparators(_configPath));
478 QDir confDir(file.dir());
479 if(!confDir.exists())
480 confDir.mkpath(file.dir().path());
481 QSettings set(file.filePath(), QSettings::IniFormat);
486 foreach(CommonDictInterface* dict, _dicts.keys()){
487 if(!dict || !dict->settings())
489 saveState(&set, dict->settings(), _dicts[dict], dict->hash());
495 void Backbone::saveState(QSettings* set, Settings* plugSet, bool active
503 section.append(QString("dictionary_%1").arg(hash));
504 QList<QString> keys = plugSet->keys();
505 foreach(QString key, keys)
506 set->setValue(section + "/" + key, plugSet->value(key));
507 set->setValue(section + "/active", active);
512 QStringList Backbone::htmls() {
518 void Backbone::searchHtml(QList<Translation *> translations) {
521 QList<TranslationPtr> dummy;
523 foreach(Translation* tr, translations) {
524 if(containsDict(tr->dict()) || !tr->dict())
525 dummy.append(TranslationPtr(tr));
526 /* foreach(CommonDictInterface* dict, activeDicts()) {
527 Translation* trans = dict->getTranslationFor(tr->key());
529 dummy.append(TranslationPtr(trans));
532 if(translations.size()>0) {
533 Translation *tr = translations.at(0);
534 foreach(CommonDictInterface* dict, activeDicts()) {
535 Translation* trans = dict->getTranslationFor(tr->key());
537 dummy.append(TranslationPtr(trans));
541 _innerHtmlResult = QtConcurrent::mapped(dummy,
542 &TranslationPtr::toHtml);
543 _htmlResultWatcher.setFuture(_innerHtmlResult);
548 void Backbone::htmlTranslationReady() {
550 QFutureIterator<QString> it(_innerHtmlResult);
553 uniqe.insert(it.next());
555 _htmlResult = uniqe.toList();
563 QList<CommonDictInterface*> Backbone::activeDicts() {
564 QList<CommonDictInterface*>res;
565 foreach(CommonDictInterface* dict, _dicts.keys())
574 void Backbone::bookmarksListReady() {
575 _bookmarksResult = _innerBookmarks.result();
576 Q_EMIT bookmarksReady();
582 void Backbone::setSettings(Settings *settings) {
583 _historyLen = settings->value("history_size").toInt();
584 _searchLimit = settings->value("search_limit").toInt();
585 if(settings->value("search_dictionaries") == "true")
589 if(settings->value("search_bookmarks") == "true")
590 _searchBookmarks = 1;
592 _searchBookmarks = 0;
593 _zoom = settings->value("zoom").toFloat();
605 Settings* Backbone::settings() {
606 Settings * settings = new Settings();
607 settings->setValue("history_size", QString("%1").arg(_historyLen));
608 settings->setValue("search_limit", QString("%1").arg(_searchLimit));
609 settings->setValue("zoom", QString("%1").arg(_zoom));
611 settings->setValue("search_bookmarks", "true");
613 settings->setValue("search_bookmarks", "false");
616 settings->setValue("search_dictionaries", "true");
618 settings->setValue("search_dictionaries", "false");
623 bool Backbone::containsDict(uint hash) const {
624 QHashIterator<CommonDictInterface*, bool> it(_dicts);
628 if(it.next().key()->hash() == hash)