Next fix of xdxf caching dialog
[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     if(settings && plugin->setSettings(settings)) {
324         return plugin;
325     }
326     else {
327         delete plugin;
328         return 0;
329     }
330 }
331
332
333 bool XdxfPlugin::isAvailable() const {
334     return true;
335 }
336
337
338 Settings* XdxfPlugin::settings() {
339     return _settings;
340 }
341
342
343 bool XdxfPlugin::isCached() {
344     if(_settings->value("cached") == "true")
345         return true;
346     return false;
347 }
348
349
350 bool XdxfPlugin::setSettings(const Settings *settings) {
351     if(settings) {
352         bool isPathChange=false;
353         QString oldPath = _settings->value("path");
354         Settings *oldSettings =  new Settings ;
355
356         if(oldPath != settings->value("path")) {
357             if(oldPath!="" && _settings->value("cache_path")!="")
358                 clean();
359             isPathChange=true;
360         }
361
362         foreach(QString key, _settings->keys())
363             oldSettings->setValue(key, _settings->value(key));
364
365         foreach(QString key, settings->keys()) {
366            if(key != "generateCache")
367                _settings->setValue(key, settings->value(key));
368         }
369
370         if(!getDictionaryInfo()) {
371             Q_EMIT notify(Notify::Warning,
372                 QString(tr("XDXF file is in wrong format")));
373             qDebug()<<"Error: xdxf file is in wrong format";
374             delete _settings;
375             _settings=oldSettings;
376             return false;
377         }
378
379         if(isPathChange) {
380             _wordsCount=0;
381             if(oldPath!="")
382                 _settings->setValue("cached","false");
383             if(_settings->value("cached")=="true"
384                     && _settings->value("cache_path")!="") {
385                 db_name = _settings->value("type")
386                         + _settings->value("cache_path");
387                 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
388             }
389         }
390
391         if((_settings->value("cached") == "false" ||
392             _settings->value("cached").isEmpty()) &&
393             settings->value("generateCache") == "true") {
394             clean();
395             makeCache("");
396         }
397
398         else if (settings->value("generateCache") == "false") {
399             _settings->setValue("cached", "false");
400         }
401     }
402     else
403         return false;
404     Q_EMIT settingsChanged();
405     return true;
406 }
407
408
409 bool XdxfPlugin::getDictionaryInfo() {
410     QFile dictionaryFile(_settings->value("path"));
411     if(!QFile::exists(_settings->value("path"))
412                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
413        Q_EMIT notify(Notify::Warning,
414                QString(tr("XDXF dictionary cannot be read from file")));
415         qDebug()<<"Error: could not open file";
416         return false;
417     }
418
419     bool okFormat=false;
420     QXmlStreamReader reader(&dictionaryFile);
421     reader.readNextStartElement();
422     if(reader.name()=="xdxf") {
423         okFormat=true;
424         if(reader.attributes().hasAttribute("lang_from"))
425             _langFrom = reader.attributes().value("lang_from").toString();
426         if(reader.attributes().hasAttribute("lang_to"))
427             _langTo = reader.attributes().value("lang_to").toString();
428     }
429     reader.readNextStartElement();
430     if(reader.name()=="full_name")
431         _name=reader.readElementText();
432     reader.readNextStartElement();
433     if(reader.name()=="description")
434         _infoNote=reader.readElementText();
435
436     _dictionaryInfo= _name + " [" + _langFrom + "-"
437                 + _langTo + "]";
438
439     dictionaryFile.close();
440     if(okFormat)
441         return true;
442     return false;
443 }
444
445
446 QIcon* XdxfPlugin::icon() {
447     return &_icon;
448 }
449
450
451 int XdxfPlugin::countWords() {
452     if(_wordsCount>0)
453         return _wordsCount;
454     QFile dictionaryFile(_settings->value("path"));
455     if(!QFile::exists(_settings->value("path"))
456                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
457         Q_EMIT notify(Notify::Warning,
458                 QString(tr("XDXF file cannot be read for %1 dictionary")
459                 .arg(name())));
460         qDebug()<<"Error: could not open file";
461         return -1;
462     }
463
464     dictionaryFile.seek(0);
465
466     long wordsCount = 0;
467
468     QString line;
469     while(!dictionaryFile.atEnd()) {
470         line = dictionaryFile.readLine();
471         if(line.contains("<k>")) {
472             wordsCount++;
473         }
474     }
475     _wordsCount = wordsCount;
476     dictionaryFile.close();
477     return wordsCount;
478 }
479
480
481 bool XdxfPlugin::makeCache(QString) {
482
483     XdxfCachingDialog d(_dictDialog->lastDialogParent());
484
485     connect(&d, SIGNAL(cancelCaching()),
486             this, SLOT(stop()));
487
488     connect(this, SIGNAL(updateCachingProgress(int,int)),
489             &d, SLOT(updateCachingProgress(int,int)));
490
491     d.show();
492
493     QCoreApplication::processEvents();
494     QFileInfo dictFileN(_settings->value("path"));
495     QString cachePathN;
496     stopped = false;
497
498     /*create cache file name*/
499     int i=0;
500     do {
501         cachePathN = QDir::homePath() + "/.mdictionary/"
502                                       + dictFileN.completeBaseName()+"."
503                                       +QString::number(i) + ".cache";
504         i++;
505     } while(QFile::exists(cachePathN));
506
507     db_name = _settings->value("type") + cachePathN;
508     db = QSqlDatabase::addDatabase("QSQLITE",db_name);
509
510     /*checke errors (File open and db open)*/
511     QFile dictionaryFile(dictFileN.filePath());
512     if (!QFile::exists(_settings->value("path"))
513                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
514         Q_EMIT updateCachingProgress(100, 0);
515         Q_EMIT notify(Notify::Warning,
516                 QString(tr("XDXF file cannot be read for %1 dictionary")
517                 .arg(name())));
518         return 0;
519     }
520     QXmlStreamReader reader(&dictionaryFile);
521     db.setDatabaseName(cachePathN);
522     if(!db.open()) {
523         qDebug() << "Database error" << db.lastError().text() << endl;
524         Q_EMIT updateCachingProgress(100, 0);
525         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
526                 "opened for %1 dictionary. Searching in XDXF file. "
527                 "You may want to recache.").arg(name())));
528         return false;
529     }
530
531     /*inicial sqlQuery*/
532     QCoreApplication::processEvents();
533     QSqlQuery cur(db);
534     cur.exec("PRAGMA synchronous = 0");
535     cur.exec("drop table dict");
536     QCoreApplication::processEvents();
537     cur.exec("create table dict(word text, normalized text ,translation text)");
538     int counter = 0;
539     cur.exec("BEGIN;");
540
541     QString readKey;
542     bool match = false;
543     QTime timer;
544     timer.start();
545     countWords();
546     int lastProg = -1;
547     _settings->setValue("strip_accents", "true");
548     counter=0;
549
550     /*add all words to db*/
551     while (!reader.atEnd() && !stopped) {
552
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 % 2 == 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
602     /*checke errors (wrong number of added words)*/
603     countWords();
604     if(!cur.next() || countWords() != cur.value(0).toInt()) {
605         Q_EMIT updateCachingProgress(100, timer.restart());
606         Q_EMIT notify(Notify::Warning,
607                 QString(tr("Database caching error, please try again.")));
608         db.close();
609         return false;
610     }
611
612     _settings->setValue("cache_path", cachePathN);
613     _settings->setValue("cached", "true");
614
615
616     disconnect(&d, SIGNAL(cancelCaching()),
617             this, SLOT(stop()));
618
619     disconnect(this, SIGNAL(updateCachingProgress(int,int)),
620             &d, SLOT(updateCachingProgress(int,int)));
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)