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