Fixed some of memory leaks and sigsev and bugs
[mdictionary] / trunk / src / plugins / xdxf / src / 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 #include "xdxfplugin.h"
23 #include <QDebug>
24 #include <QFile>
25 #include <QXmlStreamReader>
26 #include <QtPlugin>
27 #include "TranslationXdxf.h"
28 #include "../../../includes/settings.h"
29
30 XdxfPlugin::XdxfPlugin(QObject *parent) : CommonDictInterface(parent),
31                     _langFrom(tr("")), _langTo(tr("")),_name(tr("")),
32                     _type(tr("xdxf")), _infoNote(tr("")) {
33     _wordsCount = -1;
34     _settings = new Settings();
35     _dictDialog = new XdxfDictDialog(this, this);
36     cachingDialog = new XdxfCachingDialog(this);
37
38     connect(cachingDialog, SIGNAL(cancelCaching()),
39             this, SLOT(stop()));
40
41     _settings->setValue("type","xdxf");
42
43     stopped = false;
44
45     _icon = QIcon(":/icons/xdxf.png");
46 }
47
48 QString XdxfPlugin::langFrom() const {   
49     return _langFrom;
50 }
51
52 QString XdxfPlugin::langTo() const {
53     return  _langTo;
54 }
55
56 QString XdxfPlugin::name() const {
57     return  _name;
58 }
59
60 QString XdxfPlugin::type() const {
61 //    return _settings->value("type");
62     return _type;
63 }
64
65 QString XdxfPlugin::infoNote() const {
66     return  _infoNote;
67 }
68
69 QList<Translation*> XdxfPlugin::searchWordList(QString word, int limit) {
70     //if(_settings->value("cached") == "true")
71     if(word.indexOf("*")==-1 && word.indexOf("?")==-1 && word.indexOf("_")==-1
72        && word.indexOf("%")==-1)
73         word+="*";
74     if(isCached())
75         return searchWordListCache(word,limit);
76     return searchWordListFile(word, limit);
77 }
78
79 QList<Translation*> XdxfPlugin::searchWordListCache(QString word, int limit) {
80
81     QSet<Translation*> translations;
82     QString cacheFilePath = _settings->value("cache_path");
83         db.setDatabaseName(cacheFilePath);
84         if(!db.open()) {
85             qDebug() << "Database error" << db.lastError().text() << endl;
86             return searchWordListFile(word, limit);
87         }
88
89         stopped = false;
90         word = word.toLower();
91         word = word.replace("*", "%");
92         word = word.replace("?", "_");
93         word = removeAccents(word);
94         //qDebug() << word;
95
96         QSqlQuery cur(db);
97         if(limit !=0)
98             cur.prepare("select word from dict where word like ? limit ?");
99         else
100             cur.prepare("select word from dict where word like ?");
101         cur.addBindValue(word);
102         if(limit !=0)
103             cur.addBindValue(limit);
104         cur.exec();
105         while(cur.next()){
106             bool ok=true;
107             Translation *tran;
108             foreach(tran,translations) {
109                 if(tran->key().toLower()==cur.value(0).toString().toLower())
110                         ok=false;
111             }
112             if(ok)  /*add key word to list*/
113                 translations.insert(new TranslationXdxf(
114                         cur.value(0).toString().toLower(),
115                         _infoNote, this));
116         }
117         db.close();
118         return translations.toList();
119 }
120
121 QList<Translation*> XdxfPlugin::searchWordListFile(QString word, int limit) {
122     QSet<Translation*> translations;
123     QFile dictionaryFile(path);
124
125     word = word.toLower();
126     word = removeAccents(word);
127
128     stopped = false;
129     QRegExp regWord(word);
130     regWord.setCaseSensitivity(Qt::CaseInsensitive);
131     regWord.setPatternSyntax(QRegExp::Wildcard);
132     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
133         qDebug()<<"Error: could not open file";
134         return translations.toList();
135     }
136
137     QXmlStreamReader reader(&dictionaryFile);
138     /*search words list*/
139     QString a;
140     int i=0;
141     while(!reader.atEnd() && !stopped){
142         reader.readNextStartElement();
143         if(reader.name()=="ar") {
144             while(reader.name()!="k" && !reader.atEnd())
145                 reader.readNextStartElement();
146             if(!reader.atEnd())
147                 a = reader.readElementText();
148             if(regWord.exactMatch(removeAccents(a)) && (i<limit || limit==0)) {
149                 bool ok=true;
150                 Translation *tran;
151                 foreach(tran,translations) {
152                     if(tran->key().toLower()==a.toLower())
153                         ok=false;  /*if key word is in the dictionary more that one */
154                 }
155                 if(ok)  /*add key word to list*/
156                     translations<<(new TranslationXdxf(a.toLower(),
157                                 _infoNote,this));
158                 i++;
159                 if(i>=limit && limit!=0)
160                     break;
161             }
162         }
163         this->thread()->yieldCurrentThread();
164     }
165     stopped=false;
166     dictionaryFile.close();
167     return translations.toList();
168 }
169
170 QString XdxfPlugin::search(QString key) {
171 //    if(_settings->value("cached") == "true")
172     if(isCached())
173         return searchCache(key);
174     return searchFile(key);
175 }
176
177 QString XdxfPlugin::searchCache(QString key) {
178     QString result("");
179     QString cacheFilePath = _settings->value("cache_path");
180     db.setDatabaseName(cacheFilePath);
181     key = key.toLower();
182
183     if(!db.open()) {
184         qDebug() << "Database error" << db.lastError().text() << endl;
185         return searchFile(key);
186     }
187
188     QSqlQuery cur(db);
189 //    cur.prepare("select translation from dict where word like ? limit 1");
190     cur.prepare("select translation from dict where word like ?");
191     cur.addBindValue(key);
192     cur.exec();
193 //  if(cur.next())
194     while(cur.next())
195 //      result = cur.value(0).toString();
196         result += cur.value(0).toString();
197     db.close();
198     return result;
199
200 }
201
202 QString XdxfPlugin::searchFile(QString key) {
203     key = key.toLower();
204     QFile dictionaryFile(path);
205     QString resultString("");
206     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
207         qDebug()<<"Error: could not open file";
208         return "";
209     }
210     QXmlStreamReader reader(&dictionaryFile);
211
212
213
214     QString a;
215
216     bool match =false;
217     stopped = false;
218     while (!reader.atEnd()&& !stopped) {
219         reader.readNext();
220         if(reader.tokenType() == QXmlStreamReader::StartElement) {
221             if(reader.name()=="k") {
222                 a = reader.readElementText();
223                 if(a.toLower()==key.toLower())
224                     match = true;
225             }
226         }
227         if(match) {
228             QString temp("");
229             while(reader.name()!="ar" && !reader.atEnd()) {
230                 if(reader.name()!="" && reader.name()!="k") {
231                     if(reader.tokenType()==QXmlStreamReader::EndElement)
232                         temp+=tr("</");
233                     if(reader.tokenType()==QXmlStreamReader::StartElement)
234                         temp+=tr("<");
235                     temp+=reader.name().toString();
236                     if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
237                        temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
238                     temp+=tr(">");
239                 }
240                 temp+= reader.text().toString().replace("<","&lt;").replace(">","&gt;");
241                 reader.readNext();
242             }
243             if(temp.at(0)==QChar('\n'))
244                 temp.remove(0,1);
245             resultString+=tr("<t>") + temp + tr("</t>");    //.replace("\n","")
246             match=false;
247         }
248         this->thread()->yieldCurrentThread();
249     }
250     stopped=false;
251     dictionaryFile.close();
252
253     return resultString;
254 }
255
256 void XdxfPlugin::stop() {
257     stopped=true;
258 }
259
260 DictDialog* XdxfPlugin::dictDialog() {
261      return _dictDialog;
262 }
263
264 void XdxfPlugin::setPath(QString path){
265     this->path=path;
266     _settings->setValue("path",path);
267     //getDictionaryInfo();
268 }
269
270 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
271     XdxfPlugin *plugin = new XdxfPlugin();
272     if(settings){
273         plugin->setPath(settings->value("path"));
274
275         QStringList list = settings->keys();
276         foreach(QString key, list)
277             plugin->settings()->setValue(key, settings->value(key));
278
279
280         plugin->db_name = plugin->_settings->value("type")
281                + plugin->_settings->value("path");
282  //       if(!plugin->db.connectionName().isEmpty() || settings->value("generateCache")=="true")
283             plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
284
285         if(settings->value("cached").isEmpty() &&
286            settings->value("generateCache") == "true") {
287             plugin->makeCache("");
288         }
289         delete settings;
290     }
291
292     plugin->getDictionaryInfo();
293     return  plugin;
294 }
295
296 bool XdxfPlugin::isAvailable() const {
297     return true;
298 }
299
300 void XdxfPlugin::setHash(uint _hash) {
301     this->_hash=_hash;
302 }
303
304 uint XdxfPlugin::hash() const {
305    return _hash;
306 }
307
308 Settings* XdxfPlugin::settings() {
309     return _settings;
310 }
311
312 bool XdxfPlugin::isCached() {
313     if(_settings->value("cached") == "true")
314         return true;
315     return false;
316 }
317
318 void XdxfPlugin::setSettings(Settings *settings) {
319
320     QString oldPath = _settings->value("path");
321     if(oldPath != settings->value("path")) {
322         setPath(settings->value("path"));
323     }
324
325     if((_settings->value("cached") == "false" ||
326         _settings->value("cached").isEmpty()) &&
327        settings->value("generateCache") == "true") {
328         makeCache("");
329     }
330     else {
331        _settings->setValue("cached", "false");
332     }
333     delete settings;
334
335     emit settingsChanged();
336 }
337
338 void XdxfPlugin::getDictionaryInfo() {
339     QFile dictionaryFile(path);
340     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
341         qDebug()<<"Error: could not open file";
342         return;
343     }
344
345     QXmlStreamReader reader(&dictionaryFile);
346     reader.readNextStartElement();
347     if(reader.name()=="xdxf") {
348       if(reader.attributes().hasAttribute("lang_from"))
349         _langFrom = reader.attributes().value("lang_from").toString();
350       if(reader.attributes().hasAttribute("lang_to"))
351         _langTo = reader.attributes().value("lang_to").toString();
352     }
353     reader.readNextStartElement();
354     if(reader.name()=="full_name")
355         _name=reader.readElementText();
356     reader.readNextStartElement();
357     if(reader.name()=="description")
358         _infoNote=reader.readElementText();
359
360     QString format = "png";
361     QString initialPath = QDir::currentPath() + tr("/xdxf.") + format;
362 //    qDebug()<<initialPath;
363 //    qDebug()<<QPixmap(":/icons/xdxf.png").save(initialPath,format.toAscii());
364
365     _infoNote="<info path=\""+initialPath+"\">"+"\n" + _name + "(" + _type + ")"  + "</info>";
366
367
368
369     dictionaryFile.close();
370 }
371
372 QString XdxfPlugin::removeAccents(QString string) {
373     string = string.replace(QString::fromUtf8("ł"), "l", Qt::CaseInsensitive);
374     QString normalized = string.normalized(QString::NormalizationForm_D);
375     normalized = normalized;
376     for(int i=0; i<normalized.size(); i++) {
377         if( !normalized[i].isLetterOrNumber() &&
378             !normalized[i].isSpace() &&
379             !normalized[i].isDigit() &&
380             normalized[i] != '*' &&
381             normalized[i] != '%' &&
382             normalized[i] != '_' &&
383             normalized[i] != '?' ) {
384             normalized.remove(i,1);
385         }
386     }
387     return normalized;
388 }
389
390 QIcon* XdxfPlugin::icon() {
391     return &_icon;
392 }
393
394 int XdxfPlugin::countWords() {
395     if(_wordsCount > 0)
396         return _wordsCount;
397
398     QFile dictionaryFile(path);
399     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
400         qDebug()<<"Error: could not open file";
401         return -1;
402     }
403
404     dictionaryFile.seek(0);
405
406     long wordsCount = 0;
407
408     QString line;
409     while(!dictionaryFile.atEnd()) {
410         line = dictionaryFile.readLine();
411         if(line.contains("<k>")) {
412             wordsCount++;
413         }
414     }
415     _wordsCount = wordsCount;
416     dictionaryFile.close();
417     return wordsCount;
418 }
419
420 bool XdxfPlugin::makeCache(QString dir) {
421     cachingDialog->setVisible(true);
422     QCoreApplication::processEvents();
423     stopped = false;
424     QFileInfo dictFileN(_settings->value("path"));
425     QString cachePathN;
426     cachePathN = QDir::homePath() + "/.mdictionary/"
427                  + dictFileN.completeBaseName() + ".cache";
428
429     QFile dictionaryFile(dictFileN.filePath());
430
431
432     if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
433         return 0;
434     }
435
436     QXmlStreamReader reader(&dictionaryFile);
437
438     db.setDatabaseName(cachePathN);
439     if(!db.open()) {
440         qDebug() << "Database error" << db.lastError().text() << endl;
441         return false;
442     }
443     QCoreApplication::processEvents();
444     QSqlQuery cur(db);
445     cur.exec("PRAGMA synchronous = 0");
446     cur.exec("drop table dict");
447     QCoreApplication::processEvents();
448     cur.exec("create table dict(word text ,translation text)");
449     int counter = 0;
450     cur.exec("BEGIN;");
451
452     QString a;
453     bool match = false;
454     QTime timer;
455     timer.start();
456     countWords();
457
458     int lastProg = -1;
459
460
461     counter=0;
462     while (!reader.atEnd() && !stopped) {
463
464         QCoreApplication::processEvents();
465         reader.readNext();
466
467         if(reader.tokenType() == QXmlStreamReader::StartElement) {
468             if(reader.name()=="k"){
469                 a = reader.readElementText();
470                 match = true;
471             }
472         }
473         if(match) {
474             QString temp("");
475             while(reader.name()!="ar" && !reader.atEnd()) {
476                 if(reader.name()!="" && reader.name()!="k") {
477                     if(reader.tokenType()==QXmlStreamReader::EndElement)
478                         temp+=tr("</");
479                     if(reader.tokenType()==QXmlStreamReader::StartElement)
480                         temp+=tr("<");
481                     temp+=reader.name().toString();
482                     if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
483                        temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
484                     temp+=tr(">");
485                 }
486                 temp+= reader.text().toString().replace("<","&lt;").replace(">","&gt;");;
487                 reader.readNext();
488             }
489             if(temp.at(0)==QChar('\n'))
490                 temp.remove(0,1);
491             temp=tr("<t>") + temp+ tr("</t>");  //.replace("\n","")
492             match=false;
493             cur.prepare("insert into dict values(?,?)");
494             cur.addBindValue(a);
495             cur.addBindValue(temp);
496             cur.exec();
497             counter++;
498             int prog = counter*100/_wordsCount;
499             if(prog % 5 == 0 && lastProg != prog) {
500                 Q_EMIT updateCachingProgress(prog,
501                                              timer.restart());
502                 lastProg = prog;
503             }
504         }
505     }
506
507     cur.exec("END;");
508     cur.exec("select count(*) from dict");
509
510     countWords();
511     cachingDialog->setVisible(false);
512
513     if(!cur.next() || countWords() != cur.value(0).toInt())
514     {
515         db.close();
516         return false;
517     }
518     _settings->setValue("cache_path", cachePathN);
519     _settings->setValue("cached", "true");
520
521     db.close();
522     return true;
523 }
524
525 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)