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