Fixed some bugs
[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     _settings->setValue("type","xdxf");
42     _icon = QIcon("/usr/share/mdictionary/xdxf.png");
43     _wordsCount = -1;
44     stopped = false;
45
46     connect(cachingDialog, SIGNAL(cancelCaching()),
47             this, SLOT(stop()));
48     connect(this, SIGNAL(updateCachingProgress(int,int)),
49             cachingDialog, SLOT(updateCachingProgress(int,int)));
50     initAccents();
51 }
52
53 void XdxfPlugin::retranslate() {
54     QString locale = QLocale::system().name();
55
56     QTranslator *translator = new QTranslator(this);
57
58     if(!translator->load(":/xdxf/translations/" + locale)) {
59         translator->load(":/xdxf/translations/en_US");
60     }
61     QCoreApplication::installTranslator(translator);
62 }
63
64
65 XdxfPlugin::~XdxfPlugin() {
66     delete _settings;
67     delete cachingDialog;
68     delete _dictDialog;
69 }
70
71
72 QString XdxfPlugin::langFrom() const {   
73     return _langFrom;
74 }
75
76
77 QString XdxfPlugin::langTo() const {
78     return  _langTo;
79 }
80
81
82 QString XdxfPlugin::name() const {
83     return  _name;
84 }
85
86
87 QString XdxfPlugin::type() const {
88     return QString("xdxf");
89 }
90
91
92 QString XdxfPlugin::infoNote() const {
93     return _infoNote;
94 }
95
96
97 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
98     if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
99         word.indexOf("_")==-1 && word.indexOf("%")==-1)
100         word+="*";
101
102     if(isCached())
103         return searchWordListCache(word,limit);
104     return searchWordListFile(word, limit);
105 }
106
107
108 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
109     int i=0;
110     QSet<Translation*> translations;
111     QString cacheFilePath = _settings->value("cache_path");
112
113     db.setDatabaseName(cacheFilePath);
114     if(!QFile::exists(cacheFilePath) || !db.open()) {
115         qDebug() << "Database error" << db.lastError().text() << endl;
116         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
117                 "opened for %1 dictionary. Searching in XDXF file. "
118                 "You may want to recache.").arg(name())));
119         _settings->setValue("cached","false");
120         return searchWordListFile(word, limit);
121     }
122     stopped = false;
123     word = word.toLower();
124     word = word.replace("*", "%");
125     word = word.replace("?", "_");
126
127     QSqlQuery cur(db);
128     if(limit !=0)
129         cur.prepare("select word from dict where word like ? or normalized "
130                     "like ? limit ?");
131     else
132         cur.prepare("select word from dict where word like ? or normalized "
133                     "like ?");
134     cur.addBindValue(word);
135     cur.addBindValue(word);
136     if(limit !=0)
137         cur.addBindValue(limit);
138     cur.exec();
139
140     bool in = false;
141     while(cur.next() && (i<limit || limit==0 ) ) {
142         in = true;
143         bool ok=true;
144         Translation *tran;
145         foreach(tran,translations) {
146             if(tran->key().toLower()==cur.value(0).toString().toLower())
147                     ok=false;
148         }
149         if(ok) {  /*add key word to list*/
150             translations.insert(new TranslationXdxf(
151                     cur.value(0).toString().toLower(),
152                     _dictionaryInfo, this));
153             i++;
154         }
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)) {
195                 bool ok=true;
196                 Translation *tran;
197                 foreach(tran,translations) {
198                     if(tran->key().toLower()==readKey.toLower())
199                         ok=false; /*if key is in the dictionary more that one */
200                 }
201                 if(ok) {  /*add key word to list*/
202                     translations<<(new TranslationXdxf(readKey.toLower(),
203                                     _dictionaryInfo,this));
204                     i++;
205                 }
206                 if(i>=limit && limit!=0)
207                     break;
208             }
209         }
210         this->thread()->yieldCurrentThread();
211     }
212     stopped=false;
213     dictionaryFile.close();
214     return translations.toList();
215 }
216
217
218 QString XdxfPlugin::search(QString key) {
219     if(isCached())
220         return searchCache(key);
221     return searchFile(key);
222 }
223
224
225 QString XdxfPlugin::searchCache(QString key) {
226     QString result("");
227     QString cacheFilePath = _settings->value("cache_path");
228     db.setDatabaseName(cacheFilePath);
229     key = key.toLower();
230
231     if(!QFile::exists(cacheFilePath) || !db.open()) {
232         qDebug() << "Database error" << db.lastError().text() << endl;
233         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
234                 "opened for %1 dictionary. Searching in XDXF file. "
235                 "You may want to recache.").arg(name())));
236         _settings->setValue("cached","false");
237         return searchFile(key);
238     }
239
240     QSqlQuery cur(db);
241
242     cur.prepare("select translation from dict where word like ?");
243     cur.addBindValue(key);
244     cur.exec();
245     while(cur.next())
246         result += cur.value(0).toString();
247
248     db.close();
249
250     return result;
251
252 }
253
254
255 QString XdxfPlugin::searchFile(QString key) {
256     QFile dictionaryFile(_settings->value("path"));
257     QString resultString("");
258     key = key.toLower();
259
260     /*check xdxf file exist*/
261     if(!QFile::exists(_settings->value("path"))
262                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
263         Q_EMIT notify(Notify::Warning,
264                 QString(tr("XDXF file cannot be read for %1").arg(name())));
265         qDebug()<<"Error: could not open file";
266         return "";
267     }
268
269     QXmlStreamReader reader(&dictionaryFile);
270     QString readKey;
271     bool match =false;
272     stopped = false;
273
274     /*search translations for word*/
275     while (!reader.atEnd()&& !stopped) {
276         reader.readNext();
277         if(reader.tokenType() == QXmlStreamReader::StartElement) {
278             if(reader.name()=="k") {
279                 readKey = reader.readElementText();
280                 if(readKey.toLower()==key.toLower())
281                     match = true;
282             }
283         }
284         if(match) {
285             QString temp("");
286             while(reader.name()!="ar" && !reader.atEnd()) {
287                 if(reader.name()!="" && reader.name()!="k") {
288                     if(reader.tokenType()==QXmlStreamReader::EndElement)
289                         temp+="</";
290                     if(reader.tokenType()==QXmlStreamReader::StartElement)
291                         temp+="<";
292                     temp+=reader.name().toString();
293                     if(reader.name().toString()=="c" &&
294                             reader.tokenType()==QXmlStreamReader::StartElement)
295                        temp= temp + " c=\"" + reader.attributes().
296                                value("c").toString() + "\"";
297                     temp+=">";
298                 }
299                 temp+= reader.text().toString().replace("<","&lt;").
300                         replace(">","&gt;");
301                 reader.readNext();
302             }
303             if(temp.at(0)==QChar('\n'))
304                 temp.remove(0,1);
305             resultString+="<key>" + readKey +"</key>";
306             resultString+="<t>" + temp + "</t>";
307             match=false;
308         }
309         this->thread()->yieldCurrentThread();
310     }
311     stopped=false;
312     dictionaryFile.close();
313     return resultString;
314 }
315
316
317 void XdxfPlugin::stop() {
318     stopped=true;
319 }
320
321
322 DictDialog* XdxfPlugin::dictDialog() {
323      return _dictDialog;
324 }
325
326
327 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
328     XdxfPlugin *plugin = new XdxfPlugin();
329
330     if(settings && plugin->setSettings(settings)) {
331         return plugin;
332     }
333     else {
334         delete plugin;
335         return 0;
336     }
337 }
338
339
340 bool XdxfPlugin::isAvailable() const {
341     return true;
342 }
343
344
345 Settings* XdxfPlugin::settings() {
346     return _settings;
347 }
348
349
350 bool XdxfPlugin::isCached() {
351     if(_settings->value("cached") == "true")
352         return true;
353     return false;
354 }
355
356
357 bool XdxfPlugin::setSettings(const Settings *settings) {
358     if(settings) {
359         bool isPathChange=false;
360         QString oldPath = _settings->value("path");
361         Settings *oldSettings =  new Settings ;
362
363         if(oldPath != settings->value("path")) {
364             if(oldPath!="" && _settings->value("cache_path")!="")
365                 clean();
366             isPathChange=true;
367         }
368
369         foreach(QString key, _settings->keys())
370             oldSettings->setValue(key, _settings->value(key));
371
372         foreach(QString key, settings->keys()) {
373            if(key != "generateCache")
374                _settings->setValue(key, settings->value(key));
375         }
376
377         if(!getDictionaryInfo()) {
378             Q_EMIT notify(Notify::Warning,
379                 QString(tr("XDXF file is in wrong format")));
380             qDebug()<<"Error: xdxf file is in wrong format";
381             delete _settings;
382             _settings=oldSettings;
383             return false;
384         }
385
386         if(isPathChange) {
387             _wordsCount=0;
388             if(oldPath!="")
389                 _settings->setValue("cached","false");
390             if(_settings->value("cached")=="true"
391                     && _settings->value("cache_path")!="") {
392                 db_name = _settings->value("type")
393                         + _settings->value("cache_path");
394                 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
395             }
396         }
397
398         if((_settings->value("cached") == "false" ||
399             _settings->value("cached").isEmpty()) &&
400             settings->value("generateCache") == "true") {
401             clean();
402             makeCache("");
403         }
404
405         else if (settings->value("generateCache") == "false") {
406             _settings->setValue("cached", "false");
407         }
408     }
409     else
410         return false;
411     Q_EMIT settingsChanged();
412     return true;
413 }
414
415
416 bool XdxfPlugin::getDictionaryInfo() {
417     QFile dictionaryFile(_settings->value("path"));
418     if(!QFile::exists(_settings->value("path"))
419                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
420        Q_EMIT notify(Notify::Warning,
421                QString(tr("XDXF dictionary cannot be read from file")));
422         qDebug()<<"Error: could not open file";
423         return false;
424     }
425
426     bool okFormat=false;
427     QXmlStreamReader reader(&dictionaryFile);
428     reader.readNextStartElement();
429     if(reader.name()=="xdxf") {
430         okFormat=true;
431         if(reader.attributes().hasAttribute("lang_from"))
432             _langFrom = reader.attributes().value("lang_from").toString();
433         if(reader.attributes().hasAttribute("lang_to"))
434             _langTo = reader.attributes().value("lang_to").toString();
435     }
436     reader.readNextStartElement();
437     if(reader.name()=="full_name")
438         _name=reader.readElementText();
439     reader.readNextStartElement();
440     if(reader.name()=="description")
441         _infoNote=reader.readElementText();
442
443     _dictionaryInfo= _name + " [" + _langFrom + "-"
444                 + _langTo + "]";
445
446     dictionaryFile.close();
447     if(okFormat)
448         return true;
449     return false;
450 }
451
452
453 QIcon* XdxfPlugin::icon() {
454     return &_icon;
455 }
456
457
458 int XdxfPlugin::countWords() {
459     if(_wordsCount>0)
460         return _wordsCount;
461     QFile dictionaryFile(_settings->value("path"));
462     if(!QFile::exists(_settings->value("path"))
463                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
464         Q_EMIT notify(Notify::Warning,
465                 QString(tr("XDXF file cannot be read for %1 dictionary")
466                 .arg(name())));
467         qDebug()<<"Error: could not open file";
468         return -1;
469     }
470
471     dictionaryFile.seek(0);
472
473     long wordsCount = 0;
474
475     QString line;
476     while(!dictionaryFile.atEnd()) {
477         line = dictionaryFile.readLine();
478         if(line.contains("<k>")) {
479             wordsCount++;
480         }
481     }
482     _wordsCount = wordsCount;
483     dictionaryFile.close();
484     return wordsCount;
485 }
486
487
488 bool XdxfPlugin::makeCache(QString) {
489     #ifdef Q_WS_MAEMO_5
490         cachingDialog->setVisible(true);
491     #else
492         cachingDialog->show();
493     #endif
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         QCoreApplication::processEvents();
554         reader.readNext();
555         if(reader.tokenType() == QXmlStreamReader::StartElement) {
556             if(reader.name()=="k"){
557                 readKey = reader.readElementText();
558                 match = true;
559             }
560         }
561         if(match) {
562             QString temp("");
563             while(reader.name()!="ar" && !reader.atEnd()) {
564                 if(reader.name()!="" && reader.name()!="k") {
565                     if(reader.tokenType()==QXmlStreamReader::EndElement)
566                         temp+="</";
567                     if(reader.tokenType()==QXmlStreamReader::StartElement)
568                         temp+="<";
569                     temp+=reader.name().toString();
570                     if(reader.name().toString()=="c"
571                         && reader.tokenType()==QXmlStreamReader::StartElement) {
572                         temp= temp + " c=\""
573                                    + reader.attributes().value("c").toString()
574                                    + "\"";
575                     }
576                     temp+=">";
577                 }
578                 temp+= reader.text().toString().replace("<","&lt;").replace(">"
579                               ,"&gt;");
580                 reader.readNext();
581             }
582             if(temp.at(0)==QChar('\n'))
583                 temp.remove(0,1);
584             temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
585             match=false;
586             cur.prepare("insert into dict values(?,?,?)");
587             cur.addBindValue(readKey);
588             cur.addBindValue(removeAccents(readKey));
589             cur.addBindValue(temp);
590             cur.exec();
591             counter++;
592             int prog = counter*100/_wordsCount;
593             if(prog % 5 == 0 && lastProg != prog) {
594                 Q_EMIT updateCachingProgress(prog,timer.restart());
595                 lastProg = prog;
596             }
597         }
598     }
599     cur.exec("END;");
600     cur.exec("select count(*) from dict");
601     //cachingDialog->hide();
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         return false;
611     }
612
613     _settings->setValue("cache_path", cachePathN);
614     _settings->setValue("cached", "true");
615
616     db.close();
617     return true;
618 }
619
620
621 void XdxfPlugin::clean() {
622     if(QFile::exists(_settings->value("cache_path"))) {
623         QFile(_settings->value("cache_path")).remove();
624         QSqlDatabase::removeDatabase(db_name);
625     }
626 }
627
628
629 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)