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