b4fdb5ac4e04529e687b9f630bed5285790debf4
[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     QString a;
214
215     bool match =false;
216     stopped = false;
217     while (!reader.atEnd()&& !stopped) {
218         reader.readNext();
219         if(reader.tokenType() == QXmlStreamReader::StartElement) {
220             if(reader.name()=="k") {
221                 a = reader.readElementText();
222                 if(a.toLower()==key.toLower())
223                     match = true;
224             }
225         }
226         if(match) {
227             QString temp("");
228             while(reader.name()!="ar" && !reader.atEnd()) {
229                 if(reader.name()!="" && reader.name()!="k") {
230                     if(reader.tokenType()==QXmlStreamReader::EndElement)
231                         temp+=tr("</");
232                     if(reader.tokenType()==QXmlStreamReader::StartElement)
233                         temp+=tr("<");
234                     temp+=reader.name().toString();
235                     if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
236                        temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
237                     temp+=tr(">");
238                 }
239                 temp+= reader.text().toString();
240                 reader.readNext();
241             }
242             if(temp.at(0)==QChar('\n'))
243                 temp.remove(0,1);
244             resultString+=tr("<t>") + temp + tr("</t>");    //.replace("\n","")
245             match=false;
246         }
247         this->thread()->yieldCurrentThread();
248     }
249     stopped=false;
250     dictionaryFile.close();
251
252     return resultString;
253 }
254
255 void XdxfPlugin::stop() {
256     stopped=true;
257 }
258
259 DictDialog* XdxfPlugin::dictDialog() {
260      return _dictDialog;
261 }
262
263 void XdxfPlugin::setPath(QString path){
264     this->path=path;
265     _settings->setValue("path",path);
266     //getDictionaryInfo();
267 }
268
269 CommonDictInterface* XdxfPlugin::getNew(const Settings *settings) const {
270     XdxfPlugin *plugin = new XdxfPlugin();
271     if(settings){
272         plugin->setPath(settings->value("path"));
273
274         QStringList list = settings->keys();
275         foreach(QString key, list)
276             plugin->settings()->setValue(key, settings->value(key));
277
278
279         plugin->db_name = plugin->_settings->value("type")
280                + plugin->_settings->value("path");
281  //       if(!plugin->db.connectionName().isEmpty() || settings->value("generateCache")=="true")
282             plugin->db = QSqlDatabase::addDatabase("QSQLITE", plugin->db_name);
283
284         if(settings->value("cached").isEmpty() &&
285            settings->value("generateCache") == "true") {
286             plugin->makeCache("");
287         }
288     }
289
290     plugin->getDictionaryInfo();
291     return  plugin;
292 }
293
294 bool XdxfPlugin::isAvailable() const {
295     return true;
296 }
297
298 void XdxfPlugin::setHash(uint _hash) {
299     this->_hash=_hash;
300 }
301
302 uint XdxfPlugin::hash() const {
303    return _hash;
304 }
305
306 Settings* XdxfPlugin::settings() {
307     return _settings;
308 }
309
310 bool XdxfPlugin::isCached() {
311     if(_settings->value("cached") == "true")
312         return true;
313     return false;
314 }
315
316 void XdxfPlugin::setSettings(Settings *settings) {
317
318     QString oldPath = _settings->value("path");
319     if(oldPath != settings->value("path")) {
320         setPath(settings->value("path"));
321     }
322
323     if((_settings->value("cached") == "false" ||
324         _settings->value("cached").isEmpty()) &&
325        settings->value("generateCache") == "true") {
326         makeCache("");
327     }
328     else {
329        _settings->setValue("cached", "false");
330     }
331
332     emit settingsChanged();
333 }
334
335 void XdxfPlugin::getDictionaryInfo() {
336     QFile dictionaryFile(path);
337     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
338         qDebug()<<"Error: could not open file";
339         return;
340     }
341
342     QXmlStreamReader reader(&dictionaryFile);
343     reader.readNextStartElement();
344     if(reader.name()=="xdxf") {
345       if(reader.attributes().hasAttribute("lang_from"))
346         _langFrom = reader.attributes().value("lang_from").toString();
347       if(reader.attributes().hasAttribute("lang_to"))
348         _langTo = reader.attributes().value("lang_to").toString();
349     }
350     reader.readNextStartElement();
351     if(reader.name()=="full_name")
352         _name=reader.readElementText();
353     reader.readNextStartElement();
354     if(reader.name()=="description")
355         _infoNote=reader.readElementText();
356
357     QString format = "png";
358     QString initialPath = QDir::currentPath() + tr("/xdxf.") + format;
359 //    qDebug()<<initialPath;
360 //    qDebug()<<QPixmap(":/icons/xdxf.png").save(initialPath,format.toAscii());
361
362     _infoNote="<info path=\""+initialPath+"\">"+"\n" + _name + "(" + _type + ")"  + "</info>";
363
364
365
366     dictionaryFile.close();
367 }
368
369 QString XdxfPlugin::removeAccents(QString string) {
370     string = string.replace(QString::fromUtf8("ł"), "l", Qt::CaseInsensitive);
371     QString normalized = string.normalized(QString::NormalizationForm_D);
372     normalized = normalized;
373     for(int i=0; i<normalized.size(); i++) {
374         if( !normalized[i].isLetterOrNumber() &&
375             !normalized[i].isSpace() &&
376             !normalized[i].isDigit() &&
377             normalized[i] != '*' &&
378             normalized[i] != '%' &&
379             normalized[i] != '_' &&
380             normalized[i] != '?' ) {
381             normalized.remove(i,1);
382         }
383     }
384     return normalized;
385 }
386
387 QIcon* XdxfPlugin::icon() {
388     return &_icon;
389 }
390
391 int XdxfPlugin::countWords() {
392     if(_wordsCount > 0)
393         return _wordsCount;
394
395     QFile dictionaryFile(path);
396     if(!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
397         qDebug()<<"Error: could not open file";
398         return -1;
399     }
400
401     dictionaryFile.seek(0);
402
403     long wordsCount = 0;
404
405     QString line;
406     while(!dictionaryFile.atEnd()) {
407         line = dictionaryFile.readLine();
408         if(line.contains("<k>")) {
409             wordsCount++;
410         }
411     }
412     _wordsCount = wordsCount;
413     dictionaryFile.close();
414     return wordsCount;
415 }
416
417 bool XdxfPlugin::makeCache(QString dir) {
418     cachingDialog->setVisible(true);
419     QCoreApplication::processEvents();
420     stopped = false;
421     QFileInfo dictFileN(_settings->value("path"));
422     QString cachePathN;
423     cachePathN = QDir::homePath() + "/.mdictionary/"
424                  + dictFileN.completeBaseName() + ".cache";
425
426     QFile dictionaryFile(dictFileN.filePath());
427
428
429     if (!dictionaryFile.open(QFile::ReadOnly | QFile::Text)) {
430         return 0;
431     }
432
433     QXmlStreamReader reader(&dictionaryFile);
434
435     db.setDatabaseName(cachePathN);
436     if(!db.open()) {
437         qDebug() << "Database error" << db.lastError().text() << endl;
438         return false;
439     }
440     QCoreApplication::processEvents();
441     QSqlQuery cur(db);
442     cur.exec("PRAGMA synchronous = 0");
443     cur.exec("drop table dict");
444     QCoreApplication::processEvents();
445     cur.exec("create table dict(word text ,translation text)");
446     int counter = 0;
447     cur.exec("BEGIN;");
448
449     QString a;
450     bool match = false;
451     QTime timer;
452     timer.start();
453     countWords();
454
455     int lastProg = -1;
456
457
458     counter=0;
459     while (!reader.atEnd() && !stopped) {
460
461         QCoreApplication::processEvents();
462         reader.readNext();
463
464         if(reader.tokenType() == QXmlStreamReader::StartElement) {
465             if(reader.name()=="k"){
466                 a = reader.readElementText();
467                 match = true;
468             }
469         }
470         if(match) {
471             QString temp("");
472             while(reader.name()!="ar" && !reader.atEnd()) {
473                 if(reader.name()!="" && reader.name()!="k") {
474                     if(reader.tokenType()==QXmlStreamReader::EndElement)
475                         temp+=tr("</");
476                     if(reader.tokenType()==QXmlStreamReader::StartElement)
477                         temp+=tr("<");
478                     temp+=reader.name().toString();
479                     if(reader.name().toString()=="c" && reader.tokenType()==QXmlStreamReader::StartElement)
480                        temp= temp + tr(" c=\"") + reader.attributes().value(tr("c")).toString() + tr("\"");
481                     temp+=tr(">");
482                 }
483                 temp+= reader.text().toString();
484                 reader.readNext();
485             }
486             if(temp.at(0)==QChar('\n'))
487                 temp.remove(0,1);
488             temp=tr("<t>") + temp+ tr("</t>");  //.replace("\n","")
489             match=false;
490             cur.prepare("insert into dict values(?,?)");
491             cur.addBindValue(a);
492             cur.addBindValue(temp);
493             cur.exec();
494             counter++;
495             int prog = counter*100/_wordsCount;
496             if(prog % 5 == 0 && lastProg != prog) {
497                 Q_EMIT updateCachingProgress(prog,
498                                              timer.restart());
499                 lastProg = prog;
500             }
501         }
502     }
503
504     cur.exec("END;");
505     cur.exec("select count(*) from dict");
506
507     countWords();
508     cachingDialog->setVisible(false);
509
510     if(!cur.next() || countWords() != cur.value(0).toInt())
511     {
512         db.close();
513         return false;
514     }
515     _settings->setValue("cache_path", cachePathN);
516     _settings->setValue("cached", "true");
517
518     db.close();
519     return true;
520 }
521
522 Q_EXPORT_PLUGIN2(xdxf, XdxfPlugin)