8751e42f35e85fe05b2c382fb819dc2cf2eba3ca
[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     cachingDialog->setVisible(true);
490     QCoreApplication::processEvents();
491     QFileInfo dictFileN(_settings->value("path"));
492     QString cachePathN;
493     stopped = false;
494
495     /*create cache file name*/
496     int i=0;
497     do {
498         cachePathN = QDir::homePath() + "/.mdictionary/"
499                                       + dictFileN.completeBaseName()+"."
500                                       +QString::number(i) + ".cache";
501         i++;
502     } while(QFile::exists(cachePathN));
503
504     db_name = _settings->value("type") + cachePathN;
505     db = QSqlDatabase::addDatabase("QSQLITE",db_name);
506
507     /*checke errors (File open and db open)*/
508     QFile dictionaryFile(dictFileN.filePath());
509     if (!QFile::exists(_settings->value("path"))
510                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
511         Q_EMIT updateCachingProgress(100, 0);
512         Q_EMIT notify(Notify::Warning,
513                 QString(tr("XDXF file cannot be read for %1 dictionary")
514                 .arg(name())));
515         return 0;
516     }
517     QXmlStreamReader reader(&dictionaryFile);
518     db.setDatabaseName(cachePathN);
519     if(!db.open()) {
520         qDebug() << "Database error" << db.lastError().text() << endl;
521         Q_EMIT updateCachingProgress(100, 0);
522         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
523                 "opened for %1 dictionary. Searching in XDXF file. "
524                 "You may want to recache.").arg(name())));
525         return false;
526     }
527
528     /*inicial sqlQuery*/
529     QCoreApplication::processEvents();
530     QSqlQuery cur(db);
531     cur.exec("PRAGMA synchronous = 0");
532     cur.exec("drop table dict");
533     QCoreApplication::processEvents();
534     cur.exec("create table dict(word text, normalized text ,translation text)");
535     int counter = 0;
536     cur.exec("BEGIN;");
537
538     QString readKey;
539     bool match = false;
540     QTime timer;
541     timer.start();
542     countWords();
543     int lastProg = -1;
544     _settings->setValue("strip_accents", "true");
545     counter=0;
546
547     /*add all words to db*/
548     while (!reader.atEnd() && !stopped) {
549         QCoreApplication::processEvents();
550         reader.readNext();
551         if(reader.tokenType() == QXmlStreamReader::StartElement) {
552             if(reader.name()=="k"){
553                 readKey = reader.readElementText();
554                 match = true;
555             }
556         }
557         if(match) {
558             QString temp("");
559             while(reader.name()!="ar" && !reader.atEnd()) {
560                 if(reader.name()!="" && reader.name()!="k") {
561                     if(reader.tokenType()==QXmlStreamReader::EndElement)
562                         temp+="</";
563                     if(reader.tokenType()==QXmlStreamReader::StartElement)
564                         temp+="<";
565                     temp+=reader.name().toString();
566                     if(reader.name().toString()=="c"
567                         && reader.tokenType()==QXmlStreamReader::StartElement) {
568                         temp= temp + " c=\""
569                                    + reader.attributes().value("c").toString()
570                                    + "\"";
571                     }
572                     temp+=">";
573                 }
574                 temp+= reader.text().toString().replace("<","&lt;").replace(">"
575                               ,"&gt;");
576                 reader.readNext();
577             }
578             if(temp.at(0)==QChar('\n'))
579                 temp.remove(0,1);
580             temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
581             match=false;
582             cur.prepare("insert into dict values(?,?,?)");
583             cur.addBindValue(readKey);
584             cur.addBindValue(removeAccents(readKey));
585             cur.addBindValue(temp);
586             cur.exec();
587             counter++;
588             int prog = counter*100/_wordsCount;
589             if(prog % 5 == 0 && lastProg != prog) {
590                 Q_EMIT updateCachingProgress(prog,timer.restart());
591                 lastProg = prog;
592             }
593         }
594     }
595     cur.exec("END;");
596     cur.exec("select count(*) from dict");
597     cachingDialog->setVisible(false);
598
599     /*checke errors (wrong number of added words)*/
600     countWords();
601     if(!cur.next() || countWords() != cur.value(0).toInt()) {
602         Q_EMIT updateCachingProgress(100, timer.restart());
603         Q_EMIT notify(Notify::Warning,
604                 QString(tr("Database caching error, please try again.")));
605         db.close();
606         return false;
607     }
608
609     _settings->setValue("cache_path", cachePathN);
610     _settings->setValue("cached", "true");
611
612     db.close();
613     return true;
614 }
615
616
617 void XdxfPlugin::clean() {
618     if(QFile::exists(_settings->value("cache_path"))) {
619         QFile(_settings->value("cache_path")).remove();
620         QSqlDatabase::removeDatabase(db_name);
621     }
622 }
623
624
625 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)