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