Merge branch 'google'
[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     }
329     else {
330         delete plugin;
331         return 0;
332     }
333 }
334
335
336 bool XdxfPlugin::isAvailable() const {
337     return true;
338 }
339
340
341 void XdxfPlugin::setHash(uint _hash) {
342     this->_hash=_hash;
343 }
344
345
346 uint XdxfPlugin::hash() const {
347    return _hash;
348 }
349
350
351 Settings* XdxfPlugin::settings() {
352 /*
353     Settings *returnSettings=new Settings;
354     QStringList list = _settings->keys();
355     foreach(QString key, list)
356             returnSettings->setValue(key,_settings->value(key));
357     return returnSettings;
358 */
359     return _settings;
360 }
361
362
363 bool XdxfPlugin::isCached() {
364     if(_settings->value("cached") == "true")
365         return true;
366     return false;
367 }
368
369
370 bool XdxfPlugin::setSettings(const Settings *settings) {
371     if(settings) {
372         bool isPathChange=false;
373         QString oldPath = _settings->value("path");
374         Settings *oldSettings =  new Settings ;
375
376         if(oldPath != settings->value("path")) {
377             if(oldPath!="" && _settings->value("cache_path")!="")
378                 clean();
379             isPathChange=true;
380         }
381
382         foreach(QString key, _settings->keys())
383             oldSettings->setValue(key, _settings->value(key));
384
385         foreach(QString key, settings->keys()) {
386            if(key != "generateCache")
387                _settings->setValue(key, settings->value(key));
388         }
389
390         if(!getDictionaryInfo()) {
391             Q_EMIT notify(Notify::Warning,
392                 QString(tr("XDXF file is in wrong format")));
393             qDebug()<<"Error: xdxf file is in wrong format";
394             delete _settings;
395             _settings=oldSettings;
396             return false;
397         }
398
399         if(isPathChange) {
400             _wordsCount=0;
401             if(oldPath!="")
402                 _settings->setValue("cached","false");
403             if(_settings->value("cached")=="true"
404                     && _settings->value("cache_path")!="") {
405                 db_name = _settings->value("type")
406                         + _settings->value("cache_path");
407                 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
408             }
409         }
410
411         if((_settings->value("cached") == "false" ||
412             _settings->value("cached").isEmpty()) &&
413             settings->value("generateCache") == "true") {
414             clean();
415             makeCache("");
416         }
417
418         else if (settings->value("generateCache") == "false") {
419             _settings->setValue("cached", "false");
420         }
421     }
422     else
423         return false;
424     Q_EMIT settingsChanged();
425     return true;
426 }
427
428
429 bool XdxfPlugin::getDictionaryInfo() {
430     QFile dictionaryFile(_settings->value("path"));
431     if(!QFile::exists(_settings->value("path"))
432                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
433        Q_EMIT notify(Notify::Warning,
434                QString(tr("XDXF dictionary cannot be read from file")));
435         qDebug()<<"Error: could not open file";
436         return false;
437     }
438
439     bool okFormat=false;
440     QXmlStreamReader reader(&dictionaryFile);
441     reader.readNextStartElement();
442     if(reader.name()=="xdxf") {
443         okFormat=true;
444         if(reader.attributes().hasAttribute("lang_from"))
445             _langFrom = reader.attributes().value("lang_from").toString();
446         if(reader.attributes().hasAttribute("lang_to"))
447             _langTo = reader.attributes().value("lang_to").toString();
448     }
449     reader.readNextStartElement();
450     if(reader.name()=="full_name")
451         _name=reader.readElementText();
452     reader.readNextStartElement();
453     if(reader.name()=="description")
454         _infoNote=reader.readElementText();
455
456     QString initialPath = "/usr/share/mdictionary/xdxf.png";
457
458     _infoNote=" path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-"
459                 + _langTo + "]";
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     /*checke errors (File open and db open)*/
522     QFile dictionaryFile(dictFileN.filePath());
523     if (!QFile::exists(_settings->value("path"))
524                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
525         Q_EMIT updateCachingProgress(100, 0);
526         Q_EMIT notify(Notify::Warning,
527                 QString(tr("XDXF file cannot be read for %1 dictionary")
528                 .arg(name())));
529         return 0;
530     }
531     QXmlStreamReader reader(&dictionaryFile);
532     db.setDatabaseName(cachePathN);
533     if(!db.open()) {
534         qDebug() << "Database error" << db.lastError().text() << endl;
535         Q_EMIT updateCachingProgress(100, 0);
536         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
537                 "opened for %1 dictionary. Searching in XDXF file. "
538                 "You may want to recache.").arg(name())));
539         return false;
540     }
541
542     /*inicial sqlQuery*/
543     QCoreApplication::processEvents();
544     QSqlQuery cur(db);
545     cur.exec("PRAGMA synchronous = 0");
546     cur.exec("drop table dict");
547     QCoreApplication::processEvents();
548     cur.exec("create table dict(word text, normalized text ,translation text)");
549     int counter = 0;
550     cur.exec("BEGIN;");
551
552     QString readKey;
553     bool match = false;
554     QTime timer;
555     timer.start();
556     countWords();
557     int lastProg = -1;
558     _settings->setValue("strip_accents", "true");
559     counter=0;
560
561     /*add all words to db*/
562     while (!reader.atEnd() && !stopped) {
563         QCoreApplication::processEvents();
564         reader.readNext();
565         if(reader.tokenType() == QXmlStreamReader::StartElement) {
566             if(reader.name()=="k"){
567                 readKey = reader.readElementText();
568                 match = true;
569             }
570         }
571         if(match) {
572             QString temp("");
573             while(reader.name()!="ar" && !reader.atEnd()) {
574                 if(reader.name()!="" && reader.name()!="k") {
575                     if(reader.tokenType()==QXmlStreamReader::EndElement)
576                         temp+="</";
577                     if(reader.tokenType()==QXmlStreamReader::StartElement)
578                         temp+="<";
579                     temp+=reader.name().toString();
580                     if(reader.name().toString()=="c"
581                         && reader.tokenType()==QXmlStreamReader::StartElement) {
582                         temp= temp + " c=\""
583                                    + reader.attributes().value("c").toString()
584                                    + "\"";
585                     }
586                     temp+=">";
587                 }
588                 temp+= reader.text().toString().replace("<","&lt;").replace(">"
589                               ,"&gt;");
590                 reader.readNext();
591             }
592             if(temp.at(0)==QChar('\n'))
593                 temp.remove(0,1);
594             temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
595             match=false;
596             cur.prepare("insert into dict values(?,?,?)");
597             cur.addBindValue(readKey);
598             cur.addBindValue(removeAccents(readKey));
599             cur.addBindValue(temp);
600             cur.exec();
601             counter++;
602             int prog = counter*100/_wordsCount;
603             if(prog % 5 == 0 && lastProg != prog) {
604                 Q_EMIT updateCachingProgress(prog,timer.restart());
605                 lastProg = prog;
606             }
607         }
608     }
609     cur.exec("END;");
610     cur.exec("select count(*) from dict");
611     cachingDialog->setVisible(false);
612
613     /*checke errors (wrong number of added words)*/
614     countWords();
615     if(!cur.next() || countWords() != cur.value(0).toInt()) {
616         Q_EMIT updateCachingProgress(100, timer.restart());
617         Q_EMIT notify(Notify::Warning,
618                 QString(tr("Database caching error, please try again.")));
619         db.close();
620         return false;
621     }
622
623     _settings->setValue("cache_path", cachePathN);
624     _settings->setValue("cached", "true");
625
626     db.close();
627     return true;
628 }
629
630
631 void XdxfPlugin::clean() {
632     if(QFile::exists(_settings->value("cache_path"))) {
633         QFile(_settings->value("cache_path")).remove();
634         QSqlDatabase::removeDatabase(db_name);
635     }
636 }
637
638
639 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)