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