Changed repo structure
[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 "../../common/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 //  QSqlDatabase::removeDatabase(cacheFilePath);
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     XdxfPlugin *plugin = new XdxfPlugin();
313     if(settings){
314         plugin->setSettings(settings);
315     }
316     return  plugin;
317 }
318
319
320 bool XdxfPlugin::isAvailable() const {
321     return true;
322 }
323
324
325 void XdxfPlugin::setHash(uint _hash) {
326     this->_hash=_hash;
327 }
328
329
330 uint XdxfPlugin::hash() const {
331    return _hash;
332 }
333
334
335 Settings* XdxfPlugin::settings() {
336     return _settings;
337 }
338
339
340 bool XdxfPlugin::isCached() {
341     if(_settings->value("cached") == "true")
342         return true;
343     return false;
344 }
345
346
347 void XdxfPlugin::setSettings(const Settings *settings) {
348     if(settings) {
349
350         bool isPathChange=false;
351         QString oldPath = _settings->value("path");
352         if(oldPath != settings->value("path")) {
353             if(oldPath!="" && _settings->value("cache_path")!="")
354                 clean();
355             isPathChange=true;
356         }
357
358         foreach(QString key, settings->keys()) {
359            if(key != "generateCache")
360                _settings->setValue(key, settings->value(key));
361         }
362
363         if(isPathChange) {
364             _wordsCount=0;
365             if(oldPath!="") {
366                 _settings->setValue("cached","false");
367                 QSqlDatabase::removeDatabase(db_name);
368             }
369             db_name = _settings->value("type") + _settings->value("path");
370             db = QSqlDatabase::addDatabase("QSQLITE",db_name);
371         }
372
373         if((_settings->value("cached") == "false" ||
374             _settings->value("cached").isEmpty()) &&
375             settings->value("generateCache") == "true") {
376             clean();
377             makeCache("");
378         }
379
380         else if (settings->value("generateCache") == "false") {
381             _settings->setValue("cached", "false");
382         }
383
384         getDictionaryInfo();
385     }
386     Q_EMIT settingsChanged();
387 }
388
389
390 void XdxfPlugin::getDictionaryInfo() {
391     QFile dictionaryFile(_settings->value("path"));
392     if(!QFile::exists(_settings->value("path"))
393                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
394        Q_EMIT notify(Notify::Warning,
395                QString(tr("XDXF dictionary cannot be read from file")));
396         qDebug()<<"Error: could not open file";
397         return;
398     }
399
400     QXmlStreamReader reader(&dictionaryFile);
401     reader.readNextStartElement();
402     if(reader.name()=="xdxf") {
403       if(reader.attributes().hasAttribute("lang_from"))
404         _langFrom = reader.attributes().value("lang_from").toString();
405       if(reader.attributes().hasAttribute("lang_to"))
406         _langTo = reader.attributes().value("lang_to").toString();
407     }
408     reader.readNextStartElement();
409     if(reader.name()=="full_name")
410         _name=reader.readElementText();
411     reader.readNextStartElement();
412     if(reader.name()=="description")
413         _infoNote=reader.readElementText();
414
415     QString format = "png";
416     QString initialPath = QDir::currentPath() + "/xdxf." + format;
417
418     _infoNote="path=\""+initialPath+"\"> \n" + _name + " [" + _langFrom + "-"
419                 + _langTo + "] ( xdxf )";
420     dictionaryFile.close();
421 }
422
423
424 QIcon* XdxfPlugin::icon() {
425     return &_icon;
426 }
427
428
429 int XdxfPlugin::countWords() {
430     if(_wordsCount>0)
431         return _wordsCount;
432     QFile dictionaryFile(_settings->value("path"));
433     if(!QFile::exists(_settings->value("path"))
434                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
435         Q_EMIT notify(Notify::Warning,
436                 QString(tr("XDXF file cannot be read for %1 dictionary")
437                 .arg(name())));
438         qDebug()<<"Error: could not open file";
439         return -1;
440     }
441
442     dictionaryFile.seek(0);
443
444     long wordsCount = 0;
445
446     QString line;
447     while(!dictionaryFile.atEnd()) {
448         line = dictionaryFile.readLine();
449         if(line.contains("<k>")) {
450             wordsCount++;
451         }
452     }
453     _wordsCount = wordsCount;
454     dictionaryFile.close();
455     return wordsCount;
456 }
457
458
459 bool XdxfPlugin::makeCache(QString) {
460     cachingDialog->setVisible(true);
461     QCoreApplication::processEvents();
462     QFileInfo dictFileN(_settings->value("path"));
463     QString cachePathN;
464     stopped = false;
465
466     /*create cache file name*/
467     int i=0;
468     do {
469         cachePathN = QDir::homePath() + "/.mdictionary/"
470                                       + dictFileN.completeBaseName()+"."
471                                       +QString::number(i) + ".cache";
472         i++;
473     } while(QFile::exists(cachePathN));
474
475     /*checke errors (File open and db open)*/
476     QFile dictionaryFile(dictFileN.filePath());
477     if (!QFile::exists(_settings->value("path"))
478                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
479         Q_EMIT updateCachingProgress(100, 0);
480         Q_EMIT notify(Notify::Warning,
481                 QString(tr("XDXF file cannot be read for %1 dictionary")
482                 .arg(name())));
483         return 0;
484     }
485     QXmlStreamReader reader(&dictionaryFile);
486     db.setDatabaseName(cachePathN);
487     if(!db.open()) {
488         qDebug() << "Database error" << db.lastError().text() << endl;
489         Q_EMIT updateCachingProgress(100, 0);
490         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
491                 "opened for %1 dictionary. Searching in XDXF file. "
492                 "You may want to recache.").arg(name())));
493         return false;
494     }
495
496     /*inicial sqlQuery*/
497     QCoreApplication::processEvents();
498     QSqlQuery cur(db);
499     cur.exec("PRAGMA synchronous = 0");
500     cur.exec("drop table dict");
501     QCoreApplication::processEvents();
502     cur.exec("create table dict(word text, normalized text ,translation text)");
503     int counter = 0;
504     cur.exec("BEGIN;");
505
506     QString readKey;
507     bool match = false;
508     QTime timer;
509     timer.start();
510     countWords();
511     int lastProg = -1;
512     settings()->setValue("strip_accents", "true");
513     counter=0;
514
515     /*add all words to db*/
516     while (!reader.atEnd() && !stopped) {
517         QCoreApplication::processEvents();
518         reader.readNext();
519         if(reader.tokenType() == QXmlStreamReader::StartElement) {
520             if(reader.name()=="k"){
521                 readKey = reader.readElementText();
522                 match = true;
523             }
524         }
525         if(match) {
526             QString temp("");
527             while(reader.name()!="ar" && !reader.atEnd()) {
528                 if(reader.name()!="" && reader.name()!="k") {
529                     if(reader.tokenType()==QXmlStreamReader::EndElement)
530                         temp+="</";
531                     if(reader.tokenType()==QXmlStreamReader::StartElement)
532                         temp+="<";
533                     temp+=reader.name().toString();
534                     if(reader.name().toString()=="c"
535                         && reader.tokenType()==QXmlStreamReader::StartElement) {
536                         temp= temp + " c=\""
537                                    + reader.attributes().value("c").toString()
538                                    + "\"";
539                     }
540                     temp+=">";
541                 }
542                 temp+= reader.text().toString().replace("<","&lt;").replace(">"
543                               ,"&gt;");
544                 reader.readNext();
545             }
546             if(temp.at(0)==QChar('\n'))
547                 temp.remove(0,1);
548             temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
549             match=false;
550             cur.prepare("insert into dict values(?,?,?)");
551             cur.addBindValue(readKey);
552             cur.addBindValue(removeAccents(readKey));
553             cur.addBindValue(temp);
554             cur.exec();
555             counter++;
556             int prog = counter*100/_wordsCount;
557             if(prog % 5 == 0 && lastProg != prog) {
558                 Q_EMIT updateCachingProgress(prog,timer.restart());
559                 lastProg = prog;
560             }
561         }
562     }
563     cur.exec("END;");
564     cur.exec("select count(*) from dict");
565     cachingDialog->setVisible(false);
566
567     /*checke errors (wrong number of added words)*/
568     countWords();
569     if(!cur.next() || countWords() != cur.value(0).toInt()) {
570         Q_EMIT updateCachingProgress(100, timer.restart());
571         Q_EMIT notify(Notify::Warning,
572                 QString(tr("Database caching error, please try againg.")));
573         db.close();
574         return false;
575     }
576
577     _settings->setValue("cache_path", cachePathN);
578     _settings->setValue("cached", "true");
579
580     db.close();
581     return true;
582 }
583
584
585 void XdxfPlugin::clean() {
586     if(QFile::exists(_settings->value("cache_path")))
587         QFile(_settings->value("cache_path")).remove();
588 }
589
590
591 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)