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