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