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