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