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