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