Separate translations for each plugin
[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 "../../common/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(":/icons/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                     _infoNote, 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                                     _infoNote,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     else {
329         delete plugin;
330         return new XdxfPlugin();
331     }
332 }
333
334
335 bool XdxfPlugin::isAvailable() const {
336     return true;
337 }
338
339
340 void XdxfPlugin::setHash(uint _hash) {
341     this->_hash=_hash;
342 }
343
344
345 uint XdxfPlugin::hash() const {
346    return _hash;
347 }
348
349
350 Settings* XdxfPlugin::settings() {
351 /*
352     Settings *returnSettings=new Settings;
353     QStringList list = _settings->keys();
354     foreach(QString key, list)
355             returnSettings->setValue(key,_settings->value(key));
356     return returnSettings;
357 */
358     return _settings;
359 }
360
361
362 bool XdxfPlugin::isCached() {
363     if(_settings->value("cached") == "true")
364         return true;
365     return false;
366 }
367
368
369 bool XdxfPlugin::setSettings(const Settings *settings) {
370     if(settings) {
371         bool isPathChange=false;
372         QString oldPath = _settings->value("path");
373         if(oldPath != settings->value("path")) {
374             if(oldPath!="" && _settings->value("cache_path")!="")
375                 clean();
376             isPathChange=true;
377         }
378
379         foreach(QString key, settings->keys()) {
380            if(key != "generateCache")
381                _settings->setValue(key, settings->value(key));
382         }
383
384         if(!getDictionaryInfo()) {
385             Q_EMIT notify(Notify::Warning,
386                 QString(tr("XDXF file is in wrong format")));
387             qDebug()<<"Error: xdxf file is in wrong format";
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     reader.readNextStartElement();
445     if(reader.name()=="description")
446         _infoNote=reader.readElementText();
447
448     QString format = "png";
449     QString initialPath = QDir::currentPath() + "/xdxf." + format;
450
451     _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-"
452                 + _langTo + "] ( xdxf )";
453     dictionaryFile.close();
454     if(okFormat)
455         return true;
456     return false;
457 }
458
459
460 QIcon* XdxfPlugin::icon() {
461     return &_icon;
462 }
463
464
465 int XdxfPlugin::countWords() {
466     if(_wordsCount>0)
467         return _wordsCount;
468     QFile dictionaryFile(_settings->value("path"));
469     if(!QFile::exists(_settings->value("path"))
470                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
471         Q_EMIT notify(Notify::Warning,
472                 QString(tr("XDXF file cannot be read for %1 dictionary")
473                 .arg(name())));
474         qDebug()<<"Error: could not open file";
475         return -1;
476     }
477
478     dictionaryFile.seek(0);
479
480     long wordsCount = 0;
481
482     QString line;
483     while(!dictionaryFile.atEnd()) {
484         line = dictionaryFile.readLine();
485         if(line.contains("<k>")) {
486             wordsCount++;
487         }
488     }
489     _wordsCount = wordsCount;
490     dictionaryFile.close();
491     return wordsCount;
492 }
493
494
495 bool XdxfPlugin::makeCache(QString) {
496     cachingDialog->setVisible(true);
497     QCoreApplication::processEvents();
498     QFileInfo dictFileN(_settings->value("path"));
499     QString cachePathN;
500     stopped = false;
501
502     /*create cache file name*/
503     int i=0;
504     do {
505         cachePathN = QDir::homePath() + "/.mdictionary/"
506                                       + dictFileN.completeBaseName()+"."
507                                       +QString::number(i) + ".cache";
508         i++;
509     } while(QFile::exists(cachePathN));
510
511     db_name = _settings->value("type") + cachePathN;
512     db = QSqlDatabase::addDatabase("QSQLITE",db_name);
513
514     qDebug()<<QSqlDatabase::connectionNames().size();
515     foreach(QString name,QSqlDatabase::connectionNames())
516         qDebug()<<name;
517     /*checke errors (File open and db open)*/
518     QFile dictionaryFile(dictFileN.filePath());
519     if (!QFile::exists(_settings->value("path"))
520                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
521         Q_EMIT updateCachingProgress(100, 0);
522         Q_EMIT notify(Notify::Warning,
523                 QString(tr("XDXF file cannot be read for %1 dictionary")
524                 .arg(name())));
525         return 0;
526     }
527     QXmlStreamReader reader(&dictionaryFile);
528     db.setDatabaseName(cachePathN);
529     if(!db.open()) {
530         qDebug() << "Database error" << db.lastError().text() << endl;
531         Q_EMIT updateCachingProgress(100, 0);
532         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
533                 "opened for %1 dictionary. Searching in XDXF file. "
534                 "You may want to recache.").arg(name())));
535         return false;
536     }
537
538     /*inicial sqlQuery*/
539     QCoreApplication::processEvents();
540     QSqlQuery cur(db);
541     cur.exec("PRAGMA synchronous = 0");
542     cur.exec("drop table dict");
543     QCoreApplication::processEvents();
544     cur.exec("create table dict(word text, normalized text ,translation text)");
545     int counter = 0;
546     cur.exec("BEGIN;");
547
548     QString readKey;
549     bool match = false;
550     QTime timer;
551     timer.start();
552     countWords();
553     int lastProg = -1;
554     _settings->setValue("strip_accents", "true");
555     counter=0;
556
557     /*add all words to db*/
558     while (!reader.atEnd() && !stopped) {
559         QCoreApplication::processEvents();
560         reader.readNext();
561         if(reader.tokenType() == QXmlStreamReader::StartElement) {
562             if(reader.name()=="k"){
563                 readKey = reader.readElementText();
564                 match = true;
565             }
566         }
567         if(match) {
568             QString temp("");
569             while(reader.name()!="ar" && !reader.atEnd()) {
570                 if(reader.name()!="" && reader.name()!="k") {
571                     if(reader.tokenType()==QXmlStreamReader::EndElement)
572                         temp+="</";
573                     if(reader.tokenType()==QXmlStreamReader::StartElement)
574                         temp+="<";
575                     temp+=reader.name().toString();
576                     if(reader.name().toString()=="c"
577                         && reader.tokenType()==QXmlStreamReader::StartElement) {
578                         temp= temp + " c=\""
579                                    + reader.attributes().value("c").toString()
580                                    + "\"";
581                     }
582                     temp+=">";
583                 }
584                 temp+= reader.text().toString().replace("<","&lt;").replace(">"
585                               ,"&gt;");
586                 reader.readNext();
587             }
588             if(temp.at(0)==QChar('\n'))
589                 temp.remove(0,1);
590             temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
591             match=false;
592             cur.prepare("insert into dict values(?,?,?)");
593             cur.addBindValue(readKey);
594             cur.addBindValue(removeAccents(readKey));
595             cur.addBindValue(temp);
596             cur.exec();
597             counter++;
598             int prog = counter*100/_wordsCount;
599             if(prog % 5 == 0 && lastProg != prog) {
600                 Q_EMIT updateCachingProgress(prog,timer.restart());
601                 lastProg = prog;
602             }
603         }
604     }
605     cur.exec("END;");
606     cur.exec("select count(*) from dict");
607     cachingDialog->setVisible(false);
608
609     /*checke errors (wrong number of added words)*/
610     countWords();
611     if(!cur.next() || countWords() != cur.value(0).toInt()) {
612         Q_EMIT updateCachingProgress(100, timer.restart());
613         Q_EMIT notify(Notify::Warning,
614                 QString(tr("Database caching error, please try again.")));
615         db.close();
616         return false;
617     }
618
619     _settings->setValue("cache_path", cachePathN);
620     _settings->setValue("cached", "true");
621
622     db.close();
623     return true;
624 }
625
626
627 void XdxfPlugin::clean() {
628     if(QFile::exists(_settings->value("cache_path"))) {
629         QFile(_settings->value("cache_path")).remove();
630         QSqlDatabase::removeDatabase(db_name);
631     }
632 }
633
634
635 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)