change comment's and fix bug (xslt transform)
[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     stopped = false;
128     word = word.toLower();
129     word = word.replace("*", "%");
130     word = word.replace("?", "_");
131
132     QSqlQuery cur(db);
133     if(limit !=0)
134         cur.prepare("select word from dict where word like ? or normalized "
135                     "like ? limit ?");
136     else
137         cur.prepare("select word from dict where word like ? or normalized "
138                     "like ?");
139     cur.addBindValue(word);
140     cur.addBindValue(word);
141     if(limit !=0)
142         cur.addBindValue(limit);
143     cur.exec();
144
145     while(cur.next() && (translations.size()<limit || limit==0)) {
146        translations.insert(new TranslationXdxf(
147             cur.value(0).toString(),
148             _dictionaryInfo, this));
149     }
150     db.close();
151     return translations.toList();
152 }
153
154
155 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
156     QSet<Translation*> translations;
157     QFile dictionaryFile(_settings->value("path"));
158     word = word.toLower();
159     stopped = false;
160
161     QRegExp regWord(word);
162     regWord.setCaseSensitivity(Qt::CaseInsensitive);
163     regWord.setPatternSyntax(QRegExp::Wildcard);
164
165     /*check xdxf file exist*/
166     if(!QFile::exists(_settings->value("path"))
167                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
168         qDebug()<<"Error: could not open file";
169         Q_EMIT notify(Notify::Warning,
170                 QString(tr("XDXF file cannot be read for %1").arg(name())));
171         return translations.toList();
172     }
173
174     QXmlStreamReader reader(&dictionaryFile);
175     QString readKey;
176     int i=0;
177
178     /*search words list*/
179     while(!reader.atEnd() && !stopped){
180         reader.readNextStartElement();
181         if(reader.name()=="ar") {
182             while(reader.name()!="k" && !reader.atEnd())
183                 reader.readNextStartElement();
184             if(!reader.atEnd())
185                 readKey = reader.readElementText();
186             if((regWord.exactMatch(readKey)
187                     || regWord.exactMatch(removeAccents(readKey)))
188                     && (i<limit || limit==0) && !reader.atEnd())  {
189                 translations<<(new TranslationXdxf(readKey.toLower(),
190                                _dictionaryInfo,this));
191                 if(translations.size()==limit && limit!=0)
192                     break;
193             }
194         }
195         this->thread()->yieldCurrentThread();
196     }
197     stopped=false;
198     dictionaryFile.close();
199     return translations.toList();
200 }
201
202
203 QString XdxfPlugin::search(QString key) {
204     if(isCached())
205         return searchCache(key);
206     return searchFile(key);
207 }
208
209
210 QString XdxfPlugin::searchCache(QString key) {
211     QString result("");
212     QString cacheFilePath = _settings->value("cache_path");
213     db.setDatabaseName(cacheFilePath);
214     key = key.toLower();
215
216     if(!QFile::exists(cacheFilePath) || !db.open()) {
217         qDebug() << "Database error" << db.lastError().text() << endl;
218         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
219                 "opened for %1 dictionary. Searching in XDXF file. "
220                 "You may want to recache.").arg(name())));
221         _settings->setValue("cached","false");
222         return searchFile(key);
223     }
224
225     QSqlQuery cur(db);
226
227     cur.prepare("select translation from dict where word like ?");
228     cur.addBindValue(key);
229     cur.exec();
230     while(cur.next())
231         result += cur.value(0).toString();
232     db.close();
233
234     return result;
235 }
236
237
238 QString XdxfPlugin::searchFile(QString key) {
239     QFile dictionaryFile(_settings->value("path"));
240     QString resultString("");
241     key = key.toLower();
242
243     /*check xdxf file exist*/
244     if(!QFile::exists(_settings->value("path"))
245                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
246         Q_EMIT notify(Notify::Warning,
247                 QString(tr("XDXF file cannot be read for %1").arg(name())));
248         qDebug()<<"Error: could not open file";
249         return "";
250     }
251
252     QXmlStreamReader reader(&dictionaryFile);
253     QString readKey;
254     bool match =false;
255     stopped = false;
256
257     /*search translations for word*/
258     while (!reader.atEnd()&& !stopped) {
259         reader.readNext();
260         if(reader.tokenType() == QXmlStreamReader::StartElement) {
261             if(reader.name()=="k") {
262                 readKey = reader.readElementText();
263                 if(readKey.toLower()==key.toLower())
264                     match = true;
265             }
266         }
267         if(match) {
268             QString temp("");
269             while(reader.name()!="ar" && !reader.atEnd()) {
270                 if(reader.name()!="" && reader.name()!="k") {
271                     if(reader.tokenType()==QXmlStreamReader::EndElement)
272                         temp+="</";
273                     if(reader.tokenType()==QXmlStreamReader::StartElement)
274                         temp+="<";
275                     temp+=reader.name().toString();
276                     if(reader.name().toString()=="c" &&
277                             reader.tokenType()==QXmlStreamReader::StartElement)
278                        temp= temp + " c=\"" + reader.attributes().
279                                value("c").toString() + "\"";
280                     temp+=">";
281                 }
282                 temp+= reader.text().toString().replace("<","&lt;").
283                         replace(">","&gt;");
284                 reader.readNext();
285             }
286             if(temp.at(0)==QChar('\n'))
287                 temp.remove(0,1);
288             resultString+="<key>" + readKey +"</key>";
289             resultString+="<t>" + temp + "</t>";
290             match=false;
291         }
292         this->thread()->yieldCurrentThread();
293     }
294     stopped=false;
295     dictionaryFile.close();
296     return resultString;
297 }
298
299
300 void XdxfPlugin::stop() {
301     stopped=true;
302 }
303
304
305 DictDialog* XdxfPlugin::dictDialog() {
306      return _dictDialog;
307 }
308
309
310 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
311     XdxfPlugin *plugin = new XdxfPlugin();
312
313     connect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
314             this, SIGNAL(notify(Notify::NotifyType,QString)));
315
316     ((XdxfDictDialog*)plugin->dictDialog())->setLastDialogParent(_dictDialog->lastDialogParent());
317
318     if(settings && plugin->setSettings(settings)) {
319         disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
320                 this, SIGNAL(notify(Notify::NotifyType,QString)));
321         return plugin;
322     }
323     else {
324         disconnect(plugin, SIGNAL(notify(Notify::NotifyType,QString)),
325                 this, SIGNAL(notify(Notify::NotifyType,QString)));
326         delete plugin;
327         return 0;
328     }
329 }
330
331
332 bool XdxfPlugin::isAvailable() const {
333     return true;
334 }
335
336
337 Settings* XdxfPlugin::settings() {
338     return _settings;
339 }
340
341
342 bool XdxfPlugin::isCached() {
343     if(_settings->value("cached") == "true")
344         return true;
345     return false;
346 }
347
348
349 bool XdxfPlugin::setSettings(const Settings *settings) {
350     if(settings) {
351         bool isPathChange=false;
352         QString oldPath = _settings->value("path");
353         Settings *oldSettings =  new Settings ;
354
355         if(oldPath != settings->value("path")) {
356             if(oldPath!="" && _settings->value("cache_path")!="")
357                 clean();
358             isPathChange=true;
359         }
360
361         foreach(QString key, _settings->keys())
362             oldSettings->setValue(key, _settings->value(key));
363
364         foreach(QString key, settings->keys())
365            if(key != "generateCache")
366                _settings->setValue(key, settings->value(key));
367
368         if(!getDictionaryInfo()) {
369             Q_EMIT notify(Notify::Warning,
370                 QString(tr("XDXF file is in wrong format")));
371             qDebug()<<"Error: xdxf file is in wrong format";
372             delete _settings;
373             _settings=oldSettings;
374             return false;
375         }
376
377         if(isPathChange) {
378             _wordsCount=0;
379             if(oldPath!="")
380                 _settings->setValue("cached","false");
381             if(_settings->value("cached")=="true"
382                     && _settings->value("cache_path")!="") {
383                 db_name = _settings->value("type")
384                         + _settings->value("cache_path");
385                 db = QSqlDatabase::addDatabase("QSQLITE",db_name);
386             }
387         }
388
389         if((_settings->value("cached") == "false" ||
390             _settings->value("cached").isEmpty()) &&
391             settings->value("generateCache") == "true") {
392             clean();
393             makeCache("");
394         }
395
396         else if (settings->value("generateCache") == "false") {
397             _settings->setValue("cached", "false");
398         }
399     }
400     else
401         return false;
402     Q_EMIT settingsChanged();
403     return true;
404 }
405
406
407 bool XdxfPlugin::getDictionaryInfo() {
408     QFile dictionaryFile(_settings->value("path"));
409     if(!QFile::exists(_settings->value("path"))
410                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
411        Q_EMIT notify(Notify::Warning,
412                QString(tr("XDXF dictionary cannot be read from file")));
413         qDebug()<<"Error: could not open file";
414         return false;
415     }
416
417     bool okFormat=false;
418     QXmlStreamReader reader(&dictionaryFile);
419     reader.readNextStartElement();
420     if(reader.name()=="xdxf") {
421         okFormat=true;
422         if(reader.attributes().hasAttribute("lang_from"))
423             _langFrom = reader.attributes().value("lang_from").toString();
424         if(reader.attributes().hasAttribute("lang_to"))
425             _langTo = reader.attributes().value("lang_to").toString();
426     }
427     reader.readNextStartElement();
428     if(reader.name()=="full_name")
429         _name=reader.readElementText();
430     else
431         qDebug()<<"no full_name";
432     reader.readNextStartElement();
433     if(reader.name()=="description")
434         _infoNote=reader.readElementText();
435     else
436         qDebug()<<"no description";
437
438     _dictionaryInfo= _name + " [" + _langFrom + "-"
439                 + _langTo + "]";
440
441     dictionaryFile.close();
442     if(okFormat)
443         return true;
444     return false;
445 }
446
447
448 QIcon* XdxfPlugin::icon() {
449     return &_icon;
450 }
451
452
453 int XdxfPlugin::countWords() {
454     if(_wordsCount>0)
455         return _wordsCount;
456     QFile dictionaryFile(_settings->value("path"));
457     if(!QFile::exists(_settings->value("path"))
458                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
459         Q_EMIT notify(Notify::Warning,
460                 QString(tr("XDXF file cannot be read for %1 dictionary")
461                 .arg(name())));
462         qDebug()<<"Error: could not open file";
463         return -1;
464     }
465
466     dictionaryFile.seek(0);
467     long wordsCount = 0;
468
469     QString line;
470     while(!dictionaryFile.atEnd()) {
471         line = dictionaryFile.readLine();
472         if(line.contains("<k>")) {
473             wordsCount++;
474         }
475     }
476     _wordsCount = wordsCount;
477     dictionaryFile.close();
478     return wordsCount;
479 }
480
481
482 bool XdxfPlugin::makeCache(QString) {
483     XdxfCachingDialog d(_dictDialog->lastDialogParent());
484
485     connect(&d, SIGNAL(cancelCaching()),
486             this, SLOT(stop()));
487     connect(this, SIGNAL(updateCachingProgress(int,int)),
488             &d, SLOT(updateCachingProgress(int,int)));
489
490     d.show();
491     QCoreApplication::processEvents();
492     QFileInfo dictFileN(_settings->value("path"));
493     QString cachePathN;
494     stopped = false;
495
496     /*create cache file name*/
497     int i=0;
498     do {
499         cachePathN = QDir::homePath() + "/.mdictionary/"
500                                       + dictFileN.completeBaseName()+"."
501                                       +QString::number(i) + ".cache";
502         i++;
503     } while(QFile::exists(cachePathN));
504
505     db_name = _settings->value("type") + cachePathN;
506     db = QSqlDatabase::addDatabase("QSQLITE",db_name);
507
508     /*checke errors (File open and db open)*/
509     QFile dictionaryFile(dictFileN.filePath());
510     if (!QFile::exists(_settings->value("path"))
511                 || !dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
512         Q_EMIT updateCachingProgress(100, 0);
513         Q_EMIT notify(Notify::Warning,
514                 QString(tr("XDXF file cannot be read for %1 dictionary")
515                 .arg(name())));
516         return 0;
517     }
518     QXmlStreamReader reader(&dictionaryFile);
519     db.setDatabaseName(cachePathN);
520     if(!db.open()) {
521         qDebug() << "Database error" << db.lastError().text() << endl;
522         Q_EMIT updateCachingProgress(100, 0);
523         Q_EMIT notify(Notify::Warning, QString(tr("Cache database cannot be "
524                 "opened for %1 dictionary. Searching in XDXF file. "
525                 "You may want to recache.").arg(name())));
526         return false;
527     }
528
529     /*inicial sqlQuery*/
530     QCoreApplication::processEvents();
531     QSqlQuery cur(db);
532     cur.exec("PRAGMA synchronous = 0");
533     cur.exec("drop table dict");
534     QCoreApplication::processEvents();
535     cur.exec("create table dict(word text, normalized text ,translation text)");
536     int counter = 0;
537     cur.exec("BEGIN;");
538
539     QString readKey;
540     bool match = false;
541     QTime timer;
542     timer.start();
543     countWords();
544     int lastProg = -1;
545     _settings->setValue("strip_accents", "true");
546     counter=0;
547
548     /*add all words to db*/
549     while (!reader.atEnd() && !stopped) {
550         QCoreApplication::processEvents();
551         reader.readNext();
552         if(reader.tokenType() == QXmlStreamReader::StartElement) {
553             if(reader.name()=="k"){
554                 readKey = reader.readElementText();
555                 match = true;
556             }
557         }
558         if(match) {
559             QString temp("");
560             while(reader.name()!="ar" && !reader.atEnd()) {
561                 if(reader.name()!="" && reader.name()!="k") {
562                     if(reader.tokenType()==QXmlStreamReader::EndElement)
563                         temp+="</";
564                     if(reader.tokenType()==QXmlStreamReader::StartElement)
565                         temp+="<";
566                     temp+=reader.name().toString();
567                     if(reader.name().toString()=="c"
568                         && reader.tokenType()==QXmlStreamReader::StartElement) {
569                         temp= temp + " c=\""
570                                    + reader.attributes().value("c").toString()
571                                    + "\"";
572                     }
573                     temp+=">";
574                 }
575                 temp+= reader.text().toString().replace("<","&lt;").replace(">"
576                               ,"&gt;");
577                 reader.readNext();
578             }
579             if(temp.at(0)==QChar('\n'))
580                 temp.remove(0,1);
581             temp="<key>" + readKey + "</key>" + "<t>" + temp+ "</t>";
582             match=false;
583             cur.prepare("insert into dict values(?,?,?)");
584             cur.addBindValue(readKey.toLower());
585             cur.addBindValue(removeAccents(readKey).toLower());
586             cur.addBindValue(temp);
587             cur.exec();
588             counter++;
589             int prog = counter*100/_wordsCount;
590             if(prog % 2 == 0 && lastProg != prog) {
591                 Q_EMIT updateCachingProgress(prog,timer.restart());
592                 lastProg = prog;
593             }
594         }
595     }
596     cur.exec("END;");
597     cur.exec("select count(*) from dict");
598
599     /*checke errors (wrong number of added words)*/
600     countWords();
601     if(!cur.next() || countWords() != cur.value(0).toInt()) {
602         Q_EMIT updateCachingProgress(100, timer.restart());
603         Q_EMIT notify(Notify::Warning,
604                 QString(tr("Database caching error, please try again.")));
605         db.close();
606         _settings->setValue("cache_path", cachePathN);
607         if(stopped)
608             clean();
609         _settings->setValue("cache_path","");
610         return false;
611     }
612
613     _settings->setValue("cache_path", cachePathN);
614     _settings->setValue("cached", "true");
615
616     disconnect(&d, SIGNAL(cancelCaching()),
617             this, SLOT(stop()));
618     disconnect(this, SIGNAL(updateCachingProgress(int,int)),
619             &d, SLOT(updateCachingProgress(int,int)));
620     db.close();
621     return true;
622 }
623
624
625 void XdxfPlugin::clean() {
626     if(QFile::exists(_settings->value("cache_path"))) {
627         QFile(_settings->value("cache_path")).remove();
628         QSqlDatabase::removeDatabase(db_name);
629     }
630 }
631
632
633 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)