Fixed notification manager, to display properly notifications from pluins
[mdictionary] / src / plugins / xdxf / xdxfplugin.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
22 /*! \file xdxfplugin.cpp
23 \author Jakub Jaszczynski <j.j.jaszczynski@gmail.com>
24 */
25
26 #include "xdxfplugin.h"
27 #include <QDebug>
28 #include "../../include/Notify.h"
29
30 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
31                     _langFrom(""), _langTo(""),_name(""), _infoNote("") {
32     _settings = new Settings();
33     _dictDialog = new XdxfDictDialog(this, this);
34
35     connect(_dictDialog, SIGNAL(notify(Notify::NotifyType,QString)),
36             this, SIGNAL(notify(Notify::NotifyType,QString)));
37
38     cachingDialog = new XdxfCachingDialog(this);
39
40
41
42     _settings->setValue("type","xdxf");
43     _icon = QIcon("/usr/share/mdictionary/xdxf.png");
44     _wordsCount = -1;
45     stopped = false;
46
47     connect(cachingDialog, SIGNAL(cancelCaching()),
48             this, SLOT(stop()));
49     connect(this, SIGNAL(updateCachingProgress(int,int)),
50             cachingDialog, SLOT(updateCachingProgress(int,int)));
51     initAccents();
52 }
53
54 void XdxfPlugin::retranslate() {
55     QString locale = QLocale::system().name();
56
57     QTranslator *translator = new QTranslator(this);
58
59     if(locale == "pl_PL")
60         translator->load(":/translations/dict_xdxf_pl");
61     else
62         translator->load(":/translations/dict_xdxf_en");
63
64     QCoreApplication::installTranslator(translator);
65 }
66
67
68 XdxfPlugin::~XdxfPlugin() {
69     delete _settings;
70     delete cachingDialog;
71     delete _dictDialog;
72 }
73
74
75 QString XdxfPlugin::langFrom() const {   
76     return _langFrom;
77 }
78
79
80 QString XdxfPlugin::langTo() const {
81     return  _langTo;
82 }
83
84
85 QString XdxfPlugin::name() const {
86     return  _name;
87 }
88
89
90 QString XdxfPlugin::type() const {
91     return QString("xdxf");
92 }
93
94
95 QString XdxfPlugin::infoNote() const {
96     return  _infoNote;
97 }
98
99
100 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
101     if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
102         word.indexOf("_")==-1 && word.indexOf("%")==-1)
103         word+="*";
104
105     if(isCached())
106         return searchWordListCache(word,limit);
107     return searchWordListFile(word, limit);
108 }
109
110
111 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
112     int i=0;
113     QSet<Translation*> translations;
114     QString cacheFilePath = _settings->value("cache_path");
115
116     db.setDatabaseName(cacheFilePath);
117     if(!QFile::exists(cacheFilePath) || !db.open()) {
118         qDebug() << "Database error" << db.lastError().text() << endl;
119         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
120                 "opened for %1 dictionary. Searching in XDXF file. "
121                 "You may want to recache.").arg(name())));
122         _settings->setValue("cached","false");
123         return searchWordListFile(word, limit);
124     }
125     stopped = false;
126     word = word.toLower();
127     word = word.replace("*", "%");
128     word = word.replace("?", "_");
129
130     QSqlQuery cur(db);
131     if(limit !=0)
132         cur.prepare("select word from dict where word like ? or normalized "
133                     "like ? limit ?");
134     else
135         cur.prepare("select word from dict where word like ? or normalized "
136                     "like ?");
137     cur.addBindValue(word);
138     cur.addBindValue(word);
139     if(limit !=0)
140         cur.addBindValue(limit);
141     cur.exec();
142
143     bool in = false;
144     while(cur.next() && (i<limit || limit==0 ) ) {
145         in = true;
146         bool ok=true;
147         Translation *tran;
148         foreach(tran,translations) {
149             if(tran->key().toLower()==cur.value(0).toString().toLower())
150                     ok=false;
151         }
152         if(ok) {  /*add key word to list*/
153             translations.insert(new TranslationXdxf(
154                     cur.value(0).toString().toLower(),
155                     _infoNote, this));
156             i++;
157         }
158     }
159     db.close();
160     return translations.toList();
161 }
162
163
164 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
165     QSet<Translation*> translations;
166     QFile dictionaryFile(_settings->value("path"));
167     word = word.toLower();
168     stopped = false;
169
170     QRegExp regWord(word);
171     regWord.setCaseSensitivity(Qt::CaseInsensitive);
172     regWord.setPatternSyntax(QRegExp::Wildcard);
173
174     /*check xdxf file exist*/
175     if(!QFile::exists(_settings->value("path"))
176                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
177         qDebug()<<"Error: could not open file";
178         Q_EMIT notify(Notify::Warning,
179                 QString(tr("XDXF file cannot be read for %1").arg(name())));
180         return translations.toList();
181     }
182
183     QXmlStreamReader reader(&dictionaryFile);
184     QString readKey;
185     int i=0;
186
187     /*search words list*/
188     while(!reader.atEnd() && !stopped){
189         reader.readNextStartElement();
190         if(reader.name()=="ar") {
191             while(reader.name()!="k" && !reader.atEnd())
192                 reader.readNextStartElement();
193             if(!reader.atEnd())
194                 readKey = reader.readElementText();
195             if((regWord.exactMatch(readKey)
196                     || regWord.exactMatch(removeAccents(readKey)))
197                     && (i<limit || limit==0)) {
198                 bool ok=true;
199                 Translation *tran;
200                 foreach(tran,translations) {
201                     if(tran->key().toLower()==readKey.toLower())
202                         ok=false; /*if key is in the dictionary more that one */
203                 }
204                 if(ok) {  /*add key word to list*/
205                     translations<<(new TranslationXdxf(readKey.toLower(),
206                                     _infoNote,this));
207                     i++;
208                 }
209                 if(i>=limit && limit!=0)
210                     break;
211             }
212         }
213         this->thread()->yieldCurrentThread();
214     }
215     stopped=false;
216     dictionaryFile.close();
217     return translations.toList();
218 }
219
220
221 QString XdxfPlugin::search(QString key) {
222     if(isCached())
223         return searchCache(key);
224     return searchFile(key);
225 }
226
227
228 QString XdxfPlugin::searchCache(QString key) {
229     QString result("");
230     QString cacheFilePath = _settings->value("cache_path");
231     db.setDatabaseName(cacheFilePath);
232     key = key.toLower();
233
234     if(!QFile::exists(cacheFilePath) || !db.open()) {
235         qDebug() << "Database error" << db.lastError().text() << endl;
236         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
237                 "opened for %1 dictionary. Searching in XDXF file. "
238                 "You may want to recache.").arg(name())));
239         _settings->setValue("cached","false");
240         return searchFile(key);
241     }
242
243     QSqlQuery cur(db);
244
245     cur.prepare("select translation from dict where word like ?");
246     cur.addBindValue(key);
247     cur.exec();
248     while(cur.next())
249         result += cur.value(0).toString();
250
251     db.close();
252
253     return result;
254
255 }
256
257
258 QString XdxfPlugin::searchFile(QString key) {
259     QFile dictionaryFile(_settings->value("path"));
260     QString resultString("");
261     key = key.toLower();
262
263     /*check xdxf file exist*/
264     if(!QFile::exists(_settings->value("path"))
265                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
266         Q_EMIT notify(Notify::Warning,
267                 QString(tr("XDXF file cannot be read for %1").arg(name())));
268         qDebug()<<"Error: could not open file";
269         return "";
270     }
271
272     QXmlStreamReader reader(&dictionaryFile);
273     QString readKey;
274     bool match =false;
275     stopped = false;
276
277     /*search translations for word*/
278     while (!reader.atEnd()&& !stopped) {
279         reader.readNext();
280         if(reader.tokenType() == QXmlStreamReader::StartElement) {
281             if(reader.name()=="k") {
282                 readKey = reader.readElementText();
283                 if(readKey.toLower()==key.toLower())
284                     match = true;
285             }
286         }
287         if(match) {
288             QString temp("");
289             while(reader.name()!="ar" && !reader.atEnd()) {
290                 if(reader.name()!="" && reader.name()!="k") {
291                     if(reader.tokenType()==QXmlStreamReader::EndElement)
292                         temp+="</";
293                     if(reader.tokenType()==QXmlStreamReader::StartElement)
294                         temp+="<";
295                     temp+=reader.name().toString();
296                     if(reader.name().toString()=="c" &&
297                             reader.tokenType()==QXmlStreamReader::StartElement)
298                        temp= temp + " c=\"" + reader.attributes().
299                                value("c").toString() + "\"";
300                     temp+=">";
301                 }
302                 temp+= reader.text().toString().replace("<","&lt;").
303                         replace(">","&gt;");
304                 reader.readNext();
305             }
306             if(temp.at(0)==QChar('\n'))
307                 temp.remove(0,1);
308             resultString+="<key>" + readKey +"</key>";
309             resultString+="<t>" + temp + "</t>";
310             match=false;
311         }
312         this->thread()->yieldCurrentThread();
313     }
314     stopped=false;
315     dictionaryFile.close();
316     return resultString;
317 }
318
319
320 void XdxfPlugin::stop() {
321     stopped=true;
322 }
323
324
325 DictDialog* XdxfPlugin::dictDialog() {
326      return _dictDialog;
327 }
328
329
330 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
331     XdxfPlugin *plugin = new XdxfPlugin();
332     connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
333             this, SIGNAL(notify(Notify::NotifyType,QString)));
334     if(settings && plugin->setSettings(settings)) {
335         return plugin;
336     }
337     else {
338         delete plugin;
339         return 0;
340     }
341 }
342
343
344 bool XdxfPlugin::isAvailable() const {
345     return true;
346 }
347
348
349 void XdxfPlugin::setHash(uint _hash) {
350     this->_hash=_hash;
351 }
352
353
354 uint XdxfPlugin::hash() const {
355    return _hash;
356 }
357
358
359 Settings* XdxfPlugin::settings() {
360 /*
361     Settings *returnSettings=new Settings;
362     QStringList list = _settings->keys();
363     foreach(QString key, list)
364             returnSettings->setValue(key,_settings->value(key));
365     return returnSettings;
366 */
367     return _settings;
368 }
369
370
371 bool XdxfPlugin::isCached() {
372     if(_settings->value("cached") == "true")
373         return true;
374     return false;
375 }
376
377
378 bool XdxfPlugin::setSettings(const Settings *settings) {
379     if(settings) {
380         bool isPathChange=false;
381         QString oldPath = _settings->value("path");
382         Settings *oldSettings =  new Settings ;
383
384         if(oldPath != settings->value("path")) {
385             if(oldPath!="" && _settings->value("cache_path")!="")
386                 clean();
387             isPathChange=true;
388         }
389
390         foreach(QString key, _settings->keys())
391             oldSettings->setValue(key, _settings->value(key));
392
393         foreach(QString key, settings->keys()) {
394            if(key != "generateCache")
395                _settings->setValue(key, settings->value(key));
396         }
397
398         if(!getDictionaryInfo()) {
399             Q_EMIT notify(Notify::Warning,
400                 QString(tr("XDXF file is in wrong format")));
401             qDebug()<<"Error: xdxf file is in wrong format";
402             delete _settings;
403             _settings=oldSettings;
404             return false;
405         }
406
407         if(isPathChange) {
408             _wordsCount=0;
409             if(oldPath!="")
410                 _settings->setValue("cached","false");
411             if(_settings->value("cached")=="true"
412                     && _settings->value("cache_path")!="") {
413                 db_name = _settings->value("type")
414                         + _settings->value("cache_path");
415                 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
416             }
417         }
418
419         if((_settings->value("cached") == "false" ||
420             _settings->value("cached").isEmpty()) &&
421             settings->value("generateCache") == "true") {
422             clean();
423             makeCache("");
424         }
425
426         else if (settings->value("generateCache") == "false") {
427             _settings->setValue("cached", "false");
428         }
429     }
430     else
431         return false;
432     Q_EMIT settingsChanged();
433     return true;
434 }
435
436
437 bool XdxfPlugin::getDictionaryInfo() {
438     QFile dictionaryFile(_settings->value("path"));
439     if(!QFile::exists(_settings->value("path"))
440                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
441        Q_EMIT notify(Notify::Warning,
442                QString(tr("XDXF dictionary cannot be read from file")));
443         qDebug()<<"Error: could not open file";
444         return false;
445     }
446
447     bool okFormat=false;
448     QXmlStreamReader reader(&dictionaryFile);
449     reader.readNextStartElement();
450     if(reader.name()=="xdxf") {
451         okFormat=true;
452         if(reader.attributes().hasAttribute("lang_from"))
453             _langFrom = reader.attributes().value("lang_from").toString();
454         if(reader.attributes().hasAttribute("lang_to"))
455             _langTo = reader.attributes().value("lang_to").toString();
456     }
457     reader.readNextStartElement();
458     if(reader.name()=="full_name")
459         _name=reader.readElementText();
460     reader.readNextStartElement();
461     if(reader.name()=="description")
462         _infoNote=reader.readElementText();
463
464     QString initialPath = "/usr/share/mdictionary/xdxf.png";
465
466     _infoNote=" path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-"
467                 + _langTo + "]";
468     dictionaryFile.close();
469     if(okFormat)
470         return true;
471     return false;
472 }
473
474
475 QIcon* XdxfPlugin::icon() {
476     return &_icon;
477 }
478
479
480 int XdxfPlugin::countWords() {
481     if(_wordsCount>0)
482         return _wordsCount;
483     QFile dictionaryFile(_settings->value("path"));
484     if(!QFile::exists(_settings->value("path"))
485                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
486         Q_EMIT notify(Notify::Warning,
487                 QString(tr("XDXF file cannot be read for %1 dictionary")
488                 .arg(name())));
489         qDebug()<<"Error: could not open file";
490         return -1;
491     }
492
493     dictionaryFile.seek(0);
494
495     long wordsCount = 0;
496
497     QString line;
498     while(!dictionaryFile.atEnd()) {
499         line = dictionaryFile.readLine();
500         if(line.contains("<k>")) {
501             wordsCount++;
502         }
503     }
504     _wordsCount = wordsCount;
505     dictionaryFile.close();
506     return wordsCount;
507 }
508
509
510 bool XdxfPlugin::makeCache(QString) {
511     cachingDialog->setVisible(true);
512     QCoreApplication::processEvents();
513     QFileInfo dictFileN(_settings->value("path"));
514     QString cachePathN;
515     stopped = false;
516
517     /*create cache file name*/
518     int i=0;
519     do {
520         cachePathN = QDir::homePath() + "/.mdictionary/"
521                                       + dictFileN.completeBaseName()+"."
522                                       +QString::number(i) + ".cache";
523         i++;
524     } while(QFile::exists(cachePathN));
525
526     db_name = _settings->value("type") + cachePathN;
527     db = QSqlDatabase::addDatabase("QSQLITE",db_name);
528
529     /*checke errors (File open and db open)*/
530     QFile dictionaryFile(dictFileN.filePath());
531     if (!QFile::exists(_settings->value("path"))
532                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
533         Q_EMIT updateCachingProgress(100, 0);
534         Q_EMIT notify(Notify::Warning,
535                 QString(tr("XDXF file cannot be read for %1 dictionary")
536                 .arg(name())));
537         return 0;
538     }
539     QXmlStreamReader reader(&dictionaryFile);
540     db.setDatabaseName(cachePathN);
541     if(!db.open()) {
542         qDebug() << "Database error" << db.lastError().text() << endl;
543         Q_EMIT updateCachingProgress(100, 0);
544         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
545                 "opened for %1 dictionary. Searching in XDXF file. "
546                 "You may want to recache.").arg(name())));
547         return false;
548     }
549
550     /*inicial sqlQuery*/
551     QCoreApplication::processEvents();
552     QSqlQuery cur(db);
553     cur.exec("PRAGMA synchronous = 0");
554     cur.exec("drop table dict");
555     QCoreApplication::processEvents();
556     cur.exec("create table dict(word text, normalized text ,translation text)");
557     int counter = 0;
558     cur.exec("BEGIN;");
559
560     QString readKey;
561     bool match = false;
562     QTime timer;
563     timer.start();
564     countWords();
565     int lastProg = -1;
566     _settings->setValue("strip_accents", "true");
567     counter=0;
568
569     /*add all words to db*/
570     while (!reader.atEnd() && !stopped) {
571         QCoreApplication::processEvents();
572         reader.readNext();
573         if(reader.tokenType() == QXmlStreamReader::StartElement) {
574             if(reader.name()=="k"){
575                 readKey = reader.readElementText();
576                 match = true;
577             }
578         }
579         if(match) {
580             QString temp("");
581             while(reader.name()!="ar" && !reader.atEnd()) {
582                 if(reader.name()!="" && reader.name()!="k") {
583                     if(reader.tokenType()==QXmlStreamReader::EndElement)
584                         temp+="</";
585                     if(reader.tokenType()==QXmlStreamReader::StartElement)
586                         temp+="<";
587                     temp+=reader.name().toString();
588                     if(reader.name().toString()=="c"
589                         && reader.tokenType()==QXmlStreamReader::StartElement) {
590                         temp= temp + " c=\""
591                                    + reader.attributes().value("c").toString()
592                                    + "\"";
593                     }
594                     temp+=">";
595                 }
596                 temp+= reader.text().toString().replace("<","&lt;").replace(">"
597                               ,"&gt;");
598                 reader.readNext();
599             }
600             if(temp.at(0)==QChar('\n'))
601                 temp.remove(0,1);
602             temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
603             match=false;
604             cur.prepare("insert into dict values(?,?,?)");
605             cur.addBindValue(readKey);
606             cur.addBindValue(removeAccents(readKey));
607             cur.addBindValue(temp);
608             cur.exec();
609             counter++;
610             int prog = counter*100/_wordsCount;
611             if(prog % 5 == 0 && lastProg != prog) {
612                 Q_EMIT updateCachingProgress(prog,timer.restart());
613                 lastProg = prog;
614             }
615         }
616     }
617     cur.exec("END;");
618     cur.exec("select count(*) from dict");
619     cachingDialog->setVisible(false);
620
621     /*checke errors (wrong number of added words)*/
622     countWords();
623     if(!cur.next() || countWords() != cur.value(0).toInt()) {
624         Q_EMIT updateCachingProgress(100, timer.restart());
625         Q_EMIT notify(Notify::Warning,
626                 QString(tr("Database caching error, please try again.")));
627         db.close();
628         return false;
629     }
630
631     _settings->setValue("cache_path", cachePathN);
632     _settings->setValue("cached", "true");
633
634     db.close();
635     return true;
636 }
637
638
639 void XdxfPlugin::clean() {
640     if(QFile::exists(_settings->value("cache_path"))) {
641         QFile(_settings->value("cache_path")).remove();
642         QSqlDatabase::removeDatabase(db_name);
643     }
644 }
645
646
647 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)