Merge branch 'http' of ssh://drop.maemo.org/git/mdictionary into http
[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
31
32 XdxfDictDownloader XdxfPlugin::dictDownloader;
33
34 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
35                     _langFrom(""), _langTo(""),_name(""), _infoNote("") {
36
37     //DownloadDict a("<tr><td><img src=\"buf/comn_sdict05_bulg_comp/icon16.png\" alt=\"icon\" /></td><td align=\"center\">English-Bulgarian computer dictionary</td><td align=\"center\"><a href=\"http://downloads.sourceforge.net/xdxf/comn_sdict05_bulg_comp.tar.bz2\" target=\"_blank\">comn_sdict05_bulg_comp.tar.bz2</a></td><td align=\"right\">13,889</td><td align=\"right\">55,094</td><td align=\"right\">523</td><td align=\"center\">English</td><td align=\"center\">Bulgarian</td><td align=\"center\"><a href=\"http://xdxf.revdanica.com/\">Common XDXF</a></td><td align=\"center\">2006-04-23 23:34:40</td></tr>");
38
39
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
47     _settings->setValue("type","xdxf");
48     _icon = QIcon("/usr/share/mdictionary/xdxf.png");
49     _wordsCount = -1;
50     stopped = false;
51
52     initAccents();
53 }
54
55 void XdxfPlugin::retranslate() {
56     QString locale = QLocale::system().name();
57
58     QTranslator *translator = new QTranslator(this);
59
60     if(!translator->load(":/xdxf/translations/" + locale)) {
61         translator->load(":/xdxf/translations/en_US");
62     }
63     QCoreApplication::installTranslator(translator);
64 }
65
66
67 XdxfPlugin::~XdxfPlugin() {
68     delete _settings;
69     delete _dictDialog;
70 }
71
72
73 QString XdxfPlugin::langFrom() const {   
74     return _langFrom;
75 }
76
77
78 QString XdxfPlugin::langTo() const {
79     return  _langTo;
80 }
81
82
83 QString XdxfPlugin::name() const {
84     return  _name;
85 }
86
87
88 QString XdxfPlugin::type() const {
89     return QString("xdxf");
90 }
91
92
93 QString XdxfPlugin::infoNote() const {
94     return _infoNote;
95 }
96
97
98 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
99     if( word.indexOf("*")==-1 && word.indexOf("?")==-1 &&
100         word.indexOf("_")==-1 && word.indexOf("%")==-1)
101         word+="*";
102
103     if(isCached())
104         return searchWordListCache(word,limit);
105     return searchWordListFile(word, limit);
106 }
107
108
109 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
110     QSet<Translation*> translations;
111     QString cacheFilePath = _settings->value("cache_path");
112
113     db.setDatabaseName(cacheFilePath);
114     if(!QFile::exists(cacheFilePath) || !db.open()) {
115         qDebug() << "Database error" << db.lastError().text() << endl;
116         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
117                 "opened for %1 dictionary. Searching in XDXF file. "
118                 "You may want to recache.").arg(name())));
119         _settings->setValue("cached","false");
120         return searchWordListFile(word, limit);
121     }
122     stopped = false;
123     word = word.toLower();
124     word = word.replace("*", "%");
125     word = word.replace("?", "_");
126
127     QSqlQuery cur(db);
128     if(limit !=0)
129         cur.prepare("select word from dict where word like ? or normalized "
130                     "like ? limit ?");
131     else
132         cur.prepare("select word from dict where word like ? or normalized "
133                     "like ?");
134     cur.addBindValue(word);
135     cur.addBindValue(word);
136     if(limit !=0)
137         cur.addBindValue(limit);
138     cur.exec();
139
140     while(cur.next() && (translations.size()<limit || limit==0)) {
141        translations.insert(new TranslationXdxf(
142             cur.value(0).toString(),
143             _dictionaryInfo, this));
144     }
145     db.close();
146     return translations.toList();
147 }
148
149
150 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
151     QSet<Translation*> translations;
152     QFile dictionaryFile(_settings->value("path"));
153     word = word.toLower();
154     stopped = false;
155
156     QRegExp regWord(word);
157     regWord.setCaseSensitivity(Qt::CaseInsensitive);
158     regWord.setPatternSyntax(QRegExp::Wildcard);
159
160     /*check xdxf file exist*/
161     if(!QFile::exists(_settings->value("path"))
162                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
163         qDebug()<<"Error: could not open file";
164         Q_EMIT notify(Notify::Warning,
165                 QString(tr("XDXF file cannot be read for %1").arg(name())));
166         return translations.toList();
167     }
168
169     QXmlStreamReader reader(&dictionaryFile);
170     QString readKey;
171     int i=0;
172
173     /*search words list*/
174     while(!reader.atEnd() && !stopped){
175         reader.readNextStartElement();
176         if(reader.name()=="ar") {
177             while(reader.name()!="k" && !reader.atEnd())
178                 reader.readNextStartElement();
179             if(!reader.atEnd())
180                 readKey = reader.readElementText();
181             if((regWord.exactMatch(readKey)
182                     || regWord.exactMatch(removeAccents(readKey)))
183                     && (i<limit || limit==0) && !reader.atEnd())  {
184  //               qDebug()<<readKey;
185                 translations<<(new TranslationXdxf(readKey.toLower(),
186                                _dictionaryInfo,this));
187                 if(translations.size()==limit && limit!=0)
188                     break;
189             }
190         }
191         this->thread()->yieldCurrentThread();
192     }
193     stopped=false;
194     dictionaryFile.close();
195     return translations.toList();
196 }
197
198
199 QString XdxfPlugin::search(QString key) {
200     if(isCached())
201         return searchCache(key);
202     return searchFile(key);
203 }
204
205
206 QString XdxfPlugin::searchCache(QString key) {
207     QString result("");
208     QString cacheFilePath = _settings->value("cache_path");
209     db.setDatabaseName(cacheFilePath);
210     key = key.toLower();
211
212     if(!QFile::exists(cacheFilePath) || !db.open()) {
213         qDebug() << "Database error" << db.lastError().text() << endl;
214         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
215                 "opened for %1 dictionary. Searching in XDXF file. "
216                 "You may want to recache.").arg(name())));
217         _settings->setValue("cached","false");
218         return searchFile(key);
219     }
220
221     QSqlQuery cur(db);
222
223     cur.prepare("select translation from dict where word like ?");
224     cur.addBindValue(key);
225     cur.exec();
226     while(cur.next())
227         result += cur.value(0).toString();
228
229     db.close();
230
231     return result;
232
233 }
234
235
236 QString XdxfPlugin::searchFile(QString key) {
237     QFile dictionaryFile(_settings->value("path"));
238     QString resultString("");
239     key = key.toLower();
240
241     /*check xdxf file exist*/
242     if(!QFile::exists(_settings->value("path"))
243                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
244         Q_EMIT notify(Notify::Warning,
245                 QString(tr("XDXF file cannot be read for %1").arg(name())));
246         qDebug()<<"Error: could not open file";
247         return "";
248     }
249
250     QXmlStreamReader reader(&dictionaryFile);
251     QString readKey;
252     bool match =false;
253     stopped = false;
254
255     /*search translations for word*/
256     while (!reader.atEnd()&& !stopped) {
257         reader.readNext();
258         if(reader.tokenType() == QXmlStreamReader::StartElement) {
259             if(reader.name()=="k") {
260                 readKey = reader.readElementText();
261                 if(readKey.toLower()==key.toLower())
262                     match = true;
263             }
264         }
265         if(match) {
266             QString temp("");
267             while(reader.name()!="ar" && !reader.atEnd()) {
268                 if(reader.name()!="" && reader.name()!="k") {
269                     if(reader.tokenType()==QXmlStreamReader::EndElement)
270                         temp+="</";
271                     if(reader.tokenType()==QXmlStreamReader::StartElement)
272                         temp+="<";
273                     temp+=reader.name().toString();
274                     if(reader.name().toString()=="c" &&
275                             reader.tokenType()==QXmlStreamReader::StartElement)
276                        temp= temp + " c=\"" + reader.attributes().
277                                value("c").toString() + "\"";
278                     temp+=">";
279                 }
280                 temp+= reader.text().toString().replace("<","&lt;").
281                         replace(">","&gt;");
282                 reader.readNext();
283             }
284             if(temp.at(0)==QChar('\n'))
285                 temp.remove(0,1);
286             resultString+="<key>" + readKey +"</key>";
287             resultString+="<t>" + temp + "</t>";
288             match=false;
289         }
290         this->thread()->yieldCurrentThread();
291     }
292     stopped=false;
293     dictionaryFile.close();
294     return resultString;
295 }
296
297
298 void XdxfPlugin::stop() {
299    //qDebug()<<"stop";
300     stopped=true;
301 }
302
303
304 DictDialog* XdxfPlugin::dictDialog() {
305      return _dictDialog;
306 }
307
308
309 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
310     XdxfPlugin *plugin = new XdxfPlugin();
311
312     connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
313             this, SIGNAL(notify(Notify::NotifyType,QString)));
314
315     ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
316
317
318
319     if(settings && plugin->setSettings(settings)) {
320
321         disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
322                 this, SIGNAL(notify(Notify::NotifyType,QString)));
323         return plugin;
324     }
325     else {
326         disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
327                 this, SIGNAL(notify(Notify::NotifyType,QString)));
328         delete plugin;
329         return 0;
330     }
331 }
332
333
334 bool XdxfPlugin::isAvailable() const {
335     return true;
336 }
337
338
339 Settings* XdxfPlugin::settings() {
340     return _settings;
341 }
342
343
344 bool XdxfPlugin::isCached() {
345     if(_settings->value("cached") == "true")
346         return true;
347     return false;
348 }
349
350
351 bool XdxfPlugin::setSettings(const Settings *settings) {
352     if(settings) {
353         bool isPathChange=false;
354         QString oldPath = _settings->value("path");
355         Settings *oldSettings =  new Settings ;
356
357         if(oldPath != settings->value("path")) {
358             if(oldPath!="" && _settings->value("cache_path")!="")
359                 clean();
360             isPathChange=true;
361         }
362
363         foreach(QString key, _settings->keys())
364             oldSettings->setValue(key, _settings->value(key));
365
366         foreach(QString key, settings->keys()) {
367            if(key != "generateCache")
368                _settings->setValue(key, settings->value(key));
369         }
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
471     long wordsCount = 0;
472
473     QString line;
474     while(!dictionaryFile.atEnd()) {
475         line = dictionaryFile.readLine();
476         if(line.contains("<k>")) {
477             wordsCount++;
478         }
479     }
480     _wordsCount = wordsCount;
481     dictionaryFile.close();
482     return wordsCount;
483 }
484
485
486 bool XdxfPlugin::makeCache(QString) {
487
488     XdxfCachingDialog d(_dictDialog->lastDialogParent());
489
490 //    qDebug()<<_dictDialog->lastDialogParent();
491
492     connect(&d, SIGNAL(cancelCaching()),
493             this, SLOT(stop()));
494     connect(this, SIGNAL(updateCachingProgress(int,int)),
495             &d, SLOT(updateCachingProgress(int,int)));
496
497     d.show();
498
499     QCoreApplication::processEvents();
500     QFileInfo dictFileN(_settings->value("path"));
501     QString cachePathN;
502     stopped = false;
503
504     /*create cache file name*/
505     int i=0;
506     do {
507         cachePathN = QDir::homePath() + "/.mdictionary/"
508                                       + dictFileN.completeBaseName()+"."
509                                       +QString::number(i) + ".cache";
510         i++;
511     } while(QFile::exists(cachePathN));
512
513     db_name = _settings->value("type") + cachePathN;
514     db = QSqlDatabase::addDatabase("QSQLITE",db_name);
515
516     /*checke errors (File open and db open)*/
517     QFile dictionaryFile(dictFileN.filePath());
518     if (!QFile::exists(_settings->value("path"))
519                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
520         Q_EMIT updateCachingProgress(100, 0);
521         Q_EMIT notify(Notify::Warning,
522                 QString(tr("XDXF file cannot be read for %1 dictionary")
523                 .arg(name())));
524         return 0;
525     }
526     QXmlStreamReader reader(&dictionaryFile);
527     db.setDatabaseName(cachePathN);
528     if(!db.open()) {
529         qDebug() << "Database error" << db.lastError().text() << endl;
530         Q_EMIT updateCachingProgress(100, 0);
531         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
532                 "opened for %1 dictionary. Searching in XDXF file. "
533                 "You may want to recache.").arg(name())));
534         return false;
535     }
536
537     /*inicial sqlQuery*/
538     QCoreApplication::processEvents();
539     QSqlQuery cur(db);
540     cur.exec("PRAGMA synchronous = 0");
541     cur.exec("drop table dict");
542     QCoreApplication::processEvents();
543     cur.exec("create table dict(word text, normalized text ,translation text)");
544     int counter = 0;
545     cur.exec("BEGIN;");
546
547     QString readKey;
548     bool match = false;
549     QTime timer;
550     timer.start();
551     countWords();
552     int lastProg = -1;
553     _settings->setValue("strip_accents", "true");
554     counter=0;
555
556     /*add all words to db*/
557     while (!reader.atEnd() && !stopped) {
558
559         QCoreApplication::processEvents();
560         reader.readNext();
561         if(reader.tokenType() == QXmlStreamReader::StartElement) {
562             if(reader.name()=="k"){
563                 readKey = reader.readElementText();
564                 match = true;
565             }
566         }
567         if(match) {
568             QString temp("");
569             while(reader.name()!="ar" && !reader.atEnd()) {
570                 if(reader.name()!="" && reader.name()!="k") {
571                     if(reader.tokenType()==QXmlStreamReader::EndElement)
572                         temp+="</";
573                     if(reader.tokenType()==QXmlStreamReader::StartElement)
574                         temp+="<";
575                     temp+=reader.name().toString();
576                     if(reader.name().toString()=="c"
577                         && reader.tokenType()==QXmlStreamReader::StartElement) {
578                         temp= temp + " c=\""
579                                    + reader.attributes().value("c").toString()
580                                    + "\"";
581                     }
582                     temp+=">";
583                 }
584                 temp+= reader.text().toString().replace("<","&lt;").replace(">"
585                               ,"&gt;");
586                 reader.readNext();
587             }
588             if(temp.at(0)==QChar('\n'))
589                 temp.remove(0,1);
590             temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
591             match=false;
592             cur.prepare("insert into dict values(?,?,?)");
593             cur.addBindValue(readKey.toLower());
594             cur.addBindValue(removeAccents(readKey).toLower());
595             cur.addBindValue(temp);
596             cur.exec();
597             counter++;
598             int prog = counter*100/_wordsCount;
599             if(prog % 2 == 0 && lastProg != prog) {
600                 Q_EMIT updateCachingProgress(prog,timer.restart());
601                 lastProg = prog;
602             }
603         }
604     }
605     cur.exec("END;");
606     cur.exec("select count(*) from dict");
607
608     /*checke errors (wrong number of added words)*/
609     countWords();
610     if(!cur.next() || countWords() != cur.value(0).toInt()) {
611         Q_EMIT updateCachingProgress(100, timer.restart());
612         Q_EMIT notify(Notify::Warning,
613                 QString(tr("Database caching error, please try again.")));
614         db.close();
615         _settings->setValue("cache_path", cachePathN);
616         if(stopped)
617             clean();
618         _settings->setValue("cache_path","");
619         return false;
620     }
621
622     _settings->setValue("cache_path", cachePathN);
623     _settings->setValue("cached", "true");
624
625     disconnect(&d, SIGNAL(cancelCaching()),
626             this, SLOT(stop()));
627     disconnect(this, SIGNAL(updateCachingProgress(int,int)),
628             &d, SLOT(updateCachingProgress(int,int)));
629     db.close();
630     return true;
631 }
632
633 void XdxfPlugin::clean() {
634     if(QFile::exists(_settings->value("cache_path"))) {
635         QFile(_settings->value("cache_path")).remove();
636         QSqlDatabase::removeDatabase(db_name);
637     }
638 }
639
640
641 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)