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